Hierarchical inheritance

Hierarchical inheritance in Java is a type of inheritance where a single parent class is inherited by multiple child classes. In other words, multiple classes inherit from the same parent class.

In a hierarchical inheritance relationship, a single class can be the parent of multiple child classes, each of which can have its own unique characteristics and behavior. The child classes inherit all the members (fields and methods) of the parent class, but they can also add their own fields and methods, or override or modify the behavior of the inherited members.

Syntax

class A {
    // code to be executed
};

class B extends A {
    // code to be executed
};

class C extends A {
    // code to be executed
};

Code Example 1 – constructors

This code defines three classes: Animal, Dog, and Cat.

Dog and Cat are both subclasses of Animal, meaning they inherit from the Animal class.

The Animal class has a constructor that prints the message “This is an Animal” when an object of this class is created. The Dog class also has a constructor that prints the message “This is a Dog” when an object of this class is created. Similarly, the Cat class has a constructor that prints the message “This is a Cat” when an object of this class is created.

The Cube class has a main method that creates two objects: obj, which is an instance of the Cat class, and obj2, which is an instance of the Dog class.

When the Cube class is executed, it will create two objects: obj, which will trigger the Cat constructor and print the message “This is a Cat”, and obj2, which will trigger the Dog constructor and print the message “This is a Dog”.

class Animal {
    Animal() {
        System.out.println("This is an Animal");
    }
};

class Dog extends Animal {
    Dog() {
        System.out.println("This is a Dog");
    }
};

class Cat extends Animal {
    Cat() {
        System.out.println("This is a Cat");
    }
};

class Cube {
    public static void main(String[] args) {
        Cat obj = new Cat();
        Dog obj2 = new Dog();
    }
}
Output
This is an Animal
This is a Cat
This is an Animal
This is a Dog

Code Example 2 – methods

Methods of a class must be called explicitly via an object. Methods of the base class can be accessed. As can be seen in the example, an object of the type Cat can also access the method of the class Animal. The same applies to the class Dog.

class Animal {
	public void printAnimal() {
		System.out.println("This is an Animal");
	}
};

class Dog extends Animal {
	public void printDog() {
		System.out.println("This is a Dog");
	}
};

class Cat extends Animal {
	public void printCat() {
		System.out.println("This is a Cat");
	}
};

class Cube {
	public static void main(String[] args) {
		Cat obj = new Cat();
		Dog obj2 = new Dog();
		obj.printAnimal();
		obj.printCat();
		obj2.printAnimal();
		obj2.printDog();
	}
}
Output
This is an Animal
This is a Cat
This is an Animal
This is a Dog