Inheritance

Lesson 31
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

Inheritance is a concept in object-oriented programming where a class can inherit properties and methods from another class. The class that is inherited from is called the parent class or superclass, and the class that inherits from it is called the child class or subclass.

To create a subclass in C#, we use the : symbol followed by the name of the parent class. For example:

class Vehicle {
   public void Drive() {
      Console.WriteLine("Driving...");
   }
}

class Car : Vehicle {
   public void Accelerate() {
      Console.WriteLine("Accelerating...");
   }
}

In this example, we have a parent class called Vehicle that has a method called Drive(). We also have a child class called Car that inherits from the Vehicle class using the : symbol.

The Car class also has its own method called Accelerate(). Since it inherits from the Vehicle class, it also has access to the Drive() method.

We can create objects of both classes and call their respective methods:

Vehicle myVehicle = new Vehicle();
myVehicle.Drive();

Car myCar = new Car();
myCar.Accelerate();
myCar.Drive();

In this example, we create an instance of the Vehicle class called myVehicle and call its Drive() method. We also create an instance of the Car class called myCar and call its Accelerate() method as well as the inherited Drive() method from the Vehicle class.