展开全部
水果类32313133353236313431303231363533e78988e69d8331333337616531abstract public class Fruit {
abstract public double getWeight();
}
苹果类public class Apple extends Fruit {
private double weight;
public Apple(double weight) {
this.weight = weight;
}
@Override
public double getWeight() {
return weight;
}
}
橘子类public class Orange extends Fruit {
private double weight;
public Orange(double weight) {
this.weight = weight;
}
@Override
public double getWeight() {
return weight;
}
}
桃子类public class Peach extends Fruit {
private double weight;
public Peach(double weight) {
this.weight = weight;
}
@Override
public double getWeight() {
return weight;
}
}
主类public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fruit[] fruits = { new Peach(12), new Apple(2), new Orange(5) };
for (Fruit fruit : fruits) {
System.out.println(fruit.getClass().getName() + "的重量是"
+ fruit.getWeight());
}
}
}
运行结果
Peach的重量是 12.0
Apple的重量是 2.0
Orange的重量是 5.0
这篇博客展示了如何在Java中创建一个抽象类`Fruit`,包含`getWeight()`方法,然后分别创建`Apple`、`Orange`和`Peach`三个子类进行实例化。在`Main`类中,通过泛型数组遍历并打印不同水果的重量,展示了多态特性。

被折叠的 条评论
为什么被折叠?



