Write A Program In Java To Demonstrate Multilevel Inheritance.
In this, we will create a java program which demonstrate the use of multilevel inheritance
Before understanding the program we need to know about the multilevel inheritance
Class that has already been extended by another subclass. In other words, a subclass in java can be derived from another subclass, and so on, creating a hierarchy of classes. This creates a chain of inheritance in which each class in the hierarchy inherits properties and methods from the class above it.
To implement multilevel inheritance in java, we can define a hierarchy of classes in which each subclass extends the class above it. The subclasses inherit all the non-private properties and methods of their parent classes, as well as the properties and methods of the classes above them in the hierarchy.
For example, consider the following hierarchy of classes:
Animal
|
Mammal
|
Dog
In this hierarchy, the animal class is the parent class of the mammal class, and the mammal class is the parent class of the dog class. The dog class inherits all the properties and methods of its parent class mammal, as well as all the properties and methods of its grandparent class animal.
Here's a program in java that demonstrate the use of multilevel inheritance
class Animal { public void eat() { System.out.println("The animal is eating"); }}
class Dog extends Animal { public void bark() { System.out.println("The dog is barking"); }}
class Bulldog extends Dog { public void drool() { System.out.println("The bulldog is drooling"); }}
public class MultilevelInheritanceDemo { public static void main(String[] args) { Bulldog bulldog = new Bulldog(); bulldog.eat(); // calling method of grandparent class bulldog.bark(); // calling method of parent class bulldog.drool(); // calling method of child class }}
The animal is eating
The dog is barking
The bulldog is drooling
In this program, we define a grandparent class animal with a method eat(). We then define a parent class dog that extends the animal class and adds a method bark(). Finally, we define a child class bulldog that extends the dog class and adds a method drool().
In the main() method, we create an instance of bulldog and call all three methods. Since the bulldog class extends the dog class, which in turn extends the animal class, it inherits the eat() method from the animal class and the bark() method from the dog class. The drool() method is specific to the bulldog class and is not present in the animal or dog classes.
As we can see, the bulldog class inherits the eat() method from the animal class and the bark() method from the dog class, and we can call all three methods using an instance of bulldog. This is an example of multilevel inheritance in java.