Tutorial Playlist
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.
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 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.
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.
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.
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.
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 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");
  }
}
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.
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();
  }
}
Inheritance provides several advantages in Java. Here are some key advantages:
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:
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.
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.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...