Browse Tutorials
What is Inheritance in Java: Types of inheritance in java

What is Inheritance in Java: Types of inheritance in java

14 Feb 2024
Intermediate
2.52K Views
23 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Inheritance in Java: An Overview

Inheritance 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, especially in Java for beginners. We will learn the concepts of Java Inheritance, Java inheritance example, types of inheritance in Java, learn Java inheritance in this article.

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. Inheritance along with access modifiers in Java enables the generation of new classes that may be developed with the aid of pre-existing classes in Java.

What is Inheritance in Java?

Syntax


class Subclass-name extends Superclass-name 
{ 
 //methods and fields 
} 

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.

Important Terminologies Used in Java Inheritance

  • Class: A class is a collection of objects that have 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
}

Inheritance in Java Example

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 this example. 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.

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

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 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…

4. Multiple Inheritance (Through Interfaces)

A class can inherit behaviors and method signatures from various interfaces using multiple inheritance 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.

5. Hybrid Inheritance

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();
}
} 

This Java example 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.

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

This article is an introduction to Java for beginners and this article covers the idea of Inheritance in Java including its various types with examples. In Java, inheritance is when one class is able to inherit the attributes and methods of another. There are three types of inheritance in Java - single, multilevel, and hierarchical. While each type of inheritance has its own unique benefits, they all ultimately allow for code reusability which can make programs more efficient. The understanding and application of inheritance concepts play a vital role inJava Certification, 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
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 8th time in a row (2016-2023). 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