【发布时间】:2016-12-04 10:54:09
【问题描述】:
我有以下代码:
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...
}
我想知道构造这样的对象是否可行且安全,因为我担心 Point 类型的三个变量中的某些变量可以从外部修改(破坏封装)。 例如:
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);
}
这无疑将操纵在 Triangle 变量中引用的同一个“顶部”对象。 修复在 Triangle 构造函数中执行以下操作也是如此:
public Triangle(Point left, Point right, Point top) {
this.left = new Point(left);
this.right = new Point(right);
this.top = new Point(top);
}
(请记住,我在Point类中有一个复制构造函数,所以上面的三个语句是有效的)
【问题讨论】:
标签: java reference encapsulation