Inheritance

Learn about one of the most important topics in OOP: inheritance.

Overview

Inheritance is a fundamental concept of object-oriented programming. With inheritance, one class can inherit the functionality of another class. In other words, it allows programmers to encapsulate some common functionality in a base class, while more specific functionality will be implemented in child 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()
	{
	}
}

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 way to approach our problem would be to make use of inheritance. We should think of properties and methods that are applicable to both Car and Motorcycle and move them to some base class. In our case, all common functionality can be hosted inside the new Vehicle class:

Get hands-on with 1200+ tech skills courses.