0% completed
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.
The syntax for hierarchical inheritance involves having one superclass and multiple subclasses:
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.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.
Explanation:
extends Animal in Dog Class:
Dog is a subclass of Animal, inheriting its properties and methods.Dog to access the displayInfo() method from Animal.extends Animal in Cat Class:
Cat is another subclass of Animal, inheriting the same set of properties and methods.Cat to access the displayInfo() method from Animal.super(name, 5); in Dog Constructor:
Animal to initialize the name and sets the age to 5 for all Dog instances.super(name, 3); in Cat Constructor:
Animal to initialize the name and sets the age to 3 for all Cat instances.displayBreed() Method in Dog Class:
displayColor() Method in Cat Class:
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).
.....
.....
.....