嗨,我有个作业给我的班级:
- will initialize the 3 integers to 10, 8, 6
- will initialize the color to “black”
我有我所有的长度,宽度和颜色的getter和setter。我现在唯一的问题是,对于卷,如果我将值设置为不同,它将无法正确计算。
它只接受初始化的值。有什么办法吗?我的代码如下所示。例如,我可以打印.setLength(7),而不是打印总计7*8*6,而是打印出总计10*8*6。
public class Box
{
private int height = 6;
public void se(int height){
this.height=height;
}
public int getHeight(){
return height;
}
private int width = 8;
public void setWidth(int width){
this.width=width;
}
public int getWidth(){
return width;
}
private int length= 10;
public void setLength(int length){
this.length=length;
}
public int getLength(){
return length;
}
private String color="Black";
public void setColor(String color){
this.color=color;
}
public String getColor(){
return color;
}
private int vol=length*width*height;
public void setVol(int vol){
this.vol=vol;
}
public int getVol(){
return vol;
}
}发布于 2014-03-06 07:27:46
去掉vol属性和setVol设置器;这不是该类规范的一部分,也是问题的根源。重写getVol以在每次调用时从长度、宽度和高度计算卷。
您的当前设计无法工作,因为每当更改vol、width或height时,都不会重新计算。您可以保留当前的字段集,并在每次调用维度集时重写维度设置器来重新计算vol属性。这将加快getVol getter方法的速度,而代价是类设计和慢速setter方法的复杂性增加。这是一种你可以做或不做的交易,你认为合适。但是,您需要摆脱setVol方法,因为当您设置卷时,无法知道如何设置维度,从而使值保持一致。
发布于 2014-03-06 07:29:03
您需要为getter创建一个vol函数
例如:
public int getVol () {
vol=length*width*height;
return vol;
}当然,中间vol的设置是不必要的。你可以
return length*width*height;这确保始终正确计算当前vol。
https://stackoverflow.com/questions/22217833
复制相似问题