Before reading this article, please go through the following articles:
- Object Oriented Programming Using C#: Part 1
- Object Oriented Programming Using C#: Part 2
- Object Oriented Programming Using C#: Part 3
- Object Oriented Programming Using C#: Part 4
- Object Oriented Programming Using C#: Part 5
Inheritance
Dear reader's inheritance means to inherit something from the source. For example a son can inherit habits from his father. The same concept is used in of Object Oriented Programming; it's the second pillar of OOP.
Inheritance enables creation of a new class that inherits the properties from another class or base class and the class that inherits those members is called the derived class. So the derived class has the properties of the base class and its own class properties as well.
Here is a very simple diagram that will explain inheritance:
Example:
using System;
namespace Inheritance
{
class Program
{
public class vehicle
{
public vehicle()
{
Console.WriteLine("I am Vehicle");
}
}
public class car : vehicle
{
public car()
{
Console.WriteLine("I am Car");
}
}
public class truck : vehicle
{
public truck()
{
Console.WriteLine("I am truck");
}
}
public class electric : car
{
public electric()
{
Console.WriteLine("I am electric car");
}
}
public class petrol : car
{
public petrol()
{
Console.WriteLine("I am patrol car");
}
}
static void Main(string[] args)
{
truck tr = new truck();
Console.WriteLine("****************");
petrol pr = new petrol();
Console.WriteLine("****************");
electric el = new electric();
Console.WriteLine("****************");
Console.ReadKey();
}
}
}
Out Put:
In this simple example we have designed a base class, vehicle, and then we derived two classes, car and truck; these are derived classes of the vehicle class. After that we again create two classes derived from the car class. The Patrol and electric classes are derived classes of the car class which is the base class for the derived classes. Then we just create the object of the truck class that automatically calls the base class vehicle and the same for the patrol and electric classes, we create an object of these classes that automatically call the car class and then the car class calls the vehicle class.