Working with links passed to the constructor is safe and safe - Java

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;
    }

    // more program logic...
}

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)

+4
source share
3 answers

. Point Cloneable, , :

public Triangle(Point left, Point right, Point top) {
    this.left = left.clone();
    this.right = right.clone();
    this.top = top.clone();
}

Point Cloneable, , :

public Triangle(Point left, Point right, Point top) {
    this.left = new Point(left.getX(), left.getY());
    this.right = new Point(right.getX(), right.getY());
    this.top = new Point(top.getX(), top.getY());
}
+4

If you have a copy constructor, then you can use it. Otherwise, you can use the clone if the point implements cloneable .

+1
source

Source: https://habr.com/ru/post/1649563/


All Articles