I have these instance variables in my class:
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;
In my program I use methods that change the x
s and y
s, so I expect height
and width
to change as well. However, they don't. Can someone explain why this is the case, and how I can make their values "update" after a method call that changes the x
s and y
s?
Your expression private int height = y2 - y1;
is evaluated when the instance variable is initialised: i.e. when the class is instantiated. From that point on it is does nothing - it is not "linked" in any way to the source parts of the expression and does not update when they update.
You probably want a method on the class (public
if it is used outside the class, private
otherwise) which would be something like the below. You can get rid of your height
and width
fields:
public int getHeight() { return this.y2 - this.y1; }
However if you decide you still need the width and height internally I would change this to a private
method named calculateHeight
. Methods called getXYZ
are usually accessors for fields and not mutation methods. You can then call this (or the equivalent calculateWidth()
) whenever you change the field values for 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();
As an aside I would argue that width and height are positive numbers regardless of y2
being more or less than y1
. You can use Math.abs
to remove the sign on the subtraction result:
public int getHeight() { return Math.abs(y2 - y1); }
My preference would be to use a single method to return the height and width as a dimension. The two values are really a single piece of data at a point in time. You could use java.awt.Dimension for this:
public Dimension getDimension() {
new Dimension(Math.abs(x2 - x1), Math.abs(y2 - y1));
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments