Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconTypes of Inheritance in Java with Examples

Types of Inheritance in Java with Examples

Last updated:
25th Jun, 2022
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
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.

Ads of upGrad blog

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:

Ads of upGrad blog

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!

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Frequently Asked Questions (FAQs)

1What 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

2Explain 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.

3Explain 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.

Explore Free Courses

Suggested Blogs

Top 10 DJango Project Ideas & Topics
9453
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions & Answers [For Freshers & Experienced]
5531
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

Top 19 Java 8 Interview Questions (2023)
5560
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

06 Sep 2023

22 Must-Know Agile Methodology Interview Questions & Answers in US [2023]
5301
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas & Topics For Beginners [US 2023]
7593
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5359
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2023
5406
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5370
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

Top 10 Highest Paying Programming Languages In US [2023]
7744
Language is used as a form of communication between two people. One person expresses their thoughts and opinions, whereas the other listens and compre
Read More

by Pavan Vadapalli

19 Mar 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon