Inheritance is a fundamental concept in object oriented programming OOP
that allows a class called the derived class or subclass to inherit properties
and behaviors from another class called the base class or superclass.
Inheritance establishes an is a relationship between classes,
where a
subclass is considered to be a specialized version of its
superclass.
using System;
namespace ConsoleApp1
{
// Base class (superclass) representing a vehicle
public class Transport
{
// Fields
public string ManufacturerName;
public string Model;
public int YearOfManufacture;
// Constructor
public Transport(string manufacturer, string model, int year)
{
ManufacturerName
= manufacturer;
Model = model;
YearOfManufacture = year;
}
// Method
public void DisplayInformation()
{
Console.WriteLine($"Manufacturer: {ManufacturerName}, Model: {Model}, Year of Manufacture: {YearOfManufacture}");
}
}
// Derived class (subclass) representing a car, inheriting from
Transport
public class Car : Transport
{
// Additional field
public int NumberOfDoors;
// Constructor
public Car(string manufacturer, string model, int year, int numberOfDoors)
: base(manufacturer, model, year) // Call base class constructor
{
NumberOfDoors =
numberOfDoors;
}
// Method
public void DisplayCarInformation()
{
DisplayInformation(); // Call
method from base class
Console.WriteLine($"Number of Doors: {NumberOfDoors}");
}
}
class Program
{
static void Main(string[] args)
{
// Create an object of the Car class
Car myCar = new Car("Toyota",
"A",
2024, 1);
// Access inherited members from the base class
myCar.DisplayInformation();
// Access members specific to the derived class
myCar.DisplayCarInformation();
}
}
}