Inheritance C# example – In inheritance relationship in C#, a class can access fields and methods of an existing class.
Existing class is known a as base class or parent class. The class that access the features i.e. fields and methods is known as subclass, derived class or child class.
Child class use “:” operator to inherit feature of parent class e.g. class Son : Father{}
Example of Inheritance in C#
Let’s consider an example,
A son wants to use his father’s home and car and he has his own mobile only. So, the son can access his father’s home and car.
So, Father is the parent class and Son is the child class.
C# Code:
/*
* Example of java inheritance
*
*/
//base / parent class
class Father
{
public void home()
{
Console.WriteLine("Father's home");
}
public void Car()
{
Console.WriteLine("Father's Car");
}
}
//Inherit /derived / extends
class Son : Father
{
public void mobile()
{
Console.WriteLine("Son's mobile");
}
}
/*
* Test inheritance
*/
class Program
{
static void Main(string[] args)
{
Son s = new Son();
s.mobile();
s.Car();
s.home();
}
}
Output:
Father’s Home
Father’s Car
Son’s mobile
Types of Inheritance in C#
Following types of inheritance are available in C# language.
Single Inheritance :Single inheritance is just a parent and child class relationship. There should be one base class and one child class only…Single Inheritance in C#.
Multilevel Inheritance: Multilevel inheritance C# program example- In Multilevel inheritance, a class is derived from another class which is also derived from some another class … For example class C : class B and class B : class A then this type of inheritance is known as multilevel inheritance….Multilevel inheritance in C#.
Hierarchical Inheritance: When more than one classes inherit the same class is known as hierarchical inheritance…Hierarchical Inheritance in C#.
Hybrid Inheritance: In hybrid inheritance, we use mixed of different types of inheritance relationship in C# program. For example, we can mix multilevel and hierarchical inheritance etc…. Hybrid inheritance in C#.
Multiple inheritance: Multiple inheritance in C# program can be implemented using interfaces not classes. C# does not support multiple inheritance using classes…Multiple inheritance in C#.
Advantage of Inheritance:
Main advantage of inheritance principle in C# is RE- USABILITY. Meaning, use the existing class features already written by inheriting it in a new class.
Refresh…:
Parent class is also known as Base class / Super class
Child class is also known as Derived class /Sub class
Child class uses “extends” keyword to inherit a base class.
Child class cannot inherit private methods of parent.