Understanding OOP Concepts: Inheritance

avatar
Published: Feb 16, 2020 - Updated: Mar 16, 2022

Inheritance is a mechanism in which one class acquires the properties and methods of another class.

The class being inherited from is called super (parent, base) class and the class that inherits from another class is named sub (child, derived) class.

To inherit from a class, we have to use the extends keyword.

Example in Java

Let’s see an example in Java. We’re going to make a superclass named Car.

public class Car {
    String brand;
    String color;

    void displayInfo() {
        System.out.println("Car brand is " + brand + ". It's color is " + color);
    }
}

Now we’ll extend the Car class to another class:

public class AnotherClass extends Car {

    public void withExtraInfo() {
        displayInfo();
        System.out.println("The car has Sunroof\n");
    }

    public static void main(String[] arg) {
        AnotherClass audi = new AnotherClass();
        audi.brand = "Audi a3";
        audi.color = "Red";
        audi.withExtraInfo();
    }
}

The final Keyword

If we don’t want other classes to inherit from a class, we have to use the final keyword:

final class Car {
  ...
}

class AnotherClass extends Car {
  ...
}

If we run this program, we’ll see an error message.

Comments

No comments yet…