水果类
abstract public class Fruit {abstract public double getWeight();}
苹果类
public class Apple extends Fruit {private double weight;public Apple(double weight) {this.weight = weight;}@Overridepublic double getWeight() {return weight;}}
橘子类
public class Orange extends Fruit {private double weight;public Orange(double weight) {this.weight = weight;}@Overridepublic double getWeight() {return weight;}}
桃子类
public class Peach extends Fruit {private double weight;public Peach(double weight) {this.weight = weight;}@Overridepublic double getWeight() {return weight;}}
主类
public class Main {public static void main(String[] args) {// TODO Auto-generated method stubFruit[] 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
取消
评论