1)首先阅读下列程序并写出运行结果,然后编译、执行以验证; 2) 增加Dog类的构造函数,使之可以初始化Dog类中的weight值,并实现构造函数重载; 3)在Dog类中添加方法getWeight、setWeight以存取weight值; 4) 重写Dog类对象的speak()方法,使其返回“Woof Woof”字符串; 5)从Pet类派生Cat类,并且重写speak()方法返回值为”Miao Miao”; 6)在Main方法中,通过类型多态的方式实现Pet对象分别调用Dog和Cat的speak()方法,分析输出结果是否正确。 class Pet { protected String name; public Pet(String n) { name = n; } public String getName() { return name; } public String move() { return "run"; } public String speak() { return ""; } public String toString() { return "My pet " + name; } } class Dog extends Pet { protected int weight; public Dog(String s) { super(s); } } class PetTest { public static void main(String[] args) { Pet myPet = new Pet("George"); Dog myDog = new Dog("Spot"); System.out.println(myPet.toString() + "\n" + "Speak: " + myPet.speak() + "\n" + myPet.move() + " " + myPet.getName() + "\n"); System.out.println(myDog.toString() + "\n" + "Speak: " + myDog.speak() + "\n" + myDog.move() + " " + myDog.getName() + "\n"); } }
时间: 2024-01-20 08:04:41 浏览: 68
运行结果如下:
```
My pet George
Speak:
run George
My pet Spot
Speak:
run Spot
```
增加Dog类的构造函数,使之可以初始化Dog类中的weight值,并实现构造函数重载:
```java
class Dog extends Pet {
protected int weight;
public Dog(String s) {
super(s);
}
public Dog(String s, int w) {
super(s);
weight = w;
}
}
```
在Dog类中添加方法getWeight、setWeight以存取weight值:
```java
class Dog extends Pet {
protected int weight;
public Dog(String s) {
super(s);
}
public Dog(String s, int w) {
super(s);
weight = w;
}
public int getWeight() {
return weight;
}
public void setWeight(int w) {
weight = w;
}
}
```
重写Dog类对象的speak()方法,使其返回“Woof Woof”字符串:
```java
class Dog extends Pet {
protected int weight;
public Dog(String s) {
super(s);
}
public Dog(String s, int w) {
super(s);
weight = w;
}
public int getWeight() {
return weight;
}
public void setWeight(int w) {
weight = w;
}
public String speak() {
return "Woof Woof";
}
}
```
从Pet类派生Cat类,并且重写speak()方法返回值为”Miao Miao”:
```java
class Cat extends Pet {
public Cat(String s) {
super(s);
}
public String speak() {
return "Miao Miao";
}
}
```
在Main方法中,通过类型多态的方式实现Pet对象分别调用Dog和Cat的speak()方法,分析输出结果是否正确:
```java
public static void main(String[] args) {
Pet myPet = new Pet("George");
Dog myDog = new Dog("Spot");
Cat myCat = new Cat("Tom");
Pet[] pets = {myPet, myDog, myCat};
for (Pet pet : pets) {
System.out.println(pet.toString() + "\n" + "Speak: " + pet.speak() + "\n" + pet.move() + " " + pet.getName() + "\n");
}
}
```
输出结果如下:
```
My pet George
Speak:
run George
My pet Spot
Speak: Woof Woof
run Spot
My pet Tom
Speak: Miao Miao
run Tom
```
可以看到,输出结果是正确的,实现了Pet对象通过类型多态的方式分别调用Dog和Cat的speak()方法。
阅读全文