具体代码如下:
abstract class Geometry{ //创建抽象类;// public abstract double getArea(); //创建抽象方法,抽象方法必须在抽象类中。// } class Pillar{ Geometry bottom;//抽象类Geometry申明的bottom成员变量。// double height; Pillar(Geometry bottom,double height){//构造方法,作用:仅传值。// this.height=height;//把值赋给成员变量height。// this.bottom=bottom; } public double getVolume() { if(bottom==null){ System.out.println(“没有底,无法求体积”); return -1; } return bottom.getArea()height; } } class Circle extends Geometry{ //抽象类Geometry的子类Circle,Circle不是抽象子类,所以要重写父类Geometry的方法 (重写方法:重写的方法名字、参数个数、参数的类型与父类的方法完全相同。要写出方法体。)// double r; Circle(double r){ this.r=r; } public double getArea(){ return (3.14rr); } } class Rectangle extends Geometry{ double a,b; Rectangle (double a,double b){ this.a=a; this.b=b; } public double getArea(){ return ab; } } public class Application{ public static void main(String args[]){ Pillar pillar; Geometry bottom=null; pillar=new Pillar(bottom,100); System.out.println(“体积”+pillar.getVolume()); bottom=new Circle(10); //bottom是子类Circle的上转型对象,上转型对象可以调用子类重写的方法。//该语句还可以写成:Geometry botoom;Circle b=new Circle(10);bottom。 // 对象b的上转型对象bottom,可以调用子类隐藏、继承的变量和继承、重写的方法。// pillar=new Pillar(bottom,58); System.out.println(“体积”+pillar.getVolume()); bottom=new Rectangle(12,22); pillar=new Pillar(bottom,58); System.out.println(“体积”+pillar.getVolume()); } } 运行结果如下:
疑问如下: 为什么在Pillar中以申明的bottom成员变量,在主类中还需在申明一次。 (请慷慨解答!)
