The Animal abstract class has the following data & methods: o A private String v
ID: 3841673 • Letter: T
Question
The Animal abstract class has the following data & methods:
o A private String variable to hold the name o Mutator & accessor for the name
o Three “walk”, “sleep”, and “drink” methods that print that the animal can walk, sleep, and drink respectively
o Two abstract methods “eat” and “speak”. These methods must be implemented by classes that are derived from this abstract class, since they are different for each of the animals.
Notes:
o You can add any other animal that you like.
o Expand the structure to include other mammals.
What data members and/or methods would you add to the abstract class?
Explanation / Answer
Animal.java
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void walk()
{
System.out.println("__"+name+" Can Walk__");
}
public void drink()
{
System.out.println("__"+name+" Can Drink__");
}
public void sleep()
{
System.out.println("__"+name+" Can Sleep__");
}
public abstract void eat();
public abstract void speak();
}
___________________
Carnivores.java
public class Carnivores extends Animal {
public void Carnivores()
{
}
@Override
public void eat() {
System.out.println("__"+getName()+" eat Meat");
}
@Override
public void speak() {
System.out.println("__"+getName()+" Can Speak");
}
}
____________________
Herbivores.java
public class Herbivores extends Animal {
public Herbivores()
{
}
@Override
public void eat() {
System.out.println("__"+getName()+" eat Plants");
}
@Override
public void speak() {
System.out.println("__"+getName()+" can speak");
}
}
_____________________
TestClass.java
public class TestClass {
public static void main(String[] args) {
Animal h, c;
h = new Herbivores();
h.setName("giraffe");
h.sleep();
h.eat();
h.drink();
h.walk();
h.speak();
c = new Carnivores();
c.setName("Leapord");
c.sleep();
c.eat();
c.drink();
c.walk();
c.speak();
}
}
____________________
Output:
__giraffe Can Sleep__
__giraffe eat Plants
__giraffe Can Drink__
__giraffe Can Walk__
__giraffe can speak
__Leapord Can Sleep__
__Leapord eat Meat
__Leapord Can Drink__
__Leapord Can Walk__
__Leapord Can Speak
______________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.