We will discuss Inheritance in C# here. Inheritance is one of the most important concepts in Object Oriented Programming. Inheritance is the ability to create a class from another class. This also provides an opportunity to reuse the code for better functionality of the program. Instead of creating new function and data member, a class can inherit the members of an existing class. The existing class is called as base class and the new class is referred to as derived class.
Lets look at the code below;
static void Main(string args)
Car myCar = new Car();
public void GetPrice()
Console.WriteLine("Base Class method GetPrice");
public void Make()
Console.WriteLine("Base Class method Make");
class Car : Vehicle
In the above code, we have a class Vehicle which is base or parent class. This class has two methods that are GetPrice() and Make(). In these method we use Console.WriteLine() and Console.ReadLine() methods. Console.WriteLine method puts a text on the console window and append a new line at the end. Console.ReadLine method reads the line from the standard input stream.
Then we create a class Car that inherits from Vehicle class that is base class. The colon (:) sign is used to inherit a class from base class. Car class doesn’t have any method but this is inherited from the Vehicle class. So Car class should has access to all methods of Vehicle class. In the Main method, we create an instance of derived class (Car class) by Car myCar = new Car(); and then access the methods of parent class by myCar.GetPrice().
Lets run our program and check. When we run our program, the following given output will generate;
The above output shows us that the derived class has access to all public and protected method of base (parent) class.
Best WordPress Themes and Plugins with Great Team and Support!