我正在学习不可变的对象。我必须使下面的类不可变。我做得对吗?
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
}
}
"不可变"类:
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;
}
}
我不确定toString
方法。
并且可能返回像Point这样的对象也可以像数组一样修改但不确定
答案 0 :(得分:6)
final Point p = new Point(0,0);
final ImmutablePoint ip = new ImmutablePoint(p);
两个例子:
//change the original Point passed in
p.x = 10
//use the getter and change the Point
ip.getPoint().x = 10
所以,首先你需要在构造函数中创建Point
的防御性副本:
public MyImmutablePoint(Point point) {
this.point = new Point(point);
}
然后你需要创建一个从getter返回的Point
的防御副本:
public Point getPoint() {
return new Point(point);
}
这一切都促使我建议最好不要公开内部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;
}
}
进一步格式化您的代码并订购您的会员。
答案 1 :(得分:5)
不,它不是一成不变的。 Point仍然可以由MyImmutablePoint的创建者修改。例如:
Point point = new Point(1, 1);
MyImmutablePoint immutablePoint = new MyImmutablePoint(point);
point.setLocation(0, 0);