Inheritance in Java (Types with Example) – You Can’t Afford to Miss Out!

Before we begin to talk about inheritance in Java, let us understand a real-life situation here first. Imagine you have an older brother. He has to go off to college and you get all his stuff when he is gone. This simple concept is called inheritance i.e, passing down of values.

Types of Inheritance in Java

Stay updated with latest technology trends
Join DataFlair on Telegram!!

Inheritance in Java

Inheritance in Java is one of the most important topics in Object-Oriented Programming. With the help of this, classes can reuse code from another class. Before we dive into the concepts of Inheritance, we must know a few concepts:

Subclass
This is the class which inherits methods and values from the superclass. It is the child class. It can have methods and values of its own aside from possessing all the variables.

Superclass
This is the class from which the child class inherits all the methods and values. This is the parent class.

Syntax for defining inheritance between two classes:

<child class> extends <parent-class>

Why do we need Inheritance in Java?

Inheritance allows programmers to define a class in terms of another class which enhances code readability and interpretability. This helps in the maintenance of the application. We can also reuse the code from the parent class and also override them according to the needs of the program.

extends Keyword in Java

The extends keyword extends the functionality of the child class by inheriting values from the parent class. It defines an “is-a” relationship. It comes after the class definition and carries the class name of the parent class. The syntax is as follows

<child class> extends <parent-class>

This means that the child class is a type of parent class.

Types of relationships in Java

There are two types of relationships in java. They are:
1. “is-a” relationship
2. “Has-a” relationship”

1. Java “is-a” relationship

An “is-a” relationship gets implemented by inheritance. This means that a certain class is the part of the parent class. This is essential for code reusability. Inheritance is unidirectional which means that the child class is a type of parent class but the inverse is not true. For example, a brush is a tool but all tools are not brushes.
This relationship gets implemented with the help of extends and implements keywords.

2. Java “has-a” relationship

Composition is the other word of the “has-a” relationship. It means that a certain instance of this class has a reference to another class or in the same class. This relationship also helps in code reusability.

For example, A square has edges, A brush has bristles, A cat has a tail. This implementation is possible if we use the new keyword.

Different types of Inheritance in Java

Java supports the following kinds of interfaces:
a. Single Inheritance
b. Multilevel Inheritance
c. Hierarchical Inheritance
d. Multiple Inheritance(Only through Interfaces)
e. Hybrid Inheritance

1. Single Inheritance in Java

In single inheritance, a single child class inherits data and methods from its parent class. In this case, a child class can access all the methods and the variables of the parent class.

Single Inheritance in java

This diagram illustrates a single inheritance where a class B inherits from A.

Java program to illustrate Single Inheritance:

package com.dataflair.javainheritance;
class Father {
  String familyName;
  String houseaddress;
  Father() {
    familyName = "Programmer";
    houseaddress = "Delhi";
  }
}
public class Son extends Father {
  String name;
  Son() {
    name = "Shraman";
  }
  void printdetails() {
    System.out.println("Hey my name is " + this.name + " " + this.familyName + " and I am from " + this.houseaddress);
  }
  public static void main(String[] args) {
    Son s1 = new Son();
    s1.printdetails();

  }
}

Output:

Hey my name is Shraman Programmer and I am from Delhi

2. Multilevel Inheritance in Java

This represents a multi-tier inheritance wherein the child class inherits from a parent class which in itself is a child class to another parent class. A real-life example would be a child inheriting from his father who inherited from his grandfather.

Multilevel Inheritance in Java

This is an example of a multilevel inheritance where C inherits from B and B inherits from A.

Java program to illustrate the use of Multilevel Inheritance:

package com.dataflair.javainheritance;
class GrandFather {
  GrandFather() {
    System.out.println("I am the grandfather!");
  }
}

class Father extends GrandFather {
  String familyName;
  String houseaddress;
  Father() {
    System.out.println("I am the father! I inherit from Grandfather");
  }
}
public class Son extends Father {

  Son() {
    System.out.println("I am the son and I inherit from my father.");
  }

  public static void main(String[] args) {
    Son s1 = new Son();

  }
}

Output:

I am the grandfather!
I am the father! I inherit from Grandfather
I am the son and I inherit from my father.

As you can see when the base class is declared and when the object gets created, it calls the constructor of the base class. However, its parent class’s constructor gets executed first. This is an important concept to understand.

3. Hierarchical Inheritance in Java

In this type of inheritance, a single parent class passes its values and methods to multiple child classes. One class serves as the parent class and the rest of the classes are the child classes.

Hierarchical Inheritance in java

This is an example of hierarchical inheritance where classes B and C inherit from parent class A.

Java program to illustrate Hierarchical Inheritance:

package com.dataflair.javainheritance;
class Father {
  String familyName;
  String houseaddress;
  Father() {
    familyName = "Programmer";
    houseaddress = "Delhi";
  }
}
class Son extends Father {
  Son() {
    System.out.println("I am the Son");
    System.out.println("My family name is " + this.familyName + " and I am from " + this.houseaddress);

  }

}
class Daughter extends Father {
  Daughter() {
    System.out.println("I am the Daughter");
    System.out.println("My family name is " + this.familyName + " and I am from " + this.houseaddress);
  }
}
class Main {
  public static void main(String[] args) {
    Son s = new Son();
    Daughter d = new Daughter();
  }
}

Output:

I am the Son
My family name is Programmer and I am from Delhi
I am the Daughter
My family name is Programmer and I am from Delhi

4. Multiple Inheritance in Java

Multiple Inheritance, as the name suggests, means that multiple child classes can derive from one parent class. It  is not allowed in Java. However, it can be implemented by using Interfaces.

Multiple Inheritance in java

This is an example of multiple inheritance in which class C is inheriting from A and B

Java program to illustrate the use of Multiple Inheritance in Java:

package com.dataflair.javainheritance;
interface first {
  public void firstmethod();
}
interface second {
  public void secondmethod();
}
interface third extends first,
second {
  public void mainmethod();
}

public class MultInheritance implements third {
  public void mainmethod() {
    System.out.println("This is the main interface method");
  }
  public void firstmethod() {
    System.out.println("Hey I am the first method defined the first interface");
  }
  public void secondmethod() {
    System.out.println("Hey I am the second method defined it the second interface");
  }
  public static void main(String[] args) {
    MultInheritance ob = new MultInheritance();
    ob.mainmethod();
    ob.firstmethod();
    ob.secondmethod();

  }

}

Output:

This is the main interface method
Hey I am the first method defined the first interface
Hey I am the second method defined it the second interface

5. Hybrid Inheritance in Java

It is a mix of two or more types of inheritances. However, to implement multiple inheritance inside a hybrid inheritance, you have to use interfaces as Java does not support multiple inheritance.

Hybrid Inheritance in java

This is an example to show hybrid inheritance in Java where there is a combination of two types of inheritance, i.e, Hierarchical, and Multilevel.

Java program to illustrate the use of Hybrid Inheritance:

package com.dataflair.javainheritance;
class A {
  A() {
    System.out.println("I am in class A! I have two children B and C");
  }
}
class B extends A {
  B() {
    System.out.println("I am in class B! I have 1 child D");
  }

}
class C extends A {
  C() {
    System.out.println("I am in class C. I am the child class of A");
  }
}
class D extends B {
  D() {
    System.out.println("I am in D class which is the extension of B class");
  }
}
class Main {
  public static void main(String[] args) {
    D d = new D(); //This calls constructors of parent class A and B
    B b = new B(); //This calls constructors parent class A and B
    C c = new C(); //This calls the constructors class A and C
  }
}

Output:

I am in class A! I have two children B and C
I am in class B! I have 1 child D
I am in the D class which is the extension of B class
I am in class A! I have two children B and C
I am in class B! I have 1 child D
I am in class A! I have two children B and C
I am in class C. I am the child class of A

Important Points Regarding Inheritance in Java

1. Default Superclass

Every class in java is a subclass of one and only one class in Java. There is one exception to this and that is the Object class. The object class does not have any superclass.

2. No Multiple Inheritance in Java

In java, as we already saw, a single class can inherit from one and only one class. Java does not support multiple inheritance. However multiple inheritances are implemented by using interfaces as we saw in the previous example. The reason for Java not supporting multiple inheritance is to avoid ambiguity. There is a popular confusion named as the Diamond problem.

No Multiple Inheritance in java

Look at the figure above, where A is the parent class of B, C, D. Both B and C derive from A and D derives from B and C(Multiple inheritance).

Suppose A has a method called speak(). Now, B and C both has these versions of speak but they decide to overload the method speak() as per their requirements, Now if D wants to use the speak() method which class’s method should it use? B’s or C’s? There lies an ambiguity. That is the diamond problem, hence, Java does not allow multiple inheritance.

3. Constructor Inheritance in Java

Constructors are not inherited into the child classes. However they are inherited with the help of super() keyword.

4. Inheriting Private Members in Java

The subclass cannot access the private members of the parent class.

Note that derived classes, or child classes cannot access the private members of the parent class. However if one of the methods of the parent class uses the private variables, then upon inheriting all the methods from the class, the child class can indirectly access the private variables of the parent class.

Real-life examples of Inheritance in Java

Suppose a Car has two functions: accelerate and brake. Now these functions have different values for different cars as every car has a different acceleration rate and braking mechanisms. So let us take the example of a Mercedes Benz S-Class which is a car. It inherits all the definitions of the class Car. However its acceleration and braking systems are unique.

Let us see a Java program that illustrates this concept.

package com.dataflair.javainheritance;
class Car {
  public void Accelerate() {
    System.out.println("All cars accelerate like this");

  }

  public void Brake() {
    System.out.println("All cars Brake like this");

  }
}
class Mercedes extends Car {
  public void Accelerate() {
    System.out.println("The Mercedes Benz S-class accelerates like this!");

  }

  public void Brake() {
    System.out.println("The Mercedes Benz S-class brakes like this!");

  }
  public static void main(String[] args) {
    Mercedes c = new Mercedes();
    c.Accelerate();
    c.Brake();
  }

}

Output

The Mercedes Benz S-class accelerates like this!
The Mercedes Benz S-class brakes like this!

Power of subclasses

There are many advantages of using subclasses for programming. Some of them are:

a. The subclasses can have new fields that are not in the parent class.
b. Subclasses can use the inherited fields directly.
c. We can write instance methods, i.e, override the methods which have the same name as the superclass method. We can even add a different definition to the function.
d. There is no need to declare separate objects for calling parent class methods.
e. We can declare the method with the same signature as static thus hiding the parent class method.
f. We can define constructors that call the parent class constructor. If we want to do that explicitly, then we have to use the super keyword.
g. The subclass can have methods that are not there in the parent class thus making it a better version of the parent class.

Summary

In this article, we learned about inheritance in java and its use in programming. We also learned about the various types of inheritance and how to implement each one of them.

4 Responses

  1. Ayushi says:

    Thanks for giving these many details on inheritance in Java. I have started my java course online last week. It has got lot of syllabus. Now I have moved to inheritance topic which has objects, inheritance, and types of inheritance. Am finding some topics related to inheritance and java. I got your wonderful article about inheritance and also you have explained types of inheritance with related diagrams. Across your article, the one pictures shows what is inheritance and types of inheritance in java. Excellent summary and looking forward to share with others. Keep updating with the amazing article.

    • DataFlair Team says:

      Hi Ayushi,
      Thank you for such nice feedback on this Java tutorial. We are glad our article helps you in your learnings. We have 100+ Java tutorials, a series of Java interview questions and quizzes in our sidebar you can refer them as well. These interview questions and quizzes help with your practice.
      Keep learning and keep sharing.
      Regards,
      DataFlair

  2. Sudha says:

    This is the best blog I ever seen ..all topics are simple and clear, easy to understand.. thanks a lot .. appreciate for your(all data-flair team) effort and knowledge.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.