top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Hierarchical Inheritance in Java

Introduction

Inheritance is one of the fundamental concepts in object-oriented programming. Hierarchical inheritance in Java is a type of inheritance where the same class is inherited by more than one class.

In this kind of inheritance, the various classes gather their features from the same class. Read on to learn more about Java inheritance.

Overview

This tutorial will discuss why we use hierarchical inheritance in Java, important terminologies used in Java Inheritance, how hierarchical inheritance work in Java, why multiple inheritances are not supported in Java, the advantages and disadvantages of inheritance in Java, and much more. 

Hierarchical Inheritance in Java

Hierarchical inheritance is one of the most common and useful types of inheritance in Java. In this, classes inherit properties and behaviors from a single superclass but can have multiple subclasses that inherit from it. This creates a hierarchical relationship among the classes, forming a tree-like structure.

The Syntax of Java Inheritance

In Java, inheritance is implemented using the extends keyword. The syntax for creating a subclass that inherits from a superclass is as follows:

class Subclass extends Superclass {
    // subclass members and methods
}

We need to familiarize ourselves with two main syntaxes when working with inheritance in Java.

  • Subclass:  The name of the subclass you want to create.

  • Superclass: The name of the superclass that the subclass is inheriting from.

Now, let us look at an example to understand hierarchical inheritance in Java. Suppose we have a superclass called Vehicle, which represents generic properties and behaviors of vehicles. It can have subclasses like Car, Motorcycle, and Truck, which inherit from it.

The Vehicle class can have common attributes and methods that apply to all types of vehicles, such as color, speed, start(), and stop(). Each subclass (Car, Motorcycle, and Truck) can also have its own specific attributes and methods.

Here is an example:

Code for main.java file:
public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.color = "Red";
        car.speed = 60;
        car.numberOfDoors = 4;
        car.start();
        car.drive();
        car.stop();
        System.out.println("-----");
        Motorcycle motorcycle = new Motorcycle();
        motorcycle.color = "Black";
        motorcycle.speed = 100;
        motorcycle.hasSidecar = false;
        motorcycle.start();
        motorcycle.wheelie();
        motorcycle.stop();
        System.out.println("-----");
        Truck truck = new Truck();
        truck.color = "Blue";
        truck.speed = 40;
        truck.cargoCapacity = 5000;
        truck.start();
        truck.load();
        truck.unload();
        truck.stop();
    }
}
Code for vehicle.java file:
class Vehicle {
    String color;
    int speed;
    void start() {
        // Code to start the vehicle
        System.out.println("Vehicle started.");
    }
    void stop() {
        // Code to stop the vehicle
        System.out.println("Vehicle stopped.");
    }
}
class Car extends Vehicle {
    int numberOfDoors;
    void drive() {
        // Code to drive the car
        System.out.println("Car is being driven.");
    }
}
class Motorcycle extends Vehicle {
    boolean hasSidecar;
    void wheelie() {
        // Code to perform a wheelie
        System.out.println("Performing a wheelie.");
    }
}
class Truck extends Vehicle {
    int cargoCapacity;
    void load() {
        // Code to load the truck
        System.out.println("Truck is being loaded.");
    }
    void unload() {
        // Code to unload the truck
        System.out.println("Truck is being unloaded.");
    }
}

In this example, we create instances of the Car, Motorcycle, and Truck classes, set their attributes, and invoke their methods. The program outputs the corresponding messages to demonstrate the behavior of each class.

We can see how the subclasses Car, Motorcycle, and Truck inherit properties and methods from the Vehicle superclass. Each subclass also introduces its own unique attributes and methods, demonstrating the concept of hierarchical inheritance in Java.

Abstraction

Let us look at an example where we will achieve abstraction by defining an abstract superclass MediaPlayer that hides the implementation details of playing media and exposes only the essential methods (play(), stop()) and the abstract method displayMediaDetails(). 

The subclasses AudioPlayer and VideoPlayer inherit the common functionality from MediaPlayer and provide concrete implementations for displaying the details specific to audio and video media.

abstract class MediaPlayer {
    private boolean isPlaying;
    public void play() {
        isPlaying = true;
        System.out.println("Playing media...");
    }
    public void stop() {
        isPlaying = false;
        System.out.println("Stopped media.");
    }
    public abstract void displayMediaDetails();
}
class AudioPlayer extends MediaPlayer {
    private String songTitle;
    public AudioPlayer(String songTitle) {
        this.songTitle = songTitle;
    }
    public void displayMediaDetails() {
        System.out.println("Playing audio: " + songTitle);
    }
}
class VideoPlayer extends MediaPlayer {
    private String videoTitle;
    public VideoPlayer(String videoTitle) {
        this.videoTitle = videoTitle;
    }
    public void displayMediaDetails() {
        System.out.println("Playing video: " + videoTitle);
    }
}
public class Main {
    public static void main(String[] args) {
        AudioPlayer audioPlayer = new AudioPlayer("Song 1");
        audioPlayer.play();
        audioPlayer.displayMediaDetails();
        audioPlayer.stop();
        VideoPlayer videoPlayer = new VideoPlayer("Video 1");
        videoPlayer.play();
        videoPlayer.displayMediaDetails();
        videoPlayer.stop();
    }
}

In this example, MediaPlayer is an abstract class because it contains at least one abstract method (displayMediaDetails()) and cannot be instantiated directly. It defines common functionality for playing media and maintains a state (isPlaying) to track whether the media is being played or stopped.

Now, in the AudioPlayer subclass, we define a specific attribute songTitle and implement the displayMediaDetails() method to display the details of the currently playing audio. Similarly, in the VideoPlayer subclass, we define an attribute videoTitle and implement the displayMediaDetails() method to display the details of the currently playing video.

Encapsulation

Now that we have learned about abstraction let us see an example of inheritance in Java that demonstrates encapsulation and hierarchical inheritance:

Code for main.java file:

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog("Buddy");
        dog.eat();  // Accessing superclass method
        dog.bark(); // Accessing subclass method
        Cat cat = new Cat("Whiskers");
        cat.eat();  // Accessing superclass method
        cat.meow(); // Accessing subclass method
    }
}
Code for animal.java file:
// Base class (superclass)
class Animal {
    private String name;
    public Animal(String name) {
        this.name = name;
    }
    public void eat() {
        System.out.println(name + " is eating.");
    }
    // Getter method for name
    public String getName() {
        return name;
    }
}
// Derived class (subclass)
class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    public void bark() {
        System.out.println(getName() + " is barking.");
    }
}
// Derived class (subclass)
class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
    public void meow() {
        System.out.println(getName() + " is meowing.");
    }
}

Polymorphism

Polymorphism fundamentally allows objects from different classes to be treated like objects of common superclasses. In the case of hierarchical inheritance, multiple subclasses inherit from a single superclass, which creates a hierarchical relationship among the classes.

Here's a hierarchical inheritance example that explores polymorphism in Java:

Code for main.java file:

public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();
        Animal animal3 = new Cow();
        animal1.makeSound(); // Polymorphic method call
        animal2.makeSound(); // Polymorphic method call
        animal3.makeSound(); // Polymorphic method call
    }
}
Code for animal.java file:
// Base class (superclass)
class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}
// Derived class (subclass)
class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The dog barks");
    }
}
// Derived class (subclass)
class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The cat meows");
    }
}
// Derived class (subclass)
class Cow extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The cow moos");
    }
}

Why Multiple Inheritance Is Not Supported in Java?

Multiple inheritance in Java is not supported; it's like asking a creature to be physically present in two places at once, which violates the laws of nature.

Just like a person can have only one biological set of parents, a Java class can have only one direct superclass. Multiple inheritances can lead to conflicts and confusion when two superclasses define methods or variables with the same name.

Java avoids this complexity and opts for a simpler, more organized single inheritance model. So, in the case of Java, classes choose their superclasses wisely, embracing the elegance of simplicity over the perplexities of duality.

Real-World Example of Hierarchical Inheritance in Java

Here is a real-world example of hierarchical inheritance in Java:

class Shape {
    public void draw() {
        System.out.println("Drawing a shape");
    }
}
class Rectangle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}
class Circle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}
public class Main {
    public static void main(String[] args) {
        Shape shape1 = new Rectangle();
        Shape shape2 = new Circle();
        shape1.draw();
        shape2.draw();
    }
}

Advantages of Inheritance in Java

Inheritance provides several advantages in Java. Here are some key advantages:

  • Code Reusability: Inheritance allows the user to create a new class by inheriting the properties and methods of an existing class. This promotes code reusability.

  • Modularity and Extensibility: Inheritance promotes modular programming. This allows the user to divide the code into logical and hierarchical structures. The user can create a base class with common attributes and behaviors and derive specialized classes from it. This enables the user to extend the functionality of the base class.

  • Polymorphism: Inheritance is closely tied to polymorphism. It is a powerful concept in object-oriented programming. Polymorphism allows objects from different classes to be treated as objects from a common superclass. You can create a collection of objects of different derived classes using inheritance.

  • Method Overriding: Inheritance enables method overriding. This allows a derived class to provide a different implementation for a method defined in the base class. This feature is crucial for achieving runtime polymorphism.

  • Code Organization and Maintenance: Inheritance promotes better code organization. This is maintained by creating a hierarchical structure of classes. This makes it easier to understand and manage the codebase. This happens especially in large-scale projects.

  • Encapsulation and Abstraction: Inheritance helps achieve encapsulation and abstraction. You encapsulate related data and behaviors in a single entity by defining a base class with common attributes and methods. Derived classes inherit this encapsulated state and behavior.

Disadvantages of Inheritance in Java

While inheritance provides several advantages in Java, it also has some potential disadvantages that should be considered. Here are a few disadvantages of using inheritance:

  • Tight Coupling: Inheritance can lead to tight coupling between classes, especially in deep inheritance hierarchies. This tight coupling can make the code more fragile and difficult to maintain.

  • Inheritance Hierarchy Complexity: As the inheritance hierarchy grows larger and deeper, it may become challenging to trace the flow of execution and determine the origin of specific behaviors or properties. Overuse of inheritance can result in a convoluted design.

  • Inflexibility: Inheritance establishes a rigid relationship between the base and derived classes. This lack of flexibility can limit the ability to adapt to changing requirements or reuse code in different contexts.

  • Method Overriding Issues: If the base class changes its method implementation, all derived classes using method overriding will inherit the new behavior. This can lead to unexpected results if the derived classes were designed to rely on the previous implementation.

  • Increased Complexity in Understanding Code Flow: In large inheritance hierarchies, it can be challenging to understand the flow of execution. This can make the code harder to debug and maintain.

  • Name Clashes and Diamond Problem: Inheritance can lead to name clashes. This happens when two or more parent classes define methods or properties with the same name. This ambiguity can create conflicts and make the code more error-prone.

Conclusion

A key concept in Java, hierarchical inheritance increases code modularity and reusability and reduces code length. This tutorial will assist you in understanding the concepts of hierarchical inheritance in Java with examples. 

You can master Java and its various concepts with the help of online learning platforms like upGrad. Visit upGrad today to know more.

FAQs

1. Can constructors be inherited in Java?

Constructors are not inherited in Java. However, the subclass can call the constructor of the superclass. It can do so using the "super" keyword to initialize the inherited members of the superclass.

2. What is method overriding in inheritance?

Method overriding is a feature of inheritance in Java. This allows a derived class to provide a different implementation for a method already defined in the base class. The method in the derived class must have the same name, return type, and parameters as the method in the base class.

3. Can a subclass access private members of the superclass in Java?

No, a subclass cannot directly access the superclass's private members (fields or methods). Private members are only accessible within the class they are defined in. However, they can be indirectly accessed using public or protected methods provided by the superclass.

Leave a Reply

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