Java - OOP - Inheritance - Multilevel
In Java, inheritance is an important concept where one class can inherit properties and methods from another class. Multilevel inheritance is a type of inheritance where a derived class is inherited by another derived class. In this tutorial, we will discuss Multilevel Inheritance in Java with an example, which is explained in simple terms for grade 10 students.
Let's consider an example where we have a class called Animal which has a method called eat(). We have another class called Dog which extends the Animal class and has a method called bark(). We will create another class called Bulldog which extends the Dog class and has a method called play().
Copy code
// Animal class
class Animal {
public void eat() {
System.out.println("Animal is eating.");
}
}
// Dog class inherits Animal class
class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking.");
}
}
// Bulldog class inherits Dog class
class Bulldog extends Dog {
public void play() {
System.out.println("Bulldog is playing.");
}
}
// Main class to create objects and call methods
public class Main {
public static void main(String[] args) {
// Creating objects
Bulldog bulldog = new Bulldog();
// Calling methods
bulldog.eat();
bulldog.bark();
bulldog.play();
}
}
In the above code, we have three classes Animal, Dog, and Bulldog. The Animal class has a method called eat(). The Dog class extends the Animal class and has a method called bark(). The Bulldog class extends the Dog class and has a method called play().
In the Main class, we create an object of the Bulldog class and call the eat(), bark(), and play() methods. As the Bulldog class extends the Dog class which extends the Animal class, it inherits all the methods and properties of the Animal class and the Dog class.