Question: Practice question - We are up to inheritance and polymorphism in Java Here are two classes that are related by composition (the has a relation).
Practice question - We are up to inheritance and polymorphism in Java
Here are two classes that are related by composition (the has a relation). The Cat class has an object of type Animal as one of its fields.
A Cat object indirectly shares the features of its Animal field including weight, age and so on. A more natural way of relating Animal and Cat is by inheritance (the
is a relation). Rewrite the two classes so that Animal is an abstract class with abstract method makeSound and Cat is a concrete class that extends Animal.
You dont need to rewrite all the code; just make changes where appropriate. Change the visibility of weight and age so that Cat and other subclasses of Animal
can access them directly. Delete any unnecessary methods from Cat. Notice that the eat method for Cat calls the eat method of its Animal object then calls another method. Make sure your overridden version of eat does something similar. (Hint: you need the keyword super.)
Also, make sure your Cat constructor calls the Animal constructor to initialize legs, weight and lifespan.
public class Animal {
public final int legs;
public final int lifeSpan;
private int weight;
private int age = 0;
public Animal(int legs, int weight, int lifeSpan) {
this.legs = legs;
this. lifeSpan = lifeSpan;
this.weight = weight;
}
public int getWeight() {
return weight;
}
public int getAge() {
return age;
}
public void eat() {
if (age < lifeSpan/4) weight++; // still growing
}
public void birthday() {
if (age < lifeSpan) age++;
}
public void makeSound() {
// nothing here
}
}
public class Cat {
private Animal a;
public String name;
public String breed;
public Cat(String name, String breed, int lifeSpan) {
a = new Animal(4,1,lifeSpan); // 4 legs, birth weight = 1lb, lifeSpan depends on breed.
this.name = name;
this.breed = breed;
}
public int getWeight() {
return a.getWeight();
}
public int getAge() {
return a.getAge();
}
public void eat() {
a.eat();
makeSound(); // beg for more?
}
public void birthday() {
a.birthday();
}
public void makeSound() {
if (a.getAge() < a.lifeSpan/5) // kitten
System.out.println("Mew");
else if (a.getAge() <= a.lifeSpan - 4) // adult cat
System.out.println ("Meow");
else System.out.println("Wreoww!"); // old cat
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
