Java Inheritance Programming - Animal with a method called makeSound

Java Inheritance: Exercise-1 with Solution

Write a Java program to create a class called Animal with a method called makeSound(). Create a subclass called Cat that overrides the makeSound() method to bark.

This exercise shows how inheritance works in Java programming language. Inheritance allows you to create new classes based on existing classes, inheriting their attributes and behaviors. In this case, the 'Cat' class is a more specific implementation of the 'Animal' class, adding quarrel behavior.

Sample Solution:

Java Code:

// Animal.java
public class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound.");

// Cat.java
public class Cat extends Animal {
    public void makeSound() {
        System.out.println("The cat quarrels.");
// Main.java
public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        Cat cat = new Cat();        

Sample Output:

The animal makes a sound.
The cat quarrels. 


The above exercise demonstrates Java programming inheritance. In this program, we create a base class called 'Animal' with a method named makeSound(). Then, you will create a subclass of 'Animal' called 'Cat' which inherits from 'Animal'. The 'Cat' class will override the makeSound() method and change it to make a quarrel sound.


Flowchart: Animal with a method called makeSound
Flowchart: Animal with a method called makeSound
Flowchart: Animal with a method called makeSound

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Java Inheritance Exercises Home.
Next: Create a class called Vehicle with a method called drive(). Create a subclass called Car that overrides the drive() method to print "Repairing a car".

What is the difficulty level of this exercise?

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

How do I remove repeated elements from ArrayList?

If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:

Set<String> set = new HashSet<>(yourList);

Of course, this destroys the ordering of the elements in the ArrayList.

Ref: https://bit.ly/3bYIjNC


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