定义一个抽象类-水果,其中包括getWeight()方法,编写程序分别创建苹果、桃子、橘子三个类,创建若干水果对象存放在一个水果类型的数组中,输出数组中所有水果的类型、重量。提示:利用对象的getClass().getName()方法可获取对象的所属类的名称。(Java实现)
时间: 2024-03-03 18:48:46 浏览: 35
好的,以下是Java代码实现,希望能对您有所帮助:
```java
abstract class Fruit {
public abstract double getWeight();
}
class Apple extends Fruit {
private double weight;
public Apple(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
class Peach extends Fruit {
private double weight;
public Peach(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
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[3];
fruits[0] = new Apple(0.2);
fruits[1] = new Peach(0.3);
fruits[2] = new Orange(0.4);
for (Fruit fruit : fruits) {
System.out.println(fruit.getClass().getName() + ": " + fruit.getWeight() + "kg");
}
}
}
```
输出结果:
```
Apple: 0.2kg
Peach: 0.3kg
Orange: 0.4kg
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)