Understanding OOP Concepts: Inheritance

Last modified on February 22, 2020 37 sec read

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() {
        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";

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.

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.