Pages

Thursday, March 6, 2014

Introduction to OOP (Object Oriented Programming) - Inheritance

Objective

  • To be able to understand Inheritance
  • To be able to define a base class and base class
  • To implement Inheritance in C#

INHERITANCE

-Is one of the Pillars of OOP (Object Oriented Programming) which are Inheritance, Encapsulation and Polymorphism. Today, we are just going to tackle Inheritance which allows us to reuse, extend and modify the behavior that is defined in another class.

base class / parent class - The class whose members are inherited
derived class / child class - class that inherits the base class / parent class

in C#, all classes are derived from a base class Object (this provides low-level support to all classes).

to inherit a class we use ":".

public class ChildClass : ParentClass{}

by default all class can be inherited.
We can specify that a class cannot be inherited by using the keyword sealed


public sealed class ChildClass : ParentClass{}
in this way no other class can inherit the ChildClass
if you try inheriting a sealed class you will be having a compile time error 'cannot derived from sealed type' error.
to define that a class can only be inherited and cannot be instantiated (creating an instance of) we use the abstract
public abstract class ParentClass{}
in this scenario, we cannot create an instance of the ParentClass, we can only inherit it. If we try creating an instance of ParentClass we will have a 'Cannot create an instance of the abstract class or interface' error.
For our Exercise/Example:
  1. Create abstract class Transportation with properties: string Color, int NoOfWheels; and method Move() - that writes in a console with message "moved".
  2. Create a new class Car and inherit Transportation.
  3. In the Main Program Create an Instance of Car and fill-up the properties and call the Move() method in the created Car instance.
The Code:
Transportation Class:
public abstract class Transportation{
    //Properties
    public string Color {get; set;}
    public int NoOfWheels {get; set;}

    //Method
    public void Move(){
       Console.WriteLine(string.Format("the {0} transportation with {1} wheel/s moved!", this.Color, this.NoOfWheels));
    }
}

Car class inhereting Transportation Class:
public class Car : Transportation{}

The Program where we create an instance of Car and Call the Move() Method:
public class Program{
   Car car = new Car()
   {
   Color="Red",
   NoOfWheels = 4
   }

   car.Move();
}
Points to Remember:
  • a class can only inherit one(1) class
  • we cannot inherit a sealed class
  • we cannot create an instance of an abstract class
References:
  • http://msdn.microsoft.com/en-us/library/dd460654.aspx

No comments:

Post a Comment