Abstract类未初始化参数

时间:2018-03-02 12:39:09

标签: java class inheritance polymorphism abstraction

我正在尝试创建一个抽象类SolidFigure。圆柱形和长方形的pirsm都会从它开始。

我的问题是每当我实例化两个类中的任何一个(cylinder或rectPrism)时,SolidFigure中的高度(它是一个公共属性)都没有被构造函数初始化(它将为零)

这是代码:

SolidFigure:

public abstract class SolidFigure {

    private double height;

    public SolidFigure(double height) {
        height = this.height;
    }

    public double getHeight() {
        return height;
    }

    protected abstract boolean isEqual(SolidFigure s);

    protected abstract double calculateVolume();
}

气缸:

 class Cylinder extends SolidFigure{

   private double radius;
   private static double PI = 3.14;

   public Cylinder(double height, double radius) {
       super(height);
       this.radius = radius;
   }

   @Override
   protected double calculateVolume() {
        return radius * PI * getHeight();
   }

   @Override
   protected boolean isEqual(SolidFigure s) {
       return this.calculateVolume() == s.calculateVolume();
   }
}

RectPrism:

   class RectPrism extends SolidFigure{
      private double length, width;

   public RectPrism(double height, double length, double width) {
       super(height);
       this.length = length;
       this.width = width;
   }

   @Override
   protected double calculateVolume() {
        return length * width * getHeight();
   }

   @Override
   protected boolean isEqual(SolidFigure s) {
       return this.calculateVolume() == s.calculateVolume();
   }
 }

主:

    SolidFigure c = new Cylinder(12.0, 3);
    RectPrism r = new RectPrism(10.0, 4, 2);

    System.out.println(c.getHeight()); // This is zero
    System.out.println(r.calculateVolume()); // zero resulting from height

2 个答案:

答案 0 :(得分:2)

应该是相反的方式

public SolidFigure(double height) {
        this.height = height;
    }

答案 1 :(得分:0)

请更改

public SolidFigure(double height) {
        this.height = height;
    }

代码中的错误

代码height = this.height ;中的

表示您将实例变量height的值赋给参数可验证高度。它有默认值0d所以你得到这样的aswer。