Java Inheritance With Program Example

Inheritance is an essential feature of object-oriented programming as it enables us to create and manage a hierarchy of classes. With the help of inheritance, a new class can acquire common attributes and behaviour from an existing class, which implies a class can reuse methods or fields of the superclass. Further, it can also have its own additional methods and fields. Inheritance represents the IS-A relationship.

In Java, a class that is inherited, is termed a superclass. The class that drives functionality from others is known as a subclass. As a result, the inheriting class can be viewed as an extended version of the parent class. It acquires all the members that are present in the superclass and use them accordingly.

The main advantage of inheritance is code reusability.
A parent class contains all the methods that are common in its children. On the other hand, a child class can have not only methods specific to itself, but also can acquire methods from the parent class using the inheritance .

Features of Inheritance in Java

  • Method Overriding: It allows us to redefine a parent class method in a child class having the same name and signature.
  • Code reusability: It avoids the need of rewriting the same functionality which is already defined in the existing class.
  • Minimise code duplication: Inheritance minimises code duplication.
  • Code conciseness: Code reusability implies the concise code structure of a program.

Syntax:

class A {
// body

}

class B extends A {


}

Program to implement inheritance in Java

Program:

class Parent {
    public void print() {
        System.out.println("Parent class !");
    }
}

class Child extends Parent {
    public void display() {
        System.out.println("Child class !");
    }

    public static void main(String[] args) {
        Child obj = new Child();
        obj.print();
    }
}

Explanation : 

In the above example, the Parent class is having print() method, and the child class is consisting a display() method only. Since the Child class is inheriting the Parent class, therefore, print() that belongs to the Parent class would become available for the Child class. As a result, Child class is having two methods, print() and display().

The inheritance concept implies that whatever members are present in the parent class, would automatically be available in the child class except for private members. This is how reusability works using the concept.

Types of Inheritance in Java

There are various types of inheritance supported by Java. However, when it comes to class, Java only provides support for three inheritance types, involving single, multilevel, and hierarchical inheritance. When it comes to interfaces, all 5 inheritance types are supported.

1. Single Inheritance : In this type of inheritance, single parent and child class are involved. When a class only inherits behaviour and attributes from a single existing class, then it is known as Single inheritance. For instance, class A extends class B, where class A is the only parent of class B and class B is the only child of class A.

In other words, a type of inheritance in which only a single subclass and parent class involve.

Single inheritance in Java

Syntax :

class A {

}

class B extends A {

}

Java program to implement single inheritance 

Program:

class College {

    void print(String name){
        System.out.println("This is MTech Student Name :: "+name);
    }
}

class Student extends College {
    String name;

    Student( String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Student student = new Student( "Pintu");
        student.print(student.name);
    }
}

Output:

This is MTech Student Name :: Pintu

2. Multiple inheritanceIn this type of inheritance, a single subclass class and multiple superclasses are involved. When a class extends multiple parent classes at a time then it is called multiple inheritance.

Java doesn’t provide support for multiple inheritance. However, it’s possible in case of interfaces.

 

multiple inheritance in Java

Syntax: 

interface A {

}

interface B {

}

interface C extends A,B{

}

Java program to implement multiple inheritance using interface

Program:

interface Practical {

    void printPracticalExaminationTime();
}

interface  Viva {

    void printVivaTime();
}

class Examination implements Practical, Viva{

    void printMarks(){
        System.out.println("10 Marks");
    }

    @Override
    public void printPracticalExaminationTime() {
        System.out.println("Practical examination will be at 9 AM");
    }

    @Override
    public void printVivaTime() {
        System.out.println("Viva examination will be at 12 PM");

    }

    public static void main(String[] args) {
        Examination obj = new Examination();
        obj.printPracticalExaminationTime();
        obj.printVivaTime();
        obj.printMarks();
    }
}

Output:

Practical examination will be at 9 AM
Viva examination will be at 12 PM
10 Marks

3. Multilevel InheritanceIn this type of inheritance, three or more classes are involved. When a class inherits an existing class, and that subclass further gets extended by another class, it is called multilevel inheritance. For instance, class C inherits class B, and class B inherits class A, forming a sequential chain, it is called multilevel inheritance.

multilevel inheritance in Java

Syntax:

class A {


}

class B extends A {


}

class C extends B {

}

Java Program to implement multiple inheritance

Program:

class Person {

    String getName(){
        return "ProgrammerBay";
    }
}

class Programmer extends Person{
    String getCodingLanguage(){
        return "Java";
    }
}

class Program extends  Programmer{
    int getLineOfCode(){
        return 20;
    }
    public static void main(String[] args) {
        Program program = new Program();
        System.out.println(" I am "+program.getName()+" and I code in "+ program.getCodingLanguage()+
                " . This program has "+program.getLineOfCode()+" lines");
    }
}

Output:

I am ProgrammerBay and I code in Java . This program has 20 lines

4. Hierarchical InheritanceIn this type of inheritance, single parent and multiple child classes are involved. When a single class gets inherited by two or more classes at a time, it is known as hierarchical inheritance. In Java, a parent class can have multiple subclasses. For instance, there are 4 classes, A, B, C, D class,if class A is extended by B, C and D, then it would be said hierarchical inheritance .

Hierarchical Inheritance in Java

Syntax: 

class A {

}

class B extends A {

}

class C extends A {

}

class D extends A {

}

Java Program to implement hierarchical inheritance

Program:

class Shape {

void printArea(long area) {
System.out.println("Area = " + area);
}
}

class Square extends Shape {

long calculateArea(long side) {
return side * side;
}
}

class Rectangle extends Shape {

long calculateArea(long l, long b) {
return l * b;
}

public static void main(String[] args) {
long area;
Square squareObj = new Square();
Rectangle rectangleObj = new Rectangle();
area = squareObj.calculateArea(3);
squareObj.printArea(area);
area = rectangleObj.calculateArea(3, 2);
rectangleObj.printArea(area);

}
}

Output:

Area = 9
Area = 6

 

5. Hybrid Inheritance:In this, a combination of various inheritance types is involved. When classes inherit one another in a way that the hierarchy structure consists of two or more types of inheritance. In other words, it can be defined as an inheritance where two or more types of inheritance are used together

Hybrid Inheritance in Java

Syntax :

class A {

}

class B extends A {

}

class C extends B {

}
class D extends B {

}

Java Program to implement hybrid inheritance

Program:

public class A {
    public void display() {
        System.out.println("I am a method from class A");
    }
}

class B extends A {
    public void print() {
        System.out.println("I am a method from class B");
    }
}

class C extends B {
    public void show() {
        System.out.println("I am a method from class C");
    }
}

class D extends C {
    public void show() {
        System.out.println("I am a method from class D");
    }
    public static void main(String[] args) {
        D objD = new D();
        objD.display(); // A is indirect parent of D, therefore, the display method gets inherited all the way to leaf
    }
}

Output:

I am a method from class A

Important aspects of Inheritance :

The inheritance hierarchy works from parent to child only. In other words, a child can have members of its parent class, but it’s not possible in the case of a parent to have members of child class.

Case 1: Can parent class reference variable invoke method of child class?

No, it’s not possible. Inheritance follows parent to child relationship, vice versa is not allowed.

However, it can only access overridden method of child class.

Case 2. Can parent class reference variable hold instance of child class?

Yes, a parent reference variable can hold object of child class. Although, it is not able to call child methods, it’ll only work with parent members and overridden methods.

Program example :

class Person {

    void display(){
        System.out.println("Parent class method");
    }

    void show(){
        System.out.println("Parent show method");
    }
}

class Programmer extends Person{
    void print(){
        System.out.println("Child class method");
    }

    @Override
    void show() {
        System.out.println("Child show method");
    }

    public static void main(String[] args) {

        Person programmer = new Programmer();
        programmer.display();  // Only parent class method is accessible, not child class
        programmer.show();  // Runtime polymorphism comes into picture, able to access child class method 
    }
}

Case 3. Can child reference variable hold object of parent class?

No, it’s not possible. The JVM compilers would trigger an Incompatible type exception. Consider the above example, All Programmers can be a person, but every person can’t be a Programmer. In a nutshell, it would violate is-a relationship.

Why Java doesn’t provide support for multiple inheritance?

In the case of classes, the multiple inheritance concept is not supported in Java. Java doesn’t allow a class to extend multiple classes at a time, otherwise, compile time error would occur.

irect 12

The reason is the ambiguity problem. When two classes have the same method and are inherited by a class, that method became available for the inheriting class. As a result, it creates ambiguity or confusion for the compiler in determining which method to call at runtime. In other words, when a compiler can’t be able to resolve the method call at the time of program execution due to duplicate behaviour generated from multiple inheritance,then it is termed an ambiguity problem or diamond can access problem.

Why Java supports multiple inheritance in case of interfaces, but not in case of classes?

An interface can have public and abstract members. It consists only declaration of a method but not its actual definition. Therefore, When two interfaces having the same method declaration, are inherited by a child interface or directly implemented by a class doesn’t create an ambiguity issue as the definition or implementation of that method is only possible through a class.

The ambiguity problem only arises when two or more implementations of the same methods are exist. In the case of interfaces, there can always be the single implementation provided through the inheriting class as interfaces are only capable of method declarations, not implementation.

Leave a Reply