定义一个抽象类——水果,其中包括getWeight()方法,编写程序分别创建苹果、桃子、橘子3个类,创建若干水果对象存放在在一个水果类型数组中,输出数组中所有水果的类型、重量。提示:利用对象的getClass().getName()方法可获取对象所属类的名称。
源代码如下:
package pk1;
abstract class Fruit{//定义抽象类
protected double weight;
abstract public double getWeight() ;
}
class Apple extends Fruit{//定义苹果类
public Apple(double weight) {
this.weight=weight;
}
public double getWeight() {
return weight;
}
}
class Peach extends Fruit{//定义桃子类
public Peach(double weight) {
this.weight=weight;
}
public double getWeight() {
return weight;
}
}
class Orange extends Fruit{//定义橘子类
public Orange(double weight) {
this.weight=weight;
}
public double getWeight() {
return weight;
}
}
public class inform {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fruit f[]=new Fruit[3];
f[0]=new Apple(6.5);
f[1]=new Peach(9.382);
f[2]=new Orange(8.3216);
for(int k=0;k<f.length;k++) {
System.out.println(f[k].getWeight());
System.out.println(f[k].getClass().getName());
}
}
}