I have the following code:
public class Triangle {
private Point left;
private Point right;
private Point top;
public Triangle(Point left, Point right, Point top) {
this.left = left;
this.right = right;
this.top = top;
}
}
I was wondering if it is good and safe to build such an object, because I am afraid that some of the three variables of type Point may be modified externally (encapsulation break). For instance:
public static void main(String[] args) {
Point left = new Point(0.0, 1.0);
Point right = new Point(2.4, 3.2);
Point top = new Point(5.8, 2.0);
Triangle t = new Triangle(left, right, top);
top.setX(10.2);
top.setY(23.4);
}
This will undoubtedly control the same “top” object referenced by the Triangle variable. So, the fix does the following inside the triangle constructor:
public Triangle(Point left, Point right, Point top) {
this.left = new Point(left);
this.right = new Point(right);
this.top = new Point(top);
}
(remember that I have a copy constructor in the Point class, so the three statements above are valid)
source
share