我在班上有这些实例变量:
private int x1 = 0;
private int y1 = 0;
private int x2 = 0;
private int y2 = 0;
private int height = y2 - y1;
private int width = x2 - x1;
Run Code Online (Sandbox Code Playgroud)
在我的程序中,我使用改变xs和ys的方法,所以我期望height并width改变.但是,他们没有.有人可以解释为什么会这样,以及如何在更改xs和ys 的方法调用之后使其值"更新" ?
private int height = y2 - y1;初始化实例变量时会计算表达式:即实例化类时.从那时起它就什么都不做了 - 它没有以任何方式"链接"到表达式的源部分,并且在更新时不会更新.
你可能想要一个类的方法(public如果它在类外使用,private否则),如下所示.你可以摆脱你的height和width田地:
public int getHeight() { return this.y2 - this.y1; }
Run Code Online (Sandbox Code Playgroud)
但是,如果您决定在内部仍然需要宽度和高度,我会将其更改private为名为的方法calculateHeight.调用getXYZ的方法通常是字段的访问器而不是变异方法.然后,calculateWidth()只要更改字段值,就可以调用此(或等效的)y2, y1, x2, x1.
public int getHeight() { return this.height; }
private int calculateHeight() { return this.y2 - this.y1; }
...
this.y2 = this.y2 + 10;
this.height = calculateHeight();
Run Code Online (Sandbox Code Playgroud)
另外,我认为宽度和高度都是正数而不管y2是多少还是小于y1.您可以使用Math.abs删除减法结果上的符号:
public int getHeight() { return Math.abs(y2 - y1); }
Run Code Online (Sandbox Code Playgroud)
我的偏好是使用单一方法将高度和宽度作为维度返回.这两个值实际上是某个时间点的单个数据.您可以使用java.awt.Dimension:
public Dimension getDimension() {
new Dimension(Math.abs(x2 - x1), Math.abs(y2 - y1));
}
Run Code Online (Sandbox Code Playgroud)