gpt4 book ai didi

java - 抽象类未初始化参数

转载 作者:行者123 更新时间:2023-12-02 02:17:34 24 4
gpt4 key购买 nike

我正在尝试创建一个抽象类 SolidFigure。圆柱体和矩形棱柱都将从它继承。

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

这是代码:

实体图:

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();
}
}

矩形棱镜:

   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

最佳答案

应该是相反的

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

关于java - 抽象类未初始化参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com