Inheritance in Java with Example Programs

Inheritance is one of the important concept in OOPs. Java Inheritance is a process by which one class can re-use the methods and fields of other class. The Derived class(Sub class – The class which inherits the Parent class) re-uses the methods and variables of the Base class(Super class).

Inheritance represents IS-A relationship which is also called as Parent-Child relationship. (i.e) A Parent class can have any number of Child class whereas a Child class can have only one Parent class. Child class inherits the Parent class using extends keyword.

Inheritance in Java Example

Lets take the below example where Cycle class is the Super class. The Cycle class will have the common properties of a cycle such as gear and speed. The sub class here is the MountainCycle which extends the Cycle class. MountainCycle will have all the attributes of a Cycle and also has its own attribute to differentiate from other sub class. Since we are using Inheritance we need not re-write the speed and gear property for the MountainCycle again.

package com.javainterviewpoint;
class Cycle {
    int gear;
    String speed;
    public Cycle(){}
    public Cycle(int gear,String speed)
    {
        this.gear = gear;
        this.speed = speed;
    }
    
 }
 // MountianCycle is the Sub Class of Cycle
 class MountianCycle extends Cycle 
 {
     String color;
     
    public MountianCycle(String color)
    {
        this.color = color;
    }
    //Method to display both Cycle and MountianCycle class attributes
    public void ride()
    {
        System.out.println("Number of Gear : \""+gear+"\"");
        System.out.println("Speed of Cycle : \""+speed+"\"");
        System.out.println("Color of Cycle : \""+color+"\"");
    }
 }
public class InheritanceTest 
{
    public static void main(String args[]) 
    {
        //Create object of the Sub Class(MountianCycle)
        MountianCycle mb = new MountianCycle("Blue");
        //Set the values to the Cycle class attributes through MountianCycle object
        mb.speed = "50kmh";
        mb.gear = 5;
        mb.ride();
     }
}

When we run the above code we will get the below output.

Output: 

Number of Gear : "5"
Speed of Cycle : "50kmh"
Color of Cycle : "Blue"

Different Types of Inheritance in Java

Below are different types of Inheritance in Java, some are directly supported and some are indirectly supported through Java Interfaces.

  1. Single Inheritance
  2. Multiple Inheritance (Through Interface)
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance (Through Interface)

We will be looking at each of inheritance types at later point.

Private Access Modifier in Java Inheritance

A sub class can take all the attributes of a super class which is having public and protected access, it cannot access a private members of the parent class, as the private variable belongs to that class itself. In those cases the we can access those private members of the parent class using a public access methods (getters & setters). Lets change the Cycle class to have private members.

package com.javainterviewpoint;
class Cycle {
    private int gear;
    private String speed;
    public Cycle(){}
    public Cycle(int gear,String speed)
    {
        this.gear = gear;
        this.speed = speed;
    }
    public int getGear() {
        return gear;
    }
    public void setGear(int gear) {
        this.gear = gear;
    }
    public String getSpeed() {
        return speed;
    }
    public void setSpeed(String speed) {
        this.speed = speed;
    }
}
 // MountianCycle is the Sub Class of Cycle
 class MountianCycle extends Cycle 
 {
     String color;
     
    public MountianCycle(String color)
    {
        this.color = color;
    }
    //Method to display both Cycle and MountianCycle class attributes
    public void ride()
    {
        /**The below code will throw error as we are 
        accessing the private member directly**/
       /* System.out.println("Number of Gear : \""+gear+"\"");
        System.out.println("Speed of Cycle : \""+speed+"\"");*/
        System.out.println("Color of Cycle : \""+color+"\"");
    }
 }
public class InheritanceTest 
{
    public static void main(String args[]) 
    {
        //Create object of the Sub Class(MountianCycle)
        MountianCycle mb = new MountianCycle("Blue");
        /**Set the values to the Cycle class attributes through setters**/
        mb.setSpeed("66kmh");
        mb.setGear(6);
        mb.ride();
        /**Get the parent class members using public access methods getters **/
        System.out.println("Number of Gear : \""+mb.getGear()+"\"");
        System.out.println("Speed of Cycle : \""+mb.getSpeed()+"\"");
     }
}

Output :

Color of Cycle : "Blue"
Number of Gear : "6"
Speed of Cycle : "66kmh"

Use of Java Inheritance – Protected Access Modifier

A protected member of the class in different package can be accessed by the class in other package only through inheritance. Lets look into the below code

Parent.java

The Parent class belong to the package “com.javainterviewpoint.test” and has the protected member val

package com.javainterviewpoint.test;

public class Parent 
{
    protected static int val = 10;
}

Child.java

Child class belongs to the package “com.javainterviewpoint”. Even though we have imported the Parent class in our Child class, the protected member “val” will not be visible to the Child class.

package com.javainterviewpoint;

import com.javainterviewpoint.test.Parent;

public class Child 
{
    public static void main(String args[]) 
    {
        System.out.println("Value of Protected member in Parent class "+val);
     }
}

When we run the above Child class we will be getting error like “val cannot be resolved to a variable”

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	val cannot be resolved to a variable

	at com.javainterviewpoint.Child.main(Child.java:9)

The only way to make the Protected member visible to the class in the other package is through inheritance. Lets now make the child class to inherit the parent class.

package com.javainterviewpoint;

import com.javainterviewpoint.test.Parent;

public class Child extends Parent
{
    public static void main(String args[]) 
    {
        System.out.println("Value of Protected member in Parent class "+val);
     }
}

Output :

Value of Protected member in Parent class 10

Method Overriding in Java Inheritance

Method Overriding in Java is possible only when Sub class is inheriting the Super class. Lets look into the below example where both Parent and Child class will have same display() method and Child class extends Parent class.

package com.javainterviewpoint;

class Parent 
{
    public void display()
    {
        System.out.println("Parent Class display() method");
    }
}
public class Child extends Parent
{
    public void display()
    {
        System.out.println("Child class display() method");
    }
    public static void main(String args[]) 
    {
        //Parent class object to Parent reference
        Parent p = new Parent();
        p.display();
        //Child class object to Child reference
        Child c = new Child();
        c.display();
        //Child class object to Parent reference
        Parent pc = new Child();
        pc.display();
     }
}

Output :

Parent Class display() method
Child class display() method
Child class display() method

Super Keyword in Inheritance

When Sub class has inherited the Parent class then we can use the Super keyword to call the Parent class methods and constructors.

package com.javainterviewpoint;

class Parent 
{
    public Parent()
    {
        System.out.println("Parent Class Constructor");
    }
    public void display()
    {
        System.out.println("Parent Class display() method");
    }
}
public class Child extends Parent
{
    public Child()
    {
        super();
        System.out.println("Child Class Constructor");
    }
    public void display()
    {
        System.out.println("Child class display() method");
        super.display();
    }
    public static void main(String args[]) 
    {
        //Child class object to Child reference
        Child c = new Child();
        c.display();
     }
}

Output :

Parent Class Constructor
Child Class Constructor
Child class display() method
Parent Class display() method

Note :

  • While calling the Constructors of the Parent class the super() has to be the first line in the Child class constructor.
  • While calling the methods of the Parent class the super.MethodName() can be any where within the Child class method.

Leave a Reply

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