Java is an Object Oriented Programming language and OOP has multiple pillars like Abstraction, Encapsulation, Polymorphism, and Inheritance. Inheritance is the concept used in real life to explain the relationship between parents with their children. The child may contain the attributes of one or both parents but the parent doesn’t acquire any attribute from the child. Java uses the same concept in the OOP with the help of classes and objects to access the code.

  • How IS-A Relation Work in Java
  • How to Implement Inheritance in Java
  • Types Of Inheritance in Java
  • Why is Inheritance Important in OOP

How IS-A Relation Work in Java

Inheritance in OOP uses IS-A relation which creates a unidirectional relation among two or more classes. Unidirectional relation means that an Apple is a fruit but the fruit is not an apple as it is the one-way traffic only. The following components explain how IS-A relation works in Inheritance within the Java programming language:

Super/Parent Class: has the attributes(variables/methods) that can be used by the child or subclass 

Sub/Child Class: uses the attributes or a block of code from the parent class with its own attributes

Object: is the reference to the class and the child’s object can be used to access the body of the parent class.

How to Implement Inheritance in Java

Java programming language allows the use of the “extends” keyword to implement the Inheritance approach of OOP. Using the Inheritance feature in OOP requires the creation of the parent class and a child class that extends the parent class. After that, create an object of the child class in the main class and access the parent’s attributes using the object.

Syntax:

class SuperClass{

}
class SubClass extends SuperClass{

}
  • In the above code block, the SubClass inherits the SuperClass using the extends keyword.
  • The extends keyword creates a relation between both classes and enables access to the Parent’s Class code using the Child class.

Example: Inheritance in Java With Super Keyword

The following code block creates a parent class and a child class. The Person class is the parent class as it can store information that could be useful for every person like name. The Student class is the Child class that extends the Person class to access its attributes or functionalities as demonstrated below:

import java.util.Scanner;
class Person{
    Scanner ins = new Scanner(System.in);
    protected String name;
    public void inputData(){
        System.out.println("Enter Name :");
        name = ins.next();
    }
    public void display(){
        System.out.println("Name: "+this.name);
    }
}
class Student extends Person{
    Scanner ins = new Scanner(System.in);
    private int rno;
    public void inputData(){
        System.out.println("Enter Roll no :");
        rno = ins.nextInt();
        super.inputData();
    }
    public void display(){
        System.out.println("-------Output-------");
        System.out.println("Roll No: "+this.rno);
        super.display();
    }
}
public class Inheritance {

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.inputData();
        s1.display();
    }
}
  • The above example imports the Scanner class to get the input from the user.
  • The Person class contains the variable called name and a couple of methods to get input and display it on the screen.
  • The Student class defines a variable and two methods to get the roll number from the user and display() method to print values when called.
  • Both classes contain the inputData() and display() methods with the same name which is the overriding concept and it is resolved using the super keyword.
  • The super keyword is used in both the methods of the child class to get the reference of the methods used in the parent class.
  • Finally, create an object of the child class in the main method using the new keyword.
  • Use the object to call the methods of the child class only to access both child and parent classes.

Output

Types Of Inheritance in Java

Types of inheritance explain the structure of the relationship between the parent and child classes or how they are connected. Inheritance in OOP has 5 different types or ways of representation which are mentioned below:

  • Single Inheritance
  • Multi-Level Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance
  • Hybrid Inheritance

Single Inheritance

In this type of inheritance, there is only one Child class that extends the single Parent class and it is the basic structure of the inheritance:

Code:

The following code explains a general phenomenon of life as the child gets the name of his father as his last name:

class Father{
    void FName(){
        System.out.println("Bailey");
    }
}
class Child extends Father{
    void Name(){
        System.out.print("George");
    }
}
public class Inheritance {
    public static void main(String[] args) {
        Child c = new Child();
        System.out.print("Full Name of the child is: ");
        c.Name();
        c.FName();
    }
}
  • Start the code by defining the Father class with a method named FName() that prints the name of the father when called.
  • After that, build the Student class that extends the Father class with the Name() function to display the name of the child.
  • Finally, create the object of the child class in the main class to call the methods with the object to print the complete name.

Output

The following snippet displays the complete name of the child by getting the last name from the Father class:

Multi-Level Inheritance

The multi-level inheritance is the process of building the connection on multiple levels as the Parent class extends the GrandParent class. It has been a single inheritance until now, but the difference comes when the Child class extends the Parent class and another class might extend the Child class as well. This method refers to the multi-level inheritance as each new child class adds another level to the structure:

Code:

The following code contains the multi-level structure of inheritance in Java language taking the example of a mobile phone. A mobile phone has many manufacturing companies and each company has different models they have deployed in the market. Each model has multiple features like price, RAM, storage, and others:

class Mobile{
    void manufacturer(){
        System.out.println("Mobile: OnePlus\n\n");
    }
}
class Model extends Mobile{
    void set(){
        System.out.println("Model: SevenPro\n\n");
    }
}
class Feature extends Model{
    void price(){
        System.out.println("Price: 109,000");
    }
}
public class Inheritance {
    public static void main(String[] args) {
        Feature f = new Feature();
        f.manufacturer();
        f.set();
        f.price();
    }
}
  • Build the first parent class named Mobile that contains the manufacturer() method with the name of the company.
  • Define the Child class named Model that extends the Mobile class to get the models offered by the manufacturer.
  • Create another class named Feature that extends the Model class making it a Parent class as well.
  • Here, the Model class is the Parent of the Feature class and the Child of the Mobile class at the same time making the process multi-level.
  • The Feature class contains the price() method that prints the price of the model on the screen.
  • Creating an object of the Feature class in the main method to call the methods of all the classes.

Output

Hierarchical Inheritance

In this type of inheritance, multiple child classes are inheriting or extending a single parent. A single parent can be accessed by multiple child classes, but all the child classes should have their separate objects. The structure of the hierarchical inheritance is displayed in the following snippet:

Code:

The following code uses the Hybrid and Electronic car manufacture companies and both of them are the the children of the CarManufacturer class:

class CarManufacturer{
    void company(){
        System.out.println("Car Manufacturer");
    }
}
class HybridVehicle extends CarManufacturer{
    void car(){
        System.out.println("-----Calling the First Child-----");
        System.out.println("Audi");
    }
}
class ElectronicVehicle extends CarManufacturer{
    void car(){
        System.out.println("\n-----Calling the Second Child-----");
        System.out.println("Tesla");
    }
}
public class Inheritance {
    public static void main(String[] args) {
        HybridVehicle h1 = new HybridVehicle();
        h1.car();
        h1.company();
       
        ElectronicVehicle h2 = new ElectronicVehicle();
        h2.car();
        h2.company();
    }
}
  • Build the class with the name CarManufacturer that contains the company() method which displays the “Car Manufacturer” message when called.
  • Create two child classes named HybridVehicle and ElectronicVehicle displaying the names of their respective makers in the car() method:
  • Create the object of the first child which is the HybridVehicle and call its method and the parent’s method.
  • Create another object which is for the second child class, ElectronicVehicle, to call the method of the parent and its own.

Output

The following screenshot displays the parent class called with both the child classes separately to explain the hierarchical structure of the inheritance: 

Multiple Inheritance

Another type of inheritance allowed by OOP that is not directly usable with classes in the Java programming language. Multiple inheritances may end up creating the overriding problem that occurs when multiple classes have the same method name. When such a function is called in the main method, the compiler gets confused about which method to call. To avoid such ambiguities with complex solutions, java offers the use of interfaces instead of classes.

The interface doesn’t inherit the classes and it doesn’t allow the creation of its objects to be called. The object of the interface can’t be created because it doesn’t use the constructor, so it needs a class to implement the block of code written in it. Its variables are public, static, and final and they can’t be modified or changed:

Code:

The following code creates two interfaces called Father and Mother and uses the implements keyword to create their Child class. The Child class uses the attributes of its parent classes with its own methods and attributes:

interface Father{
    String name = "Snow";
}
interface Mother{
    String HairColor = "Black";
    void display();
}
class Child implements Father, Mother{
    public void display(){
        System.out.println("Name is: John "+name);
        System.out.println("Hair Color is: "+HairColor);
    }
}
public class Inheritance {
    public static void main(String[] args) {
        Child c = new Child();
        c.display();
    }
}
  • The two interfaces in the code are used to get the name and HairColor variables respectively.
  • Build the Child class that implements both the parent interfaces differentiated by the comma(,) and defines the display() method. 
  • The display() method is also created in the Mother interface with the HairColor attribute and the child class uses both interfaces while defining the method.
  • Create the object of the child class in the main() method to call the display() method using it.

Output

Hybrid Inheritance

This inheritance type is the combination of any two types of inheritances like Single/Hierarchical, Multiple/Hierarchical inheritances, etc. The latter combination might create a diamond problem which occurs in Java because multiple inheritance is not supported by the language. We can use Hybrid inheritance with the help of interfaces to inherit children of multiple parents:

Code:

The following code block implements the Hybrid inheritance using the structure of the above picture. It takes the example of finding the marks obtained by the student in the examination for the theory and practical. The Result(GrandChild) class simply takes the marks from its parent classes and displays the final result on the screen in a structured form:

class Paper{
    int rno = 101;
    int practical = 45;
}
class ObtainedMarks extends Paper{
    int theory = 87;
    int pm = theory + practical;
}
interface TotalMarks
{
    int pmark = 150;
    void display();
}

class Result extends ObtainedMarks implements TotalMarks
{

    public void display()
    {
        System.out.println("Roll = "+rno);
        System.out.println("Marks in Theory = "+theory);
        System.out.println("Marks in Practical = "+practical);
        System.out.println("Obtained Marks = "+pm);
        System.out.println("Total Marks = "+pmark);
    }
}
public class Inheritance {

    public static void main(String[] args) {
        Result r = new Result();
        r.display();
    }
}
  • Create a Paper class that takes the roll number of the student and marks of the practical examination.
  • The next class is called ObtainedMarks which extends the Paper class to get marks of the theory and the sum of both practical and theory papers.
  • To solve the diamond problem, use the interface to store the total marks of the paper and declare the display() method without its definition.
  • Create the GrandChild class called Result that extends the ObtainedMarks class and implements the TotalMarks interface.
  • Define the display() method to print the complete result card on the screen.
  • Finally, create the object of the Result class and call the display() method to get the compiled result.

Output

Why is Inheritance Important in OOP

Inheritance is important in OOP as it provides the reusability of the block of code multiple times across multiple classes. Copying a class is another approach but it is not a very effective one when we need a code multiple times. Creating multiple copies of the same code wastes storage space and other resources. It is also used to solve the Overriding problem in the OOP to invoke multiple methods with the same name from different classes.

That’s all about it.

Conclusion

Inheritance in Java programming language is a vital aspect or feature of OOP that allows the reusability of the existing code across classes. It uses the child class to inherit the attributes or methods from the parent class or classes using the extends keyword. The Inheritance has 5 types that explain different structures or ways to represent different classes in the inheritance. Java language doesn’t support the use of multiple inheritance due to the overriding problem in the OOP.