C# Hierarchical Inheritance
In C#, Hierarchical Inheritance is a type of inheritance in which a class is derived from more than one class. In this type of inheritance, two or more derived classes inherit properties and methods from a single base class. It is also known as Multi-Inheritance.
Let's understand this with the help of an example.
Example:
1using System; 2 3public class Animal 4{ 5 public void Eat() 6 { 7 Console.WriteLine("Eating..."); 8 } 9} 10 11public class Dog : Animal 12{ 13 public void Bark() 14 { 15 Console.WriteLine("Barking..."); 16 } 17} 18 19public class Cat : Animal 20{ 21 public void Meow() 22 { 23 Console.WriteLine("Meowing..."); 24 } 25} 26 27public class Program 28{ 29 public static void Main() 30 { 31 Dog dog = new Dog(); 32 dog.Eat(); // Calling Eat() method of Animal class through Dog class object 33 dog.Bark(); // Calling Bark() method of Dog class 34 35 Cat cat = new Cat(); 36 cat.Eat(); // Calling Eat() method of Animal class through Cat class object 37 cat.Meow(); // Calling Meow() method of Cat class 38 } 39}
In the above example, we have created a base class Animal
, and two derived classes Dog
and Cat
, which are inheriting the Animal
class. Both derived classes are using the Eat()
method of the Animal
class and implementing their own unique methods.
When we create objects of derived classes, they can access the Eat()
method of the base class using the this
keyword.
This is how we can implement hierarchical inheritance in C#.