用Java语言写定义一个抽象类-水果,其中包括getWeight()方法,编写程序分别创建苹果、桃子、橘子三个类,创建若干水果对象存放在一个水果类型的数组中,输出数组中所有水果的类型、重量。提示:利用对象的getClass().getName()方法可获取对象的所属类的名称。
时间: 2024-03-10 19:49:26 浏览: 20
好的,以下是Java语言实现:
```java
// 定义抽象类Fruit
abstract class Fruit {
public abstract double getWeight();
}
// 定义苹果类,继承自Fruit类
class Apple extends Fruit {
private double weight;
public Apple(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
// 定义桃子类,继承自Fruit类
class Peach extends Fruit {
private double weight;
public Peach(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
// 定义橘子类,继承自Fruit类
class Orange extends Fruit {
private double weight;
public Orange(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
public class Test {
public static void main(String[] args) {
// 创建水果数组
Fruit[] fruits = new Fruit[3];
fruits[0] = new Apple(0.5);
fruits[1] = new Peach(0.3);
fruits[2] = new Orange(0.2);
// 输出水果类型和重量
for (Fruit fruit : fruits) {
System.out.println(fruit.getClass().getName() + "的重量为:" + fruit.getWeight() + "kg");
}
}
}
```
输出结果为:
```
Apple的重量为:0.5kg
Peach的重量为:0.3kg
Orange的重量为:0.2kg
```