w3resource

Java Polymorphism: Animal base class with Lion, Tiger, and Panther subclasses

Java Polymorphism: Exercise-10 with Solution

Write a Java program to create a base class Animal with methods eat() and sound(). Create three subclasses: Lion, Tiger, and Panther. Override the eat() method in each subclass to describe what each animal eats. In addition, override the sound() method to make a specific sound for each animal.

Sample Solution:

Java Code:

//Animal.java
class Animal {
  public void eat() {
    System.out.println("Animal eats.");
  }

  public void sound() {
    System.out.println("Animal makes a sound.");
  }
}

//Lion.java
class Lion extends Animal {
  @Override
  public void eat() {
    System.out.println("Lion eats meat.");
  }

  @Override
  public void sound() {
    System.out.println("Lion roars.");
  }
}
//Tiger.java
class Tiger extends Animal {
  @Override
  public void eat() {
    System.out.println("Tiger eats meat and sometimes fish.");
  }

  @Override
  public void sound() {
    System.out.println("Tiger growls.");
  }
}
//Panther.java
class Panther extends Animal {
  @Override
  public void eat() {
    System.out.println("Panther eats meat and small mammals.");
  }

  @Override
  public void sound() {
    System.out.println("Panther purrs and sometimes hisses.");
  }
}
//Main.java
public class Main {
  public static void main(String[] args) {
    Animal lion = new Lion();
    Animal tiger = new Tiger();
    Animal panther = new Panther();

    lion.eat();
    lion.sound();

    tiger.eat();
    tiger.sound();

    panther.eat();
    panther.sound();
  }
}

Sample Output:

Lion eats meat.
Lion roars.
Tiger eats meat and sometimes fish.
Tiger growls.
Panther eats meat and small mammals.
Panther purrs and sometimes hisses.

Explanation:

In the above exercise -

  • The "Animal" class is the base class and 'Lion', 'Tiger', and 'Panther' are its subclasses. Each subclass overrides the eat() method to describe what each animal eats and the sound() method to make a specific sound for each animal.
  • In the main() method, we create instances of Lion, Tiger, and Panther. We then call the eat() and sound() methods on these objects. Since these methods are overridden in the subclasses, the appropriate behavior for each animal will be displayed when we run the program.

Flowchart:

Flowchart: Animal Java
Flowchart: Lion Java
Flowchart: Tiger Java
Flowchart: Panther Java
Flowchart: Main Java

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: BankAccount base class with Savings, Checking Account subclasses.
Next: Vehicle base class with Car and Motorcycle subclasses.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.