[英]Java getters and setters not working
我正在做家庭作业,由我确定气瓶的体积。 本课程的对象是类和对象。 我有两个类,“ CylinderTest”和“ Cylinder”。 气缸测试调用Cylinder。 到目前为止,除get和set方法外,其他一切似乎都可以正常工作。 我试图防止对负数进行计算,但这不起作用,无论如何它都会执行计算。
这是CylinderTest类
public class CylinderTest
{
public static void main(String[] args)
{
Cylinder myTest = new Cylinder(-1, -1);
myTest.getHeight();
myTest.getRadius();
System.out.println(myTest);
printHeader();
double volume = myTest.volume();
displayCylinder(volume);
}
private static void printHeader()
{
System.out.println("Cylinder");
System.out.println("________");
}
private static void displayCylinder(double volume)
{
System.out.print("Cylinder volume = ");
System.out.println(volume);
}
}
这是气缸类
public class Cylinder
{
// variables
public static final double PI = 3.14159;
private double radius, height, volume;
// constructor
public Cylinder(double radius, double height)
{
this.radius = radius;
this.height = height;
}
// Volume method to compute the volume of the cylinder
public double volume()
{
return PI * radius * radius * height;
}
// accessors and mutators (getters and setters)
public double getRadius()
{
return radius;
}
public void setRadius(double radius)
{
if (radius > 0.0)
this.radius = radius;
else
this.radius = 1.0;
}
public double getHeight()
{
return height;
}
public void setHeight(double height)
{
if (height > 0.0)
this.height = height;
else
this.height = 1.0;
}
public double getVolume()
{
return volume;
}
public void setVolume(double volume)
{
this.volume = volume;
}
}
在构造函数中,您需要使用与getter和setter中相同的测试,而不是直接设置值。 当前,您使用new Cylinder(-1,-1)
规避了setter中的测试。
您的构造函数应调用设置器,并应检查设置器中的逻辑。 如果调用代码传递负值,您是否真的要继续使用值1?
您可以摆脱构造函数的使用:
Cylinder myTest = new Cylinder();
myTest.setHeight(-1);
myTest.setRadius(-1);
或者,您可以创建一个“工厂”方法:
public static Cylinder createCylinder(double radius, double height)
{
Cylinder tmp = new Cylinder();
tmp.setRadius(radius);
tmp.setHeight(height);
}
尽管从语法上不建议这样做,但您也可以更改构造函数以调用setter。看起来像这样:
public Cylinder(double radius, double height)
{
setRadius(radius);
setHeight(height);
}
由于这被认为是不好的做法,请参见: 从基本构造函数调用Java基本方法
除了不在构造函数中执行测试之外,您还无需设置音量(任何时候它都为null)。
因此,将您的构造函数更改为:
public Cylinder(double radius, double height)
{
this.setRadius(radius);
this.setHeight(height);
this.volume = volume();
}
并删除 setVolume()
并将setHeight()
和setRadius()
私有。
您的setter方法没有进行验证,因为您根本没有调用它们。 正如其他人所评论的那样,一个好主意是在构造函数中调用它们,而不是直接将值分配给radius
和height
。
像您一样初始化Cylinder的属性本身并不是错误的。 但是,由于您需要在输入上运行“ <= 0”验证,并且设置器已经实现了此调用,因此这是一个简单的解决方案。
另外一些注意事项不会影响您要查找的结果,但仍然让我惊讶:
TestCylinder
,您调用了两个getter方法,但没有将它们分配给任何东西。 请记住,getter返回一个值,因此,有效地调用它们本身无济于事。 TestCylinder
,您直接调用Cylinder.volume()
,而不是使用其getter方法getVolume
获取圆柱体的体积。 在这里,我建议您要么将逻辑来计算吸气剂的体积并仅使用该方法,要么建议让吸气剂调用volume()
,以防您在Cylinder
类的另一部分中需要后者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.