Understanding OOP Concepts: Inheritance

Last modified on February 22, 2020 37 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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.

Author

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

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *