Java Polymorphism Programming - Animal Class with Bird and Cat Subclasses for Specific Sounds
Java Polymorphism: Exercise-1 with Solution
Write a Java program to create a base class Animal (Animal Family) with a method called Sound(). Create two subclasses Bird and Cat. Override the Sound() method in each subclass to make a specific sound for each animal.
In the given exercise, here is a simple diagram illustrating polymorphism implementation:

In the above diagram, we have a base class Animal with the makeSound() method. It serves as the superclass for two subclasses, Bird and Cat. Both subclasses override the makeSound() method to provide their own sound implementations.
Sample Solution:
Java Code:
// Animal.java
// Base class Animal
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
// Bird.java
// Subclass Bird
public class Bird extends Animal {
@Override
public void makeSound() {
System.out.println("The bird chirps");
}
}
// Cat.java
// Subclass Cat
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat meows");
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Bird bird = new Bird();
Cat cat = new Cat();
animal.makeSound(); // Output: The animal makes a sound
bird.makeSound(); // Output: The bird chirps
cat.makeSound(); // Output: The cat meows
}
}
Sample Output:
The animal makes a sound The bird chirps The cat meows
Flowchart:




Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Java Polymorphism Exercises Home.
Next: Vehicle Class with Car and Bicycle Subclasses for Speed Control.
What is the difficulty level of this exercise?
Java: Tips of the Day
distinctValuesOfArray
Returns all the distinct values of an array.
Uses Arrays.stream().distinct() to discard all duplicated values.
public static int[] distinctValuesOfArray(int[] elements) { return Arrays.stream(elements).distinct().toArray(); }
Ref: https://bit.ly/3mn5ner
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook