Navratri Sale: Get Upto 30% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
What is Inheritance in Java: Types of Inheritance in Java

What is Inheritance in Java: Types of Inheritance in Java

13 Sep 2024
Intermediate
5.27K Views
30 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

Inheritance in Java: An Overview

Inheritance in Java is a mechanism that acquires one object to take all the properties and behavior from its parent class. Inheritance is one of the most important pillars of object-oriented programming in Java. In this Java tutorial, we will learn the concepts of Java Inheritance, types of inheritance in Java, etc.

If you aren't thorough with the concepts of classes and objects, refer to, What is Class in Java? - Objects and Classes in Java.

Step into the world of full stack development with confidence—enroll in our Java Full Stack Developer Certification today!

What is Inheritance in Java?

Inheritance in Java assists in creating a new class that can be built by taking help from an existing class. In this method, a class inherits from an existing one by reusing methods and fields from the class.

What is Inheritance in Java?

Java is-a relationship

In Java, inheritance is an is-a relationship. We can use inheritance only if there is an is-a relationship between two classes. For example,

In the above figure:

  • A car is a Vehicle
  • A bus is a Vehicle
  • A truck is a Vehicle
  • A bike is a Vehicle

Here, the Car class can inherit from the Vehicle class, the bus class can inherit from the Vehicle class, and so on.

Read More - Top 50 Java Interview Questions

Important Terminologies Used in Java Inheritance

  • Class: A class is a collection of objects having similar traits, behaviors, and attributes. Class does not exist in the actual world. It merely serves as a model, blueprint, or prototype from which objects can be made.
  • Superclass/Parent Class: A superclass, also known as a base class or a parent class, is a class from which features are inherited.
  • Subclass/Child Class: A subclass (also known as a derived class, extended class, or child class) is a class that derives from another class. In addition to the attributes and methods of the superclass, the subclass may also add additional fields and methods.
  • Reusability: The concept of "reusability" is supported by inheritance; for example, if we want to construct a new class but an existing class already contains some of the code we need, we can derive our new class from the old class. We are utilizing the fields and methods of the pre-existing class by doing this.

How to Use Inheritance in Java?

In Java, inheritance works using the extends keyword. You can tell you are derived from an existing class by using the extends keyword. To state it another way, "extends" refers to more functionality.

Syntax


// Parent class (Superclass)
class ParentClass {
  // Fields and methods
}// Child class (Subclass) that inherits from ParentClass
class ChildClass extends ParentClass {
 // Additional fields and methods
}

Example


// Parent class (Superclass)class Animal {
  String name;
  int age;  
 public Animal(String name, int age) {
    this.name = name;
    this.age = age;
  }  
 public void speak() {
    System.out.println(name + " makes a sound.");
  }
}// Child class (Subclass) that inherits from Animal
class Dog extends Animal {
  String breed;  public Dog(String name, int age, String breed) {
    super(name, age); // Call the constructor of the parent class
    this.breed = breed;
  }  // Override the speak() method
  @Override
  public void speak() {
    System.out.println(name + " barks loudly!");
  }  public void fetch() {
    System.out.println(name + " fetches a ball.");
  }
}public class InheritanceExample {
  public static void main(String[] args) {
    // Create instances of Animal and Dog
    Animal genericAnimal = new Animal("Generic", 5);
    Dog myDog = new Dog("Buddy", 3, "Golden Retriever");    // Call methods
    genericAnimal.speak(); // Output: Generic makes a sound.
    myDog.speak(); // Output: Buddy barks loudly!
    myDog.fetch(); // Output: Buddy fetches a ball.
  }
}

Java inheritance is shown in the Java Online Compiler. The Dog class is a subclass that derives from Animal, overrides the speak() function, and adds a fetch() method. The Animal class serves as the parent class and has attributes and a speak() method. Instances of both classes are created by the main method, demonstrating polymorphism as they call their respective speak() methods and generating output specific to their behaviors.

Output

Generic makes a sound.
Buddy barks loudly!
Buddy fetches a ball.

Read More - Java Web Developer Salary

Access Modifiers in Java

Types of Access Modifiers in Java

  1. Default Access Modifier: The parent class is only accessible inside the Java project's package currently in use, but not outside of the package.
  2. Private Access Modifier: The methods of private modifiers can not be accessed by other users other than their native class.
  3. Protected Access Modifier: The methods and the members of the protected class are only accessible and visible to their classes and their inherited classes.
  4. Public Access Modifier: It is used for making a method or data member accessible for everyone and every platform.

To learn Access Modifiers in detail, refer to Access Modifiers in Java

Method Overriding in Java Inheritance

When you redefine any base class method with the same signature i.e. same return type, number, and type of parameters in the derived class, it is known as method overriding in Java. In this case, the method in the subclass overrides the method in the superclass.

Example of Method Overriding in Java


class DotNetTricks {
    public void print() { // overridden function
        System.out.println("Welcome to DotNetTricks");
    }
}

class ScholarHat extends DotNetTricks {
    @Override
    public void print() { // overriding function
        System.out.println("Welcome to ScholarHat");
    }
}

public class Main {
    public static void main(String[] args) {
        ScholarHat obj1 = new ScholarHat();

        // Call the print() function of the ScholarHat class
        obj1.print();
    }
}

In the above code, the base class Scholarhat overrides the print() function of the parent class, DotNetTricks. When you create an object of ScholarHat and call its print() function, it executes the version of the function defined in the ScholarHat class.

Output

Welcome to ScholarHat

super Keyword in Java Inheritance

In the above topic we saw that when the same method is defined in both the base class and the derived class, the method in the subclass overrides the one in the superclass. In such cases, the super keyword in Java is used to call the method of the parent class from the method of the child class.


class DotNetTricks {
    public void print() { // overridden function
        System.out.println("Welcome to DotNetTricks");
    }
}

class ScholarHat extends DotNetTricks {
    @Override
    public void print() { // overriding function

   // call method of the superclass
    super.print();
        System.out.println("Welcome to ScholarHat");
    }
}

public class Main {
    public static void main(String[] args) {
        ScholarHat obj1 = new ScholarHat();

        // Call the print() function 
        obj1.print();
    }
}

Here, the super keyword in the Java Online Editor is used to call the print() method present in the superclass.

Output

Welcome to DotNetTricks
Welcome to ScholarHat

Types of Inheritance in Java

There are five types of Inheritance in Java

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance
  4. Multiple Inheritance
  5. Hybrid Inheritance

1. Single Inheritance in Java

This is a single-level Inheritance with one subclass with the properties of the superclass.

1. Single Inheritance in Java

Example


class Animal
  { 
  void sleep(){System.out.println("sleeping...");} 
  } 
  class Dog extends Animal
  { 
  void bark(){System.out.println("barking...");} 
  } 
  class TestInheritance
  { 
  public static void main(String args[])
  { 
  Dog d=new Dog(); 
  d.bark(); 
  d.sleep(); 
  }
  } 

The Dog class in this example inherits from the Animal class to demonstrate inheritance in Java. The TestInheritance class creates a Dog instance and calls the bark() and sleep() methods to show how a subclass inherits functionality from its superclass. The Dog class adds a bark() method.

Output

barking…
sleeping…

2. Multi-Level Inheritance in Java

If there are 3 classes named A, B, and C in the Java toolkit, then class B inherits the properties of class A, and class C inherits the properties of class B. This happens in multilevel inheritance in Java.

Multi-Level Inheritance in Java

Multi-Level Inheritance in Java Example


class Animal
  { 
  void eat(){System.out.println("eating...");} 
  } 
  class Dog extends Animal{ 
  void sleep(){System.out.println("sleeping...");} 
  } 
  class BabyDog extends Dog
  { 
  void weep(){System.out.println("weeping...");} 
  } 
  class TestInheritance2
  { 
  public static void main(String args[])
  { 
  BabyDog d=new BabyDog(); 
  d.weep(); 
  d.sleep(); 
  d.eat(); 
  }
  }

The 'BabyDog' class in this example illustrates multi-level inheritance in Java; it derives from the 'Dog' class, which in turn derives from the 'Animal' class. The 'BabyDog' object has access to and may call methods from all three types, showing how inheritance establishes a hierarchy of classes with similar functionality.

Output

weeping…
sleeping…
eating…

3. Hierarchical Inheritance in Java

It multiplied one parent class with their child classes. This type of Inheritance in Java helps to reduce the code length and also increases the "code modularity".

Hierarchical Inheritance in Java

Example


class Animal
  { 
  void eat(){System.out.println("eating...");} 
  } 
  class Dog extends Animal
  { 
  void sleep(){System.out.println("sleeping...");} 
  } 
  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 
  }
  } 

This Java sample in the Java Compiler explains basic inheritance. As a result of the 'Cat' class' inheritance from the 'Animal' class, instances of the 'Cat' class can access and use the parent class' methods. A compile-time error (C.T.Error) is generated when attempting to call a method from a class that is unrelated to the one being called, such as "bark()," which is not a member of "Animal" or "Cat."

Output

meowing…
eating…

Read More: Hierarchical Inheritance in Java

4. Multiple Inheritance (Through Interfaces) in Java

A class can inherit behaviors and method signatures from various interfaces using multiple inheritances through interfaces, which encourages code reuse and flexibility. Interfaces ensure that classes follow predetermined behaviors by defining method contracts without implementing them.

Example


// Define two interfacesinterface Animal {
  void eat();
  void sleep();
}interface Bird {
  void fly();
}// Create a class that implements both interfaces
class Sparrow implements Animal, Bird {
  @Override
  public void eat() {
    System.out.println("Sparrow is eating.");
  }  @Override
  public void sleep() {
    System.out.println("Sparrow is sleeping.");
  }  @Override
  public void fly() {
    System.out.println("Sparrow is flying.");
  }
}public class Main {
  public static void main(String[] args) {
    Sparrow sparrow = new Sparrow();
    sparrow.eat(); // Calls the eat() method from the Animal interface
    sparrow.sleep(); // Calls the sleep() method from the Animal interface
    sparrow.fly(); // Calls the fly() method from the Bird interface

  }

}

The "Animal" and "Bird" interfaces are defined in this code, along with the class "Sparrow," which implements both interfaces. The 'eat()','sleep()', and 'fly()' methods are implemented by the 'Sparrow' class. It generates a "Sparrow" object and invokes its methods in the "main" method to show multiple inheritance through interfaces.

Output

Sparrow is eating.
Sparrow is sleeping.
Sparrow is flying.

Read More: Multiple Inheritance in Java

5. Hybrid Inheritance in Java

When a class derives from numerous classes by combining various inheritance types, this is referred to as hybrid inheritance in Java. Java enables both single and multiple inheritance through classes and interfaces. When a class uses hybrid inheritance, it can derive from a variety of classes, some of which are descended from through interface inheritance and others through class inheritance.

Example


// Base class
class Animal {
  void eat() {
    System.out.println("Animal is eating.");
  }
}// Interface for flying behavior
interface Flying {
  void fly();
}// Interface for swimming behavior
interface Swimming {
  void swim();
}// Derived class inheriting from Animal and implementing Flying interface
class Bird extends Animal implements Flying {
  @Override
  public void fly() {
    System.out.println("Bird is flying.");
  }
}// Derived class inheriting from Animal and implementing Swimming interface
class Fish extends Animal implements Swimming {
  @Override
  public void swim() {
    System.out.println("Fish is swimming.");
  }
}// Derived class inheriting from Bird and Fish
class FlyingFish extends Bird implements Swimming {
  @Override
  public void swim() {
    System.out.println("FlyingFish is swimming.");
  }
}public class Main {
  public static void main(String[] args) {
    Bird bird = new Bird();
    bird.eat();
    bird.fly();    Fish fish = new Fish();
    fish.eat();
    fish.swim();    FlyingFish flyingFish = new FlyingFish();
    flyingFish.eat();
    flyingFish.fly();
    flyingFish.swim();
}
} 

The code in the Java Playground shows how to create a class hierarchy using interfaces and class inheritance. It has two interfaces, 'Flying' and 'Swimming', which represent behaviors, as well as an 'Animal' base class with a 'feed' method. The derived classes "Bird" and "Fish" implement the "Flying" and "Swimming" interfaces, respectively, and both classes inherit from "Animal." The 'FlyingFish' class also implements 'Swimming' and further inherits from 'Bird'. To show method overriding and interface implementation, instances of these classes are created in the 'Main' class and their methods are called.

Output

Animal is eating.
Bird is flying.
Animal is eating.
Fish is swimming.
Animal is eating.
Bird is flying.
FlyingFish is swimming.

Why Do We Need Java Inheritance?

  • Code reuse: All subclasses share the code that was written for the superclass. The parent class code can be used directly by child classes.
  • Method Overriding: The only way to override a method is through inheritance. It is one approach for Java to implement run-time polymorphism.
  • Abstraction: Through inheritance, we may reach the concept of abstraction, which frees us from having to provide all the details. Abstraction only makes the user aware of the capability.

Advantages Of Inheritance in Java

  • Code reuse is made possible by inheritance, which lowers the amount of new code required. Reduced code duplication results from the subclass's ability to reuse the superclass's properties and functions.
  • Inheritance enables the development of abstract classes that specify a common interface for a collection of related classes. This encourages abstraction and encapsulation, which makes it simpler to extend and maintain the code.
  • A class hierarchy can be created through inheritance and utilized to represent the relationships between actual objects in the real world.
  • Polymorphism, or the capacity for a thing to take on various forms, is made possible by inheritance. The superclass's methods can be overridden by subclasses, giving them the flexibility to alter how they behave.

Disadvantages of Inheritance in Java

  • Inheritance may result in a more difficult-to-understand and complex code. This is particularly true if there are many inheritances used or if the inheritance hierarchy is complex.
  • Changes to the superclass without affecting the subclass are challenging to do because inheritance generates a tight coupling between the two classes.

Summary

In Java, inheritance is when one class can inherit the attributes and methods of another. While each type of inheritance has its unique benefits, they all ultimately allow for code reusability making programs more efficient. The understanding and application of inheritance concepts play a vital role in Full Stack Java Developer Course, enabling developers to design and implement efficient, scalable, and maintainable Java programs.

FAQs

Q1. What is Java inheritance?

Java inheritance enables classes to take on characteristics and behaviors from other classes.

Q2. What are the 4 types of inheritance in Java?

Single inheritance, multiple inheritance (via interfaces), multilevel inheritance, and hierarchical inheritance are the four types of inheritance in Java.

Q3. What is inheritance with example?

When a new class (subclass) is generated by inheriting attributes and methods from an existing class (superclass), this process is known as inheritance in Java. A "Car" class, for example, may derived from a "Vehicle" class.

Q4. What is inheritance in the Java parent class?

In Java, attributes and methods are inherited from a parent class (superclass) by child classes (subclasses).

Q5. What is the syntax of inheritance?

When defining a subclass in Java, the "extends" keyword is used to implement inheritance syntax. For example: class ChildClass extends ParentClass.

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Advanced Full-Stack .NET Developer Certification TrainingOct 05SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification TrainingOct 05SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification TrainingOct 06SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Full-Stack .NET Developer Certification TrainingOct 06SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core ProjectOct 19SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
.NET Solution Architect Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Azure Developer Certification TrainingOct 27SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this