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()方法,分析输出结果是否正确。
时间: 2024-02-18 22:03:49 浏览: 43
以下是程序代码:
```java
public class Pet {
public void speak() {
System.out.println("Pet speak");
}
}
public class Dog extends Pet {
public void speak() {
System.out.println("Bark Bark");
}
}
public class Cat extends Pet {
public void speak() {
System.out.println("Meow Meow");
}
}
public class Main {
public static void main(String[] args) {
Pet pet1 = new Dog();
Pet pet2 = new Cat();
pet1.speak();
pet2.speak();
}
}
```
程序运行结果为:
```
Bark Bark
Meow Meow
```
以下是增加了构造函数、添加存取weight值方法、重写speak()方法的Dog类代码:
```java
public class Dog extends Pet {
private int weight;
public Dog() {
this.weight = 0;
}
public Dog(int weight) {
this.weight = weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getWeight() {
return this.weight;
}
public void speak() {
System.out.println("Woof Woof");
}
}
```
以下是从Pet类派生Cat类,并重写speak()方法的代码:
```java
public class Cat extends Pet {
public void speak() {
System.out.println("Miao Miao");
}
}
```
运行经过修改后的程序,输出结果为:
```
Woof Woof
Miao Miao
```
我们可以看到,通过类型多态的方式,Pet类对象分别调用Dog和Cat的speak()方法,输出结果正确。