C# Inheritance Basics
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class to inherit properties and methods from an existing class. This promotes code reusability and establishes a clear hierarchical relationship between classes, often referred to as a "is-a" relationship.
What is Inheritance?
In C#, the class that is inherited from is called the base class (or parent class), and the class that inherits is called the derived class (or child class). The derived class automatically gains access to the non-private members (fields, properties, methods) of its base class.
Syntax for Inheritance
To indicate that a class derives from another, you use a colon (:
) followed by the name of the base class after the derived class name.
public class Vehicle
{
public string Make { get; set; }
public string Model { get; set; }
public virtual void StartEngine()
{
Console.WriteLine("Engine started.");
}
}
public class Car : Vehicle
{
public int NumberOfDoors { get; set; }
// Override the base class method
public override void StartEngine()
{
Console.WriteLine("Car engine started smoothly.");
}
}
Key Concepts
- Base Class (Parent Class): The class from which members are inherited.
- Derived Class (Child Class): The class that inherits members from the base class.
virtual
Keyword: Used in the base class to indicate that a method can be overridden by a derived class.override
Keyword: Used in the derived class to provide a specific implementation for a method inherited from the base class.- Single Inheritance: C# supports single inheritance for classes, meaning a class can only inherit from one direct base class.
Example Usage
Let's see how we can use the Car
class that inherits from Vehicle
:
using System;
public class Program
{
public static void Main(string[] args)
{
// Create an instance of the derived class
Car myCar = new Car();
myCar.Make = "Toyota";
myCar.Model = "Camry";
myCar.NumberOfDoors = 4;
Console.WriteLine($"Car: {myCar.Make} {myCar.Model}");
Console.WriteLine($"Doors: {myCar.NumberOfDoors}");
// Call the inherited method (overridden version)
myCar.StartEngine();
// We can also use a base class reference to a derived class object
Vehicle genericVehicle = myCar;
genericVehicle.StartEngine(); // Still calls the overridden Car.StartEngine()
}
}
Benefits of Inheritance
- Code Reusability: Avoids redundant code by defining common functionality in a base class.
- Extensibility: New classes can be created that extend the functionality of existing ones without modifying the original code.
- Polymorphism: Enables treating objects of derived classes as objects of their base class, leading to more flexible and maintainable code.
Inheritance is a cornerstone of object-oriented design. Understanding how to effectively use it will significantly improve your C# programming skills.