w3resource

Java Polymorphism: Animal Base Class with Bird and Panthera Subclasses

Java Polymorphism: Exercise-7 with Solution

Write a Java program to create a base class Animal with methods move() and makeSound(). Create two subclasses Bird and Panthera. Override the move() method in each subclass to describe how each animal moves. Also, override the makeSound() method in each subclass to make a specific sound for each animal.

Sample Solution:

Java Code:

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

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

//Bird.java

class Bird extends Animal {
  @Override
  public void move() {
    System.out.println("Bird flies");
  }

  @Override
  public void makeSound() {
    System.out.println("Bird chirps");
  }
}
//Panthera.java

class Panthera extends Animal {
  @Override
  public void move() {
    System.out.println("Panthera walks");
  }

  @Override
  public void makeSound() {
    System.out.println("Panthera roars");
  }
}
//Main.java
public class Main {
  public static void main(String[] args) {
    Animal bird = new Bird();
    Animal panthera = new Panthera();

    performAction(bird);
    performAction(panthera);
  }

  public static void performAction(Animal animal) {
    animal.move();
    animal.makeSound();
  }
}

Sample Output:

Bird flies
Bird chirps
Panthera walks
Panthera roars

Explanation:

We have the "Animal" class as the base class, and "Bird" and "Panthera" are its subclasses. Each subclass overrides the move() and makeSound() methods to provide their specific implementations.

In the "Main" class, we have a static method performAction(Animal animal) that takes an object of the base class Animal as a parameter. Inside this method, we call the move() and makeSound() methods on the animal object. Since the performAction method takes an Animal type parameter, it can accept Bird and Panthera objects.

Flowchart:

Flowchart: Animal Java
Flowchart: Bird Java
Flowchart: Panthera Java
Flowchart: Main Java

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Shape Class with Circle, Rectangle, and Triangle Subclasses for Area and Perimeter Calculation.
Next: Shape base class with Circle, Square, and Triangle subclasses.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.