Get startedGet started for free

Centralising code with inheritance

1. Centralising code with inheritance

We will now explore Inheritance, a core element of the OOP programming paradigm, and its implementation in Java.

2. Working with multiple classes

Consider a Toyota class and a Honda class for two types of cars. Each car has common properties such as model, color, and license plate. If we create a new Mercedes class, we would need to define the same properties again, leading to repetitive code as we add more car classes for different car types. Inheritance in OOP helps us solve this problem. It helps us consolidate shared code in one place, allowing classes to utilize common features without rewriting code.

3. The power of inheritance

To illustrate, we can create a Car class that contains all the shared properties and methods, such as model, color, and license plate. We then define our Toyota class using the extends keyword to inherit from the Car class. Inheritance is established by adding the extends keyword after the class name, followed by the base class name from which we want to inherit.

4. Introducing base class

In OOP terminology, the class that contains the shared code, from which other classes inherit, is called the Base class or Parent class. In this example, the Car class serves as the base class, containing the shared code from which other classes can be composed.

5. Inheriting with subclasses

The class derived from a base class is called a subclass or Child class. In our scenario, the Toyota class is a subclass of the Car class. Within the Toyota class constructor, we call the super() method and pass the parameters needed for the Car base class. The super() method must be called in the subclass's constructor for Inheritance to function correctly in Java. The "is-a" phrase can help clarify the purpose of Inheritance. A Toyota is a car, just like a Honda is a car. If you find yourself using the phrase "is-a" when defining classes that share code, Inheritance is likely the solution you need.

6. Creating inheritance instances

When we create an instance of the Toyota class, we can access and print the color property inherited from the Car class. The color property is not defined within the Toyota class, but any instance of Toyota can access it because the Toyota class inherited that property from the Car class.

7. Let's practice!

Inheritance is crucial in OOP, but using it excessively can make designs more complicated than necessary. The need for Inheritance will become evident when it arrives and you find yourself duplicating code. It's time for you to create your own base classes and implement Inheritance.