Explain Inheritance in C# ?
Answer:
In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects. In inheritance, there will be two classes - base class and derived classes. A class can inherit attributes and methods from existing class called base class or parent class. The class which inherits from a base class is called derived classes or child class. For more clarity on this topic, let us have a look at 2 classes shown below. Here Class Car is Base Class and Class Ford is derived class.
class Car { public Car() { Console.WriteLine("Base Class Car"); } public void DriveType() { Console.WriteLine("Right Hand Drive"); } } class Ford : Car { public Ford() { Console.WriteLine("Derived Class Ford"); } public void Price() { Console.WriteLine("Ford Price : 100K $"); } }
When we execute following lines of code ,
Ford CarFord = new Ford(); CarFord.DriveType(); CarFord.Price();
Output Generated is as given below.
Base Class Car Derived Class Ford Right Hand Drive Ford Price : 100K $
What this means is that, all the methods and attributes of Base Class car are available in Derived Class Ford. When an object of class Ford is created, constructors of the Base and Derived class get invoked. Even though there is no method called DriveType() in Class Ford, we are able to invoke the method because of inheriting Base Class methods to derived class.