Write the Pet, Dog and Snake classes as follows to support the Pets client class.
Pet
Instance variable(s): a name of type String
Constructor(s): a 1-arg constructor to initialize name
Accessor method(s): return name
toString method: return “pet “ followed by the name of the pet
Dog
extends Pet
Additional instance variable(s): a weight of type int
Constructor(s): a 2-arg constructor to initialize name and weight
Accessor method(s): return weight
toString method: return Pet’s toString followed by “is a dog, weighing “ <weight>
“ pounds”
other method(s): 1) a speak method that returns “woof”, and 2) a move method that returns “runs”
Snake
extends Pet
Additional instance variable(s): a length of type int
Constructor(s): a 2-arg constructor to initialize name and length
Accessor method(s): return length
toString method: return Pet’s toString followed by “is a snake, “ <length> “ inches long”
other method(s): 1) a speak method that returns “hiss”, and 2) a move method that returns “slither”
1 Answer
? Favorite Answer
public class Pet
{
protected String name;
public void Pet(String n) {
name = n;
}
public String getName() {
return name;
}
public String toString() {
return “pet ” + getName();
}
}
public class Dog extends Pet
{
private int weight;
public void Dog(String n, int w) {
super(n);
setWeight(w);
}
public String getWeight() {
return weight;
}
public String setWeight(int w) {
weight = w;
}
public String toString() {
return super.toString() + ” is a dog weighing ” + getWeight() + ” pounds”;
}
public String speak() {
return “woof”;
}
public String moves() {
return “runs”;
}
}
public class Snake extends Pet
{
private int length;
public void Dog(String n, int l) {
super(n);
setLength(l);
}
public String getLength() {
return length;
}
public String setLength(int l) {
length = l;
}
public String toString() {
return super.toString() + ” is a snake ” + getLength() + ” inches long”;
}
public String speak() {
return “hiss”;
}
public String moves() {
return “slither”;
}
}