Java Intermediate

0% completed

Previous
Next
Hierarchical Inheritance

Hierarchical Inheritance is a type of inheritance in which multiple subclasses inherit from the same superclass. This setup creates a scenario where one parent class can have multiple child classes, each adding its own specific attributes and behaviors while still sharing the common features of the parent class.

Syntax of Hierarchical Inheritance

The syntax for hierarchical inheritance involves having one superclass and multiple subclasses:

Image
class Superclass { // Superclass members } class SubclassA extends Superclass { // Members specific to SubclassA } class SubclassB extends Superclass { // Members specific to SubclassB }
  • Superclass: The class being inherited from by multiple subclasses.
  • SubclassA and SubclassB: Multiple classes that inherit from the same superclass.

Example: Dog and Cat Inheriting from Animal

In this example, we'll demonstrate hierarchical inheritance by creating an Animal class as the superclass, with Dog and Cat as subclasses. All classes will be defined within a single Solution.java file for simplicity.

Java
Java

. . . .

Explanation:

  • extends Animal in Dog Class:

    • Establishes that Dog is a subclass of Animal, inheriting its properties and methods.
    • Allows Dog to access the displayInfo() method from Animal.
  • extends Animal in Cat Class:

    • Establishes that Cat is another subclass of Animal, inheriting the same set of properties and methods.
    • Allows Cat to access the displayInfo() method from Animal.
  • super(name, 5); in Dog Constructor:

    • Calls the constructor of the superclass Animal to initialize the name and sets the age to 5 for all Dog instances.
  • super(name, 3); in Cat Constructor:

    • Calls the constructor of the superclass Animal to initialize the name and sets the age to 3 for all Cat instances.
  • displayBreed() Method in Dog Class:

    • Specific method to display the breed of the dog, showcasing subclass-specific behavior.
  • displayColor() Method in Cat Class:

    • Specific method to display the color of the cat, showcasing subclass-specific behavior.

Hierarchical Inheritance allows multiple subclasses to inherit from the same superclass, reflecting a real-world scenario where different specific entities share common characteristics but also have their own distinct attributes. In the above example, both Dog and Cat inherit general properties (name, age, displayInfo()) from Animal, while introducing their own unique features (breed for Dog and color for Cat).

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next