Reputation: 361
I am learning about immutable Objects. I have to make following 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;
}
}
Iam not sure about the toString
method though.
and maybe returning an object like Point can be modified as well like an array but not sure
Upvotes: 4
Views: 256
Reputation: 61128
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 defensive copy of the Point
taken in the constructor:
public MyImmutablePoint(Point point) {
this.point = new Point(point);
}
Then you need to create a defensive copy of the Point
returned from the getter:
public Point getPoint() {
return new Point(point);
}
This all leads me to suggest that it would probably be better not to expose the internal point
at all:
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;
}
}
Further format your code and order your members.
Upvotes: 6
Reputation: 2262
No it is not immutable. Point can still be modified by the creator of MyImmutablePoint. Ex:
Point point = new Point(1, 1);
MyImmutablePoint immutablePoint = new MyImmutablePoint(point);
point.setLocation(0, 0);
Upvotes: 5