定义一个抽象类-水果,其中包括getWeight()方法,编写程序分别创建苹果、桃子、橘子三个类,创建若干水果对象存放在一个水果类型的数组中,输出数组中所有水果的类型、重量。提示:利用对象的getClass().getName()方法可获取对象的所属类的名称。(Java实现)
时间: 2024-02-29 10:51:18 浏览: 82
Get和Set方法-java类和对象
以下是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().getName() + ",重量:" + fruits[i].getWeight());
}
}
}
```
输出结果如下:
```
类型:Apple,重量:0.5
类型:Peach,重量:0.3
类型:Orange,重量:0.4
类型:Apple,重量:0.4
类型:Peach,重量:0.2
```
阅读全文