Java 从未返回值的子类访问基类中的get方法
我试着从圆柱体进入圆的半径。当我从圆柱体内部调用基类getRadius()方法时,什么都没有发生。有人能指出我做错了什么吗?我会很感激的 圆圈类:Java 从未返回值的子类访问基类中的get方法,java,Java,我试着从圆柱体进入圆的半径。当我从圆柱体内部调用基类getRadius()方法时,什么都没有发生。有人能指出我做错了什么吗?我会很感激的 圆圈类: public class Circle extends Point { double radius; Circle(){ this.radius = 0.0; } Circle(double radius){ this.radius = radius; } public double getRadius(){
public class Circle extends Point {
double radius;
Circle(){
this.radius = 0.0;
}
Circle(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
public void setRadius(double radius){
this.radius = radius;
}
public double area(){
double area = Math.PI * Math.pow(radius, 2);
return area;
}
@Override
public String toString(){
return String.format("Radius: " + radius);
}
}
气缸等级:
public class Cylinder extends Circle{
private double height;
public Cylinder(){
this.height = 0.0;
}
public Cylinder(double height){
this.height = height;
}
public double getHeight(){
return height;
}
public void setHeight(double height){
this.height = height;
}
public double volume(double height){
double volRad = super.getRadius();
double volume = Math.PI * Math.pow(volRad, 2) * height;
return volume;
}
@Override
public double area(){
double areaRad = super.getRadius();
double area = Math.PI * Math.pow(areaRad, 2);
return area;
}
@Override
public String toString(){
return String.format("Height: " + height);
}
}
my main()函数中的代码(忽略点代码):
这是我的输出:
Point properties: X-value: 3 Y-value: 4
Circle properties: Radius: 3.2
Cylinder properties: Height: 5.1
Circle area: 32.17
Cylinder area: 0
Cylinder volume: 0
BUILD SUCCESSFUL (total time: 0 seconds)
您的
圆柱体
中的半径
为0.0,因为您从未为其赋值。
这将有助于:
Cylinder cylinder = new Cylinder(height);
cylinder.setRadius(some value);
最好添加允许设置半径和高度的构造函数:
public Cylinder(double radius, double height){
super(radius);
this.height = height;
}
您需要在圆柱体对象上调用setRadius,或者在
圆柱体的构造函数中为Cyclinder添加一个2参数构造函数(高度、半径),您没有显式调用圆的任何超级构造函数。因此,默认构造函数被隐式调用,它将半径设置为0
相反,您需要调用定义半径的超级构造函数:
public Cylinder(double height, double radius){
super(radius);
this.height = height;
}
而不是仅具有高度的构造函数。将高度初始化为0的默认构造函数是可以的,因为半径也不重要。您没有为圆柱体设置半径的值,并且“默认”值为0.0:
Circle(){
this.radius = 0.0;
}
你可以这样设置
Cylinder cylinder = new Cylinder(height);
cylinder.setRadius(some value);
或修改圆柱体构造函数:
public Cylinder(double height, double radius){
super(radius); //call the correct constructor, not the one that set 0.0 as default.
this.height = height;
}
并按如下方式创建实例:
Cylinder cylinder = new Cylinder(height, radius);
尽管如此,如果您可以,我会更喜欢,并使用圆创建圆柱体的实例(将此对象传递给构造函数)。您没有设置圆柱体的半径。。。或者换句话说:圆柱体不仅仅是传递给构造函数的高度。
Cylinder cylinder = new Cylinder(height, radius);