Inheritance


Inheritance is the main concept of object-oriented programming. Inheritance is the mechanism that provides one class is allowed to inherit features of another class. The class from which we are going to inherit is called the base class and in which class we are inheriting the feature is called the derived class. The main purpose of the inheritance is reusability. We can reuse the already created class by inheriting it in another class. For example, every car has some common functionality like 4 wheels, steering or seats, etc, so we create one class for the car and in every new model of the car we inherit these features as it is. So, it reuses the car class for common features.


public class Car
{
        public void Steering()
        {
            Console.WriteLine("Steering");
        }

        public void Wheels()
        {
            Console.WriteLine("Wheels");
        }

        public void Brakes()
        {
            Console.WriteLine("Brakes");
        }
}

public class TataNexon : Car
{
        public void SoundSystem()
        {
            Console.WriteLine("SoundSystem");
        }

        public void Automatic()
        {
            Console.WriteLine("Automatic");
        }
}

public class TataHarrier : Car
{
        public void SoundSystem()
        {
            Console.WriteLine("SoundSystem");
        }

        public void PetrolOrDiesel()
        {
            Console.WriteLine("PetrolOrDiesel");
        }
}

public class Program
{
        static void Main(string[] args)
        {
            TataHarrier tataHarrier = new TataHarrier();
            tataHarrier.Brakes();
            tataHarrier.Steering();
            tataHarrier.Wheels();
            tataHarrier.SoundSystem();
            tataHarrier.PetrolOrDiesel();

            TataNexon tataNexon = new TataNexon();
            tataNexon.Brakes();
            tataNexon.Steering();
            tataNexon.Wheels();
            tataNexon.SoundSystem();
            tataNexon.Automatic();
        }
}

Different type of Inheritance:
1.      Single Inheritance: One class is inherited from another class means single derived class is inherited from the single base class.
2.      Multilevel inheritance: A derived class is inherited from another derived class. For example, B is derived from A, and C is derived from B.
3.      Multiple Inheritance: A derived class is inherited from multiple base classes. This type inheritance not supported in .net framework.
4.      Hierarchical Inheritance: More than one derived class is inherited from the single base class. For example, A is the base class, B and C are derived classes from A.

Post a Comment

0 Comments