Multi level Inheritance Java

In the earlier, Bird-Ostrich inheritance program, Ostrich extends only one class, Bird, because Ostrich wants to walk and the method is there in Bird’s class.

Now Ostrich also wants to eat but the eat() method is there in another class Animal. Now, it is required to Ostrich to extend two classes Bird and Animal. Observe the following pseudo code.

class Animal
{
  // eat() method exists her
}

class Bird
{
  // walk() method exists her
}

public class Ostrich extends Bird, Animal
{
  // Ostrich wants both walk() and eat()
}

As you can observe in the above code, after extends two classes exist, Bird and Animal. This is not permitted by Java. If you write multiple classes after extends, it comes under multiple inheritance and Java does not support. That is, Java permits to extend only one class. But Ostrich wants both. How to solve the problem?

Very simple. As Java permits to extend only one class, we write multiple classes that extends only one to the other like a ladder.

class Animal
{
  // eat() method exists her
}

class Bird extends Animal
{
  // walk() method exists her
}

public class Ostrich extends Bird
{
  // Ostrich wants both walk() and eat()
}

You can see in the above code, one-to-one ladder like Ostrich extends Bird and Bird extends Animal (and infact, this ladder can go any extent).

Let us rewrite the earlier Bird-Ostrich code where we add one more class Animal.

class Animal
{
  public void eat()
  {
    System.out.println("Animal can eat");
  }
}

class Bird extends Animal
{
  public void walk()
  {
    System.out.println("Bird can walk");
  }
}

public class Ostrich extends Bird
{
  public void run()
  {
    System.out.println("Ostrich can run at good speeds");
  }
  public static void main(String args[])
  {
    Animal a1 = new Animal();       // create a Animal object
    a1.eat();                       // Animal object a1 is calling its own eat() method

    Bird b1 = new Bird();           // create a Bird object
    b1.walk();                      // Bird object b1 is calling its own walk() method
    b1.eat();                       // Bird object b1 calling its super class Animal method eat(), permitted by inheritance

    Ostrich o1 = new Ostrich();     // create a Ostrich object
    o1.run();                       // Ostrich object1 o1 is calling its own run() method
    o1.walk();                      // now Ostrich object1 o1 is calling Bird’s walk() method. 
    o1.eat();                       // Ostrich also can call Animal's eat() due to inheritance. THIS IS THE POWER OF INHERITANCE
  }
}

Multi level Inheritance Java

Ostrich extends Bird and Bird extends Animal, it is one-to-one relation. This type of relation is known as "multilevel inheritance". Other inheritance is multiple inheritance.

Leave a Comment

Your email address will not be published.