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.