Abstract类未初始化参数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Abstract类未初始化参数相关的知识,希望对你有一定的参考价值。
我正在尝试创建一个抽象类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
答案
它应该是相反的方式
public SolidFigure(double height) {
this.height = height;
}
另一答案
请更换
public SolidFigure(double height) {
this.height = height;
}
你的代码有什么问题
在你的代码height = this.height ;
中,这意味着你将实例变量height的值赋给参数可验证的高度。它有默认值0d所以你得到这样的aswer。
以上是关于Abstract类未初始化参数的主要内容,如果未能解决你的问题,请参考以下文章
初始化 VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll) 时出现错误 80040154(类未注册异常)