Programs

Types of Inheritance in Java with Examples

Inheritance in Java allows developers to create new classes with the existing ones. It enables the reusability of code. Inheritance can be both Single Inheritance and Multilevel Inheritance. Inheritance decreases the redundancy of code, makes it more readable and maintainable, and thus acts as a tool for increasing software quality.

Importance Of Inheritance

In Java, Inheritance is the method by which one class acquires the properties and functionalities of another class. Inheritance saves time, decreases redundancy, makes code more readable, understandable and maintainable, and acts as a tool for increasing software quality. Inheritance has many vital applications in Java programming language Inheritance enables developers to create new classes using existing ones Inherited classes act as templates or blueprints Inheritance provides software reusability Inherited classes act as a parent-child relationship Inherited methods make inherited classes independent Inherited attributes make inherited classes independent.

The inheritance hierarchy denotes a parent-child relationship between the different levels of inheritance. The topmost level of inheritance is known as “Super Class” or “Parent Class”.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name  

{  

   //methods and fields  

}  

The extended keyword indicates that you’re making a new class that inherits all of the functionality from its parent. It means “to increase” or enhance what’s already there.

Example: In the below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class that extends the Bicycle class, and class Test is a driver class to run a program. 

Input:

// Java program to illustrate the

// concept of inheritance

// base class

class Bicycle {

// the Bicycle class has two fields

public int gear;

public int speed;

// the Bicycle class has one constructor

public Bicycle(int gear, int speed)

{

this.gear = gear;

this.speed = speed;

}

// the Bicycle class has three methods

public void applyBrake(int decrement)

{

speed -= decrement;

}

public void speedUp(int increment)

{

speed += increment;

}

// toString() method to print info of Bicycle

public String toString()

{

return (“No of gears are ” + gear + “\n”

+ “speed of bicycle is ” + speed);

}

}

// derived class

class MountainBike extends Bicycle {

 

// the MountainBike subclass adds one more field

public int seatHeight;

// the MountainBike subclass has one constructor

public MountainBike(int gear, int speed,

int startHeight)

{

// invoking base-class(Bicycle) constructor

super(gear, speed);

seatHeight = startHeight;

}

// the MountainBike subclass adds one more method

public void setHeight(int newValue)

{

seatHeight = newValue;

}

// overriding toString() method

// of Bicycle to print more info

@Override public String toString()

{

return (super.toString() + “\nseat height is “

+ seatHeight);

}

}

// driver class

public class Test {

public static void main(String args[])

{

MountainBike mb = new MountainBike(3, 100, 25);

System.out.println(mb.toString());

}

}

Output:

No of gears are 3

speed of the bicycle is 100

seat height is 25

Terms Used in Inheritance

  • Class: A class is a group of objects that have common properties. It’s like an instruction manual or blueprint from which other individual units are created.
  • Sub Class/Child Class: A subclass is a class that inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from which a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: Reusability is a key design principle in object-oriented programming. It means that you can reuse the fields and methods from existing classes when creating new ones instead of repeating yourself over again with individual coding every time.

Popular Courses & Articles on Software Engineering

Types Of Java Inheritance

1. Single Inheritance

Single Inheritance means that one class extends another or implements several interfaces at once with the same access modifier or not access modifier, i.e., either public or private. The subclass created inherits all member functions and data members from its base/superclass except those declared as private, and these members may be accessed by the members and friends of the subclass.

Refer to the example below:

Input:

// Java program to illustrate the

// concept of single inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

 

class one {

public void print_A()

{

System.out.println(“A”);

}

}

 

class two extends one {

public void print_for() { System.out.println(“for”); }

}

// Driver class

public class Main {

public static void main(String[] args)

{

two g = new two();

g.print_A();

g.print_for();

g.print_Apple();

}

}

Output:

A

For

Apple

2. Multilevel Inheritance

Multilevel inheritance is the one where there is a chain of inheritance. n In Java, a derived class cannot directly access the grandparent’s members. When you have an inheritance hierarchy like this one where each new level inherits from another person or thing before them (or vice versa), it becomes difficult for any given object in either group because they are only able to use what’s available at their own respective levels; therefore making debugging more tedious than necessary!

Input:

// Java program to illustrate the

// concept of Multilevel inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

 

class one {

public void print_Inheritance()

{

System.out.println(“Inheritance”);

}

}

 

class two extends one {

public void print_in() { System.out.println(“in”); }

}

 

class three extends two {

public void print_Inheritance()

{

System.out.println(“Java”);

}

}

 

// Derived class

public class Main {

public static void main(String[] args)

{

three g = new three();

g.print_Inheritance();

g.print_in();

g.print_Java();

}

}

Output:

Inheritance

In

Java

3. Hierarchical Inheritance

Two classes in a hierarchy can inherit from one another. For example, if the Dog and Cat both fall under Animal, then there will be hierarchical inheritance with them being descendants of that class.

Input:

class Animal{  

void eat(){System.out.println(“eating…”);}  

}  

class Dog extends Animal{  

void bark(){System.out.println(“barking…”);}  

}  

class Cat extends Animal{  

void meow(){System.out.println(“meowing…”);}  

}  

class TestInheritance3{  

public static void main(String args[]){  

Cat c=new Cat();  

c.meow();  

c.eat();  

//c.bark();//C.T.Error  

}}  

 

Output:

meowing…

eating…

4. Multiple Inheritance (Through Interfaces)

Java does not support multiple inheritance with classes, but it’s possible to achieve them through interfaces. In the image below Class C is derived from both A and B, which means that they share some features while having different implementations for others depending on their specific needs in code execution or fulfillment of methods required by users (i).

Input:

// Java program to illustrate the

// concept of Multiple inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

 

interface one {

public void print_eye();

}

 

interface two {

public void print_for();

}

 

interface three extends one, two {

public void print_eye();

}

class child implements three {

@Override public void print_eye()

{

System.out.println(“Eye”);

}

 

public void print_for() { System.out.println(“for”); }

}

 

// Derived class

public class Main {

public static void main(String[] args)

{

child c = new child();

c.print_eye();

c.print_for();

c.print_eye();

}

}

Output:

Eye

for

Eye

5. Hybrid Inheritance (Through Interfaces)

Hybrid inheritance is a type of programming that allows us to mix two or more types. Classes cannot do this alone because they only have one set of methods, which means we need another object for it all to work properly, but interfaces offer peace of mind by allowing you to know what your program will look like before any code has been written!

Input

(Reference)

Class A and B extends class C → Hierarchical inheritance

Class D extends class A → Single inheritance

class C

{

   public void disp()

   {

System.out.println(“C”);

   }

}

class A extends C

{

   public void disp()

   {

System.out.println(“A”);

   }

}

class B extends C

{

   public void disp()

   {

System.out.println(“B”);

   }

}

class D extends A

{

   public void disp()

   {

System.out.println(“D”);

   }

   public static void main(String args[]){

D obj = new D();

obj.disp();

   }

}

Output:

D

If you’d like to learn in-depth about inheritance in Java and other OOP concepts, we recommended upGrad’s Executive PG Program in Software Development from IIIT-Bangalore. The 13-months course is designed by world-class industry professionals and faculty for building competence in 30+ tools and software. It included 400+ hours of content, 30+ industry-relevant case studies and projects, and 10+ live sessions to help you achieve desired outcomes; The course offers three specializations, namely full-stack development, Cloud back-end development, and Cyber Security.

Book your seat in the program today!

What are the four types of Inheritance?

The four types of Inheritance in Java are: 1. Hierarchical Inheritance 2. Hybrid Inheritance 3. Single inheritance 4. Multilevel Inheritance

Explain Polymorphism in Java.

Polymorphism in Java is an Object-Oriented Programming concept under which objects in programs can take multiple forms. Doing so allows a single object to perform the same action in numerous ways.

Explain multithreading in Java.

Multithreading in Java is a feature through which multiple parts (each called thread) of a program can be executed concurrently to allow optimal CPU utilization.

Want to share this article?

Upskill Yourself & Get Ready for The Future

Leave a comment

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

Our Best Software Development Course

Get Free Consultation

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks