Creating a class immutable

I study immutable objects. I have to make the next class immutable. Did I do it right?

import java.awt.Point;
public class MyImmutablePoint {
    Point point;

    public MyImmutablePoint(Point point) {
        super();
        this.point = point;
    }

    public MyImmutablePoint() {
        this (new Point (0,0));
    }

    public Point getPoint() {
        return point;
    }

    public void setPoint(Point point) {
        this.point = point
    }
}

"Immutable" class:

public final class MyImmutablePoint {
    private final Point point;

    public MyImmutablePoint(Point point) {
        this.point = point;
    }

    public MyImmutablePoint() {
        this (new Point (0,0));
    }

    public Point getPoint() {
        return point;
    }   
}

However, I am not sure about the method toString. and perhaps the return of an object, such as Point, can be changed in the same way as an array, but not sure

+4
source share
2 answers

No

final Point p = new Point(0,0);
final ImmutablePoint ip = new ImmutablePoint(p);

Two examples:

//change the original Point passed in
p.x = 10
//use the getter and change the Point
ip.getPoint().x = 10

So, first you need to create a protective copy Point taken in the constructor:

public MyImmutablePoint(Point point) {
    this.point = new Point(point);
}

Then you need to create a protective copy Pointreturned from the recipient:

public Point getPoint() {
    return new Point(point);
}

All this leads me to the assumption that it is probably better not to disclose the inside Point:

public final class MyImmutablePoint {

    private final Point point;

    public MyImmutablePoint(Point point) {
        this.point = new Point(point);
    }

    public MyImmutablePoint() {
        this.point = new Point (0,0);
    }

    public int getX() {
        return point.x;
    }

    public int getY() {
        return point.y;
    }
}

.

+6

, . MyImmutablePoint. :

    Point point = new Point(1, 1);
    MyImmutablePoint immutablePoint = new MyImmutablePoint(point);
    point.setLocation(0, 0);
+5

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


All Articles