Consider the two classes:
public class Point {
public int x;
public int y;
public Point(int xVal, int yVal) {
x = xVal;
y = yVal;
}
public Point(Point pt) {
x = pt.x;
y = pt.y;
}
}
public class BoundingBox {
public Point topLeft;
public Point bottomRight;
public BoundingBox(Point setTopLeft, Point setBottomRight) {
topLeft = new Point(setTopLeft);
bottomRight = new Point(setBottomRight);
}
}
Should BoundingBox make a copy of the points passed into its constructor as shown, or just take a reference to them? If it assumes their reference values, is it guaranteed that those Point objects will exist as long as the BoundingBox exists?
Yes, the point objects will continue to exist until they’re not used anymore. This is what the JVM garbage collection does for you.
You should make a copy of them. Otherwise, what happens when someone else comes along and does this:
Generally it’s good practice to avoid “gotchas” — code that works in ways that’s not expected. Even if you remember what your code’s gotchas are now, the first time you forget one you’re going to be really confused.