For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
Hierarchical inheritance in Java is a type of inheritance where multiple subclasses inherit from a single superclass. It allows different classes to share common properties and methods defined in the base class while adding their own unique behavior. This creates a tree-like structure that makes code modular, reusable, and easy to maintain.
In this tutorial, we will explain hierarchical inheritance in Java with syntax and examples. You will learn how it works, why Java does not support multiple inheritance, and how concepts like abstraction, encapsulation, and polymorphism fit into this model. We will also cover examples, advantages, and disadvantages to help you understand the practical applications.
Advance your Java programming expertise with our Software Engineering courses and elevate your learning to the next level. Hurry, enroll now.
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.
Fast-track your tech career by building future-ready skills in Cloud, DevOps, AI, and Full Stack Development. Get experience, learn from industry experts, and gain the expertise today’s top employers are looking for.
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.
Must Read: Set in Java: Operations, Examples & Uses
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.
Read to Learn More: Abstraction in Java: Types of Abstraction Explained Examples
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.");
}
}
Must Read: Encapsulation in Java with Example
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");
}
}
Must Read: Polymorphism in Java: Concepts, Types, Characterisitics & Examples
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();
}
}
Also Read: String Array In Java: Java String Array With Coding Examples
Inheritance provides several advantages in Java. Here are some key advantages:
Must Read: For Loop Program in Java: Syntax and Examples
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:
Hierarchical inheritance in Java is a powerful concept that allows multiple subclasses to share the features of a single superclass. It improves code reusability, promotes modular design, and supports concepts like polymorphism, abstraction, and encapsulation. By organizing classes into a tree-like structure, it simplifies development and reduces redundancy.
However, developers must also be cautious of tight coupling and complexity in large hierarchies. Understanding hierarchical inheritance in Java with examples is essential for building scalable, maintainable applications. Mastering this concept provides a solid foundation for working with object-oriented programming in real-world Java projects.
No, constructors are not inherited in hierarchical inheritance in Java. Each subclass must define its own constructor, but it can call the constructor of the superclass using the super keyword. This ensures proper initialization of superclass properties before executing the subclass’s specific code.
Method overriding in hierarchical inheritance allows a subclass to redefine a method already present in the superclass. In Java, the subclass method must have the same name, parameters, and return type. This enables polymorphism, allowing different subclasses to provide their own behavior while maintaining a common interface through the superclass.
No, a subclass in hierarchical inheritance cannot directly access private members of its superclass. Private fields and methods are restricted to the class in which they are defined. However, subclasses can access them indirectly through protected or public getters and setters defined in the superclass.
Hierarchical inheritance in Java is when multiple subclasses inherit from a single superclass. This creates a tree-like structure where the superclass defines common attributes and methods, while subclasses extend it with their own specialized behavior. For example, a superclass Vehicle can have subclasses like Car, Bike, and Truck.
Hierarchical inheritance involves multiple subclasses extending a single superclass, while multiple inheritance allows a subclass to inherit from more than one superclass. Java does not support multiple inheritance with classes to avoid conflicts, but it supports hierarchical inheritance. This ensures cleaner code and eliminates ambiguity.
Hierarchical inheritance is commonly used in Java because it promotes code reusability and better organization. A single superclass defines common properties, and multiple subclasses extend those functionalities. This reduces redundancy, makes the code easier to maintain, and supports object-oriented principles like polymorphism and abstraction.
Yes, hierarchical inheritance can be implemented using interfaces in Java. Multiple classes can implement the same interface, which acts like a common contract. However, unlike classes, interfaces only define method signatures, and subclasses must provide the actual implementations.
A common real-world example of hierarchical inheritance in Java is a superclass Shape with subclasses Circle, Rectangle, and Triangle. Each subclass inherits methods like draw() from Shape but overrides it to implement shape-specific drawing behavior. This demonstrates code reusability and polymorphism.
Polymorphism in hierarchical inheritance allows objects of different subclasses to be treated as objects of a common superclass. For instance, if Dog and Cat inherit from Animal, an Animal reference can store either a Dog or a Cat object, and the overridden makeSound() method will execute based on the actual object type.
Hierarchical inheritance provides advantages like code reusability, modularity, better organization, polymorphism, and easier maintenance. By placing common code in a superclass, developers reduce duplication. Subclasses extend this functionality, making the design more flexible and extensible.
The disadvantages include tight coupling between classes, difficulty in maintaining deep inheritance hierarchies, reduced flexibility due to rigid superclass-subclass relationships, and complexity when debugging large projects. Overuse of inheritance can also make the design harder to understand.
Yes, abstract classes are often used in hierarchical inheritance in Java. An abstract class defines common attributes and methods, including abstract methods that must be implemented by subclasses. This ensures consistency across multiple subclasses while promoting abstraction.
Encapsulation in hierarchical inheritance is achieved by declaring class variables as private and accessing them through getters and setters. The superclass can encapsulate common data, while subclasses extend functionality without directly exposing sensitive variables. This protects data integrity.
Java does not support multiple inheritance with classes to avoid the diamond problem, where ambiguity arises if two parent classes define the same method. Instead, Java allows multiple inheritance through interfaces, ensuring clarity while still offering flexibility.
Hierarchical inheritance involves one superclass and multiple subclasses, whereas multilevel inheritance is when a subclass acts as a superclass for another subclass, forming a chain. For example, Animal → Mammal → Dog is multilevel, while Animal → Dog and Animal → Cat is hierarchical.
Yes, hierarchical inheritance can be combined with multilevel inheritance. For example, Animal can be a superclass with Dog and Cat as subclasses. Dog may further have a subclass Puppy, making the inheritance structure both hierarchical and multilevel.
The super keyword in hierarchical inheritance is used by subclasses to call constructors and methods of the superclass. This ensures that the superclass’s attributes are properly initialized before executing subclass-specific behavior.
Method overloading occurs when multiple methods in a class share the same name but have different parameter lists. Method overriding happens when a subclass provides a new implementation for a method defined in the superclass. In hierarchical inheritance, overriding supports runtime polymorphism, while overloading enhances flexibility.
Yes, hierarchical inheritance is possible with interfaces. Multiple classes can implement the same interface, inheriting its method contracts. Additionally, interfaces themselves can extend other interfaces, allowing hierarchical relationships.
The best use case of hierarchical inheritance in Java is when multiple entities share common attributes but also require specialized behavior. For example, in a banking system, Account can be a superclass, and subclasses like SavingsAccount, CurrentAccount, and LoanAccount can extend it with specific rules.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free
Author|900 articles published