Please use the following methods/functions. I am confused on how to create a sub
ID: 3706608 • Letter: P
Question
Please use the following methods/functions. I am confused on how to create a subclass in Java using Eclipse. Q1) Create a java package called Lab10-Q1 with a class called Q1 that has the main function with the below code public static void main(Stringl args) Animal[] pet = new Animal[2]; pet[0] = new Dog("Buddy",41); pet[1] = new Cat("Whiskers" ,4); for (Animal i: pet) System.out.printin( The pet name is+i.getName0 +and it weights+i.getWeightPounds0+ pounds and says "+ ispeak0 ) Inside the java package add a base class called Animal, and two subclasses of Animal called Cat and Dog. An Animal should have a name and a weight, and be able to speak. A cat should "meow" and a dog should "bark" You should have the following functionsExplanation / Answer
Below is your code: -
Q1.java
package Lab10_Q1;
public class Q1 {
public static void main(String[] args) {
Animal[] pet = new Animal[2];
pet[0] = new Dog("Buddy",41);
pet[1] = new Cat("Whiskers",4);
for(Animal i: pet) {
System.out.println("The pet name is "+i.getName()
+ " and it weights "+i.getWeightPounds()+" pounds and says "+i.speak());
}
}
}
Animal.java
package Lab10_Q1;
public class Animal {
private String name;
private int weightPounds;
public Animal(String animalName, int lbs) {
this.name = animalName;
this.weightPounds = lbs;
}
public int getWeightPounds() {
return weightPounds;
}
public void setWeightPounds(int lbs) {
this.weightPounds = lbs;
}
public String getName() {
return name;
}
public void setName(String animalName) {
this.name = animalName;
}
public String speak() {
return "";
}
}
Cat.java
package Lab10_Q1;
public class Cat extends Animal {
public Cat(String animalName, int lbs) {
super(animalName, lbs);
}
public String speak() {
return "meow";
}
}
Dog.java
package Lab10_Q1;
public class Dog extends Animal {
public Dog(String animalName, int lbs) {
super(animalName, lbs);
}
public String speak() {
return "bark";
}
}
Output
The pet name is Buddy and it weights 41 pounds and says bark
The pet name is Whiskers and it weights 4 pounds and says meow