Types of Inheritance – Free C# Tutorials

Types of inheritance

In the previous blog we saw about simple inheritance here we in detail about the types of inheritance namely, Multilevel and hierarchical inheritance.

Multilevel Inheritance in c#

  • A common requirement in object-oriented programming is the use of a derived class as a super class. C# supports this concepts and uses extensively in building it’s class library.
  • This concept allows us to build  a chain of classes.
  • The class A serves as the base class for the derived class B which in turn serves as the base class for the derived class C. The chain ABC is known as the inheritance path.

A derived class with multilevel base class are declared as follows:

class A
{
}
class B: A // first level declaration
{
}
class C : B // second level declaration
{
}
  • This process may be extended to any number of levels.The class C can inherit the members of both A and B.
  • As discussed earlier,the constructors are executed from the  top downwards, with the bottom most constructors being executed last.Example:

 

Class A
{
  protected int a;
  public A  ( int x )
  {
    a = x;
  }
}
class B:A
{
   protected int b;
   public B ( int x , int y ) : base (x)
   {
     b =y ;
   }
}
class C:B
{
   int c;
   public C ( int x , int y , int  z ) : base (x,y)
   {
     c= z;
   }
}

The constructors are implemented in the following order:

A() // class A

B() // class B

C() // class C

  • Note that we have used base in both the derived classes without specifying the actual name of the base class. Since c# supports only single inheritance , base means  the immediate base class constructor.
  • However, it should be seen that we place  arguments in proper order so that correct values are passed to the data members.

Hierarchical Inheritance in c#

  • Another interesting application of inheritance is to use it as a support to the hierarchical inheritance design of the program.
  • Many programming problems can be cast into an hierarchy where certain features of one level are shared by many other below  levels.

The following figure shows the hierarchical inheritance.

The following figure shows a hierarchical classification of accounts in a commercial bank.This is possible because all the accounts posses some common features:

 

This is all about the inheritance in C#.

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *