w3resource

Java: Abstract Bird Class with Eagle and Hawk Subclasses

Java Abstract Class: Exercise-11 with Solution

Write a Java program to create an abstract class Bird with abstract methods fly() and makeSound(). Create subclasses Eagle and Hawk that extend the Bird class and implement the respective methods to describe how each bird flies and makes a sound.

Sample Solution:

Java Code:

//Bird.java
abstract class Bird {
  public abstract void fly();

  public abstract void makeSound();
}

//Eagle.java
class Eagle extends Bird {
  @Override
  public void fly() {
    System.out.println("Eagle: Flying high in the sky.");
  }

  @Override
  public void makeSound() {
    System.out.println("Eagle: Screech! Screech!");
  }
}
//Hawk.java
class Hawk extends Bird {
  @Override
  public void fly() {
    System.out.println("Hawk: Soaring through the air.");
  }

  @Override
  public void makeSound() {
    System.out.println("Hawk: Caw! Caw!");
  }
}
//Main.java
public class Main {
  public static void main(String[] args) {
    Bird eagle = new Eagle();
    Bird hawk = new Hawk();

    eagle.fly();
    eagle.makeSound();

    hawk.fly();
    hawk.makeSound();
  }
}

Sample Output:

Eagle: Flying high in the sky.
Eagle: Screech! Screech!
Hawk: Soaring through the air.
Hawk: Caw! Caw!

Explanation:

In the above exercise -

  • The abstract class "Bird" has two abstract methods fly() and makeSound(). The subclasses Eagle and Hawk extend the Bird class and provide their own implementations for these abstract methods.
  • The "Eagle" class describes how an eagle flies high in the sky and makes a screeching sound, while the "Hawk" class describes how a hawk soars through the air and makes a cawing sound.
  • In the main method, we create instances of Eagle and Hawk, and then call the fly() and makeSound() methods on each object to describe how each bird flies and makes a sound.

Flowchart:

Flowchart: Bird Java
Flowchart: Eagle Java
Flowchart: Hawk Java
Flowchart: Main Java

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Abstract Shape2D Class with Rectangle and Circle Subclasses.
Next: Abstract GeometricShape Class with Triangle and Square Subclasses.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.