Java Inheritance

  • Post author:
  • Post category:Java / Java OOP
  • Post last modified:July 7, 2021
  • Reading time:2 mins read

We will one of the most important concept of JAVA OOP is java inheritance.

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability.

We group the “inheritance concept” into two categories:

  1. subclass (child) – the class that inherits from another class
  2. superclass (parent) – the class being inherited from

To inherit from a class, use the extends keyword.

The final Keyword

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

If you try to access a final class, Java will generate an error.

The super keyword

  1. It is used to differentiate the members of superclass from the members of subclass, if they have same names.
  2. It is used to invoke the superclass constructor from subclass.

Differentiating the Members

-code

If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below.

Code_here

Invoking Superclass Constructor

–code

If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below.

Code_here