w3resource

Java Inheritance Programming - Animal Class with a method move()

Java Inheritance: Exercise-6 with Solution

Write a Java program to create a class called Animal with a method named move(). Create a subclass called Cheetah that overrides the move() method to run.

Sample Solution:

Java Code:

// Animal.java
// Parent class Animal

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

// Cheetah.java
// Child class Cheetah
public class Cheetah extends Animal {
    @Override
    public void move() {
        System.out.println("This cheetah is running!");
    }
}
// Main.java
// Main class
public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        animal.move();
        Cheetah cheetah = new Cheetah();
        cheetah.move();
    }
}

Sample Output:

Animal moves
This cheetah is running!

Explanation:

In the above exercise, the Animal class has a single method called move(). This method simply prints a message to the console saying the animal is moving. The Cheetah class extends the Animal class and overrides the move() method to print a message that Cheetah is running.

In the Main class, we create an instance of the "Animal" class and call its move() method. This prints the "This animal is moving" message to the console. We also create an instance of the "Cheetah" class and call its move() method. This prints the "This cheetah is running" message to the console.

Flowchart:

Flowchart: Animal Class with a method move().
Flowchart: Animal Class with a method move().
Flowchart: Animal Class with a method move().

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: BankAccount class with methods called deposit() and withdraw().
Next: Person Class with methods called getFirstName() and getLastName().

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);
yourList.clear();
yourList.addAll(set);

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