你确定你的没问题吗?
时间: 2023-11-26 08:03:52 浏览: 30
非常抱歉,我的前一个回答有误。以下是修正后的Java代码:
```java
// 定义抽象类 Fruit
abstract class Fruit {
public abstract double getWeight();
}
// 定义 Apple 类
class Apple extends Fruit {
private double weight;
public Apple(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
// 定义 Peach 类
class Peach extends Fruit {
private double weight;
public Peach(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
// 定义 Orange 类
class Orange extends Fruit {
private double weight;
public Orange(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
// 主程序
public class Main {
public static void main(String[] args) {
Fruit[] fruits = new Fruit[5]; // 创建水果类型的数组
fruits[0] = new Apple(0.5); // 创建苹果对象
fruits[1] = new Peach(0.3); // 创建桃子对象
fruits[2] = new Orange(0.4); // 创建橘子对象
fruits[3] = new Apple(0.4); // 创建苹果对象
fruits[4] = new Peach(0.2); // 创建桃子对象
for (int i = 0; i < fruits.length; i++) {
System.out.println("类型:" + fruits[i].getClass().getSimpleName() + ",重量:" + fruits[i].getWeight());
}
}
}
```
输出结果如下:
```
类型:Apple,重量:0.5
类型:Peach,重量:0.3
类型:Orange,重量:0.4
类型:Apple,重量:0.4
类型:Peach,重量:0.2
```
非常感谢您指出我的错误。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)