Inheritance
Explore the concept of inheritance in C# to understand how one class can inherit properties and methods from another, enabling code reuse and establishing relationships like car is a vehicle. Discover the use of base and derived classes, implicit casting, and the limitations of inheritance such as single inheritance, sealed classes, and access modifiers. Learn the difference between inheritance and composition, emphasizing modern C# practices favoring composition for flexible and maintainable code design.
Inheritance is a fundamental concept of object-oriented programming. With inheritance, one class can inherit the functionality of another class. This allows us to encapsulate common functionality in a base class and implement specific functionality in derived classes.
The best way to understand inheritance is to see it in action.
Let’s take a Car class as an example:
public class Car{public string Model { get; set; }public decimal Price { get; set; }public int Year { get; set; }public int FuelCapacityInLiters { get; set; }public int FuelLeft { get; set; }public void Drive(){}}
Lines 3–7: We define properties representing the state of the car, such as model, price, and fuel capacity.
Lines 9–11: We define a
Drivemethod representing the car’s behavior.
Our car has a model and price, along with other properties, and can be driven. What if we want to create a Motorcycle class? It also has a price and model and can be driven.
Should we merely copy the code from the Car class to the Motorcycle class?
A better approach is to use inheritance. We can identify properties and methods applicable to both Car and Motorcycle and move them to a base class. We can define this common functionality within a new Vehicle class.
Implementing inheritance
Because the Car and Motorcycle classes have some functionality in common, we create a Vehicle class to hold those common properties and ...