MultiLevel Inheritance in C#
Inheritance Used in C# for inherit methods and variable of base class. Multilevel Inheritance in C# allow us to use base class functions in various classes that inherits from base class. Today we will write code that describe you working of MultiLevel Inheritance in C#
MultiLevel Inheritance in C#
Inheritance is concept of OOP based Languages. Multilevel inheritance in C#,a class inherits the variables and methods from class above it.ok now look on this code and then i will describe you what's going on in this code:
using System;
using System.Collections.Genric;
using System.Text;
namespace CSharpMulti
{
class Program
[
static void Main(string[]args)
{
DerivedClass dob= new DerivedClass3();
Base baseRef;//it is base class reference
baseRef = dob;
baseRef.newFunction();
}
}
class Base
{
//create virtual method in base class
public virtual void newFunction()
{
Console.WriteLine("newFunction() in Base class.");
}
}
class DerivedClass1:Base
{
//override newFunction in derived class
public override void newFunction()
{
Console.WriteLine("newFunction() in First Derived Class.");
}
}
class derivedClass2:DerivedClass1
{
public override void newFunction()
{
Console.WriteLine("newFunction() in second Derived Class.");
}
}
class DerivedClass3:DerivedClass2
{
//this class does not override newFunction
}
}
IN Above given code,Derivedclass2 class inherits from the DerivedClass1 class.The derivedClass1 class on the other hand inherit from another class,base.
OUTPUT of this code will be->
newFunction() in second derived Class.
Press any key to continuee..
We can reuse the method, properties of existing any class and this facility can be given through Inheritance. Inheritance can be divided into 5 type. These are given below:
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Here I'll give description briefly with example about Multilevel Inheritance. We know that Inheritance is nothing but relationship among multiple classes. Suppose, class clsBranchOffice is defined by using method, properties of another class clsHeadOffice. In this case, clsHeadOffice is called Base class and clsBranchOffice is called Derived class. In this way more class clsRegonalOffice can be derived by using method, properties of clsHeadOffice, clsBranchOffice. The mechanism of using the multiple class is called Multilevel Inheritance.
Base Class---Derived Class---Derived Class