Sunday, June 28, 2020

C# Tutorial 15 - Inheritance in C#

C# Tutorial 15 - Inheritance in C#


 A main concept in Object Oriented Programming is inheritance. It allows us to speed up implementation time as we can reuse already existing code and allows us to inherit fields and members of another class. Instead of writing new code we look for existing code, and inherit it in our new code. C# does not supports multiple inheritance it only supports multilevel inheritance.
  • Child/Derived Class - a class that inherits another class is derived or child class.
  • Parent/Base Class - a class being inherited from is called parent or base class.
The general syntax for inheriting a class in C# is as follow:
class derived-class : base-class  
{  
   // methods and fields  
   .
   .
} 
By default members of a class are private and private members are not inherited while inheriting a class. In order to inherit members using inheritance, you can set them internal or protected internal. We have discussed access modifiers in previous tutorials.. Now, consider a class Vehicle which have three fields engine number, model and color and there is another class with name Car which is inheriting this Vehicle class
class Vehicle // Base class 
{  
   internal int engine_no;
   internal string color;
  
internal string model;
}
class Car : Vehicle // Derived class
{
    int power;
    string company;
    public void showDetails()
    {
        Console.WriteLine("Engine No.: "+engine_no);
        Console.WriteLine("Color is: "+color);
        Console.WriteLine("Model: "+model);
        Console.WriteLine("Power: "+power);
        Console.WriteLine("Engine No.: "+
company);    
    }
}
class Program    // Main Class
{
    public static void Main()
    {
        Car c1 = new Car();
        c1.engine_no = 12345;
        c1.color = "blue";
        c1.model = "Benz";
        c1.power = 2000;
        c1.company = "
Mercedes";
        c1.showDetails();
    }
}
As mentioned before, C# does not supports multiple inheritance but multilevel inheritance. If
you want to achieve multiple inheritance, you can do so by using interfaces. We will discuss
interfaces upcoming tutorials. A general example of multilevel inheritance is given below:
class A  
{  
   // methods and fields in class A
   .
   .
} 

//Inherits fields and members of class A
     class B : A  
     {  
        // methods and fields in class B 
        .
        .
     }         
     //Inherits fields and members of class B
     // and B also contains fields and members of class A
class C : B  
{  
    // methods and fields in class C
    .
    .
}



No comments:

Post a Comment