I've got 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;
}
// more program logic...
}
I was wondering if it's okay and safe to construct an object like that, because I fear that some of the three variables of type Point could be modified from the outside(break encapsulation). For example:
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 manipulate the same "top" object that's being referenced in the Triangle variable. So is the fix doing 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);
}
(keep in mind that I have a copy constructor in the Point class, so the three statements above are valid)