Java Inheritance

Inheritance in Java refers to the ability of child classes to inherit or acquire all the non-private properties and behaviors from the parent class. Inheritance is one of the four pillars of object-oriented programming and is used to promote code reusability among the classes in a hierarchy.

In this tutorial, we will learn about inheritance types supported in Java and how inheritance is implemented in an application.

1. What is Inheritance in Java?

In inheritance, a class extends another class to inherit all its non-private members, by default. This class is called the child class or subclass. The class from which the child class extends is called the parent class or superclass.

In Java, extends keyword is used for inheritance between classes.

public class Parent {
}

public class Child extends Parent {    //Child class is extending the Parent class
}

2. Inheritance in Action

Suppose we have Employee class. The Employee class has some attributes and methods which all employees must have within the organization.

In the same application, there can be other special employees as well e.g. Manager. Managers are regular employees of the organization, but additionally, they have few more attributes over other employees, e.g., reportees or subordinates.

public class Employee {

    private Long id;
    private String firstName;
    private String lastName;

    //Getters and Setters
}
public class Manager extends Employee {

  private List<Employee> subordinates;

  public Manager(long id, String firstName, String lastName, List<Employee> subordinates) {

    super(id, firstName, lastName);
    this.subordinates = subordinates;
  }
}

In the above implementation, employees have common attributes like id, firstName and lastName; while manager has the specialized subordinates attribute only. To inherit all non-private members from Employee class (in this case, getter and setter methods), Manager extends the Employee class.

Let us verify that Manager class inherits the Employee attributes as well.

Manager manager = new Manager(1l, "Lokesh", "Gupta", List.of(new Employee(2l, "Alex", "Dave")));
System.out.println(manager);

Program Output.

Manager{id=1, firstName='Lokesh', lastName='Gupta', subordinates=[Employee{id=2, firstName='Alex', lastName='Dave'}]}

Clearly, Manager class is able to use the fields and methods of the Employee class.

Now consider if we do not use inheritance. Then we would have maintained the id, firstName and lastName fields in both classes. It would have caused code duplication which always create problems in code maintenance.

3. Types of Inheritance

In Java, inheritance can be one of four types – depending on class hierarchy.

  • Single inheritance
  • Multi-level inheritance
  • Hierarchical inheritance
  • Multiple inheritance

3.1. Single Inheritance

In single inheritance, one child class extends one parent class. The above example code (Employee and Manager) is an example of single inheritance.

Java Single Inheritance
Single Inheritance

3.2. Multi-level Inheritance

In multilevel inheritance, there will be inheritance between more than three classes in such a way that a child class will act as the parent class for another child class. Let’s understand with a diagram.

Multilevel Inheritance
Multilevel Inheritance

In the above example, Class B extends class A, so class B is a child class of class A. But C extends B, so B is the parent class of C. So B is parent class as well as child class also.

3.3. Hierarchical Inheritance

In hierarchical inheritance, there is one superclass, and more than one subclasses extend the superclass.

Hierarchical Inheritance
Hierarchical Inheritance

These subclasses B, C, D will share the common members inherited from A, but they will not be aware of members from each other.

3.4. Multiple Inheritance

In multiple inheritance, a child class can inherit the behavior from more than one parent classes.

Multiple inheritance
Multiple inheritance

In the diagram, class D extends classes A and B. In this way, D can inherit the non-private members of both classes. But, in Java, we cannot use extends keyword with two classes. So, how will multiple inheritance work?

Till JDK 1.7, multiple inheritance was not possible in java. But from JDK 1.8 onwards, multiple inheritance is possible via use of interfaces with default methods.

4. Accessing Members of Parent Class

In a child class, we can access non-private members of parent classes. Let’s see how individual members can be accessed.

4.1. Constructors

Constructors of parent class can be called via super keyword. There are only two rules:

  • super() call must be made from the child class constructor.
  • super() call must be the first statement inside the constructor.
public class Manager extends Employee {

    public Manager() {
        super();  //This must be first statement inside constructor

        //Other statements
    }
}

4.2. Fields

The non-private member fields can be inherited in the child class. We can access them using dot operator e.g. manager.id. Here id the attribute is inherited from the parent class Employee.

The private member fields must be accessed via the public getter and setter methods.

Manager manager = new Manager(...);

manager.getId();
manager.getFirstName();
manager.getLastName();

We must be careful when dealing with fields with the same name in parent and child classes. Remember that member fields cannot be overridden. Having the same name field will hide the field from the parent class – while accessing via the child class.

In this case, the attribute accessed will be decided based on the reference type. For example, suppose that Employee and Manager have a common attribute rating. When we invoke manager.rating then the value received will be decided by the reference type.

class Employee {

  int rating = 100;
}

class Manager extends Employee {

  int rating = 200;
}

Manager manager = new Manager();
System.out.println(manager.rating);   //200

Employee mgrEmployee = new Manager();
System.out.println(mgrEmployee.rating);   //100

In the above example, even though we are creating the instance of Manager both times, the value of rating is different because it is being referred from the reference type.

4.3. Methods

Child classes can directly access the non-private methods of the parent class using this keyword. A child class cannot access the private methods of the parent class.

In the following example, Manager class is able to access the public getter and setter methods in the toString() method.

public class Manager extends Employee {

  private List<Employee> subordinates;

  @Override
  public String toString() {

    return "Manager{" +
        "id=" + getId() +
        ", firstName='" + getFirstName() + '\'' +
        ", lastName='" + getLastName() + '\'' +
        ", subordinates=" + subordinates +
        '}';
  }
}

Note that if the parent and child classes have a non-private method with the same name, then the method accessed will be from the actual instance type.

class Employee {

  public int getRating() {
    return 100;
  }
}

class Manager extends Employee {

  public int getRating() {
    return 200;
  }
}

Manager manager = new Manager();
System.out.println(manager.getRating());   //200

Employee mgrEmployee = new Manager();
System.out.println(mgrEmployee.getRating());   //200

5. Conclusion

Let’s summarize what we learned about inheritance in Java:

  • Inheritance is also known IS-A relationship.
  • It allows the child class to inherit non-private members of the parent class.
  • In java, inheritance is achieved via extends keyword.
  • From Java 8 onward, you can use interfaces with default methods to achieve multiple inheritance.
  • Member fields are accessed from the reference type class.
  • Member methods are accessed from actual instance types.

Drop me any questions, you might have, in the comments section.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial