Inheritance
Inheritance is a property of OOP (Object Oriented Programming ) language which is used to derive new class from already existed class. There are 5 types of Inheritance,
- Single Inheritance
- Multilevel Inheritance
- Multiple Inheritance
- Hybrid Inheritance
- Hierarchical Inheritance
Single Inheritance
In single inheritance one new class get derived from already existing Base class as in the following figure,
Figure: Single Inheritance
The above example has shown there is one Class A which is base class and another class is Class B which get derived from Class A.
Example
Class Employee
- Int Id;
- String Name;
- Public void Get()
- {
- Console.WriteLine(“Enter the Details of Employee“)
- This.Id = Convert.ToInt32(Console.ReadLine());
- This.Name = Console.ReadLine();
- }
- Public void Display()
- {
- Console.WriteLine(“Id is: ”+This.Id);
- Console.WriteLine(“Name is: ”+This.Name);
- }
- Class Branch: Employee
- String Name, Adress;
- Public void Get()
- {
- Console.WriteLine(“Enter the Branch Value“)
- This.Name = Console.ReadLine();
- This.Adress = Console.ReadLine();
- }
- Public void Display()
- {
- Console.WriteLine(“Name is: ”+This.Name);
- Console.WriteLine(“Name is: ”+This.Adress);
- }
- Class SinInheritance
- Public Void Main()
- {
- Branch Obj = new Branch();
- Obj.Get();
- Obj.Display();
- }
- }
Multilevel Inheritance
Figure: Multilevel Inheritance
In Multilevel inheritance one new class get derived from Base class and another class will get derived from class which has recently derived from base class as shown in above figure. As we can see there are 3 classes Class A ,Class B and Class C in which Class A is Parent class of Class B and Class B is Parent class of Class C.
Example
Class Employee.
- Int Id;
- String Name;
- Public void Get()
- {
- Console.WriteLine(“Enter the Details of Employee“)
- This.Id = Convert.ToInt32(Console.ReadLine());
- This.Name = Console.ReadLine();
- }
- Public void Display()
- {
- Console.WriteLine(“Id is: ”+This.Id);
- Console.WriteLine(“Name is: ”+This.Name);
- }
- Class Branch: Employee
- String BName, Adress;
- Public void Get()
- {
- Console.WriteLine(“Enter the Branch Details“)
- This.BName = Console.ReadLine();
- This.Adress = Console.ReadLine();
- }
- Public void Display()
- {
- Console.WriteLine(“Name is: ”+This.BName);
- Console.WriteLine(“Name is: ”+This.Adress);
- }
- Class Salary: Branch
- Double Salaries;
- Public Void Get()
- {
- Console.WriteLine(“Enter The Salary Details: ”);
- This.Salaries = Convert.ToDouble(Console.ReadLine());
- }
- Public Void Display()
- {
- Console.WriteLine(“Salary is: ”+This.Salaries);
- }
- Class MultiLevelInheritance
- Public Void Main()
- {
- Salary Obj = new Salary();
- Obj.Get();
- Obj.Display();
- }
- }
Point To Remember
Inheritance is one of the property of oops which is used to derive new class from already existing class.