java对象之间的引用,对java中对象的双重引用

What if I want to get rid of one of the variables for the sake of making the code safer?

你是以一种奇怪的方式问这个问题.我认为你想通过稍后改变originOne来确保某人不能影响rectOne.

Is there a way to do that other than writing the constructor in such a way that no extra objects are created?

您的解决方案在您的问题中:创建一个额外的对象.

public Rectangle(Point p) {

origin = new Point(p.x, p.y);

}

要么

public Rectangle(Point p) {

origin = p.clone();

}

它必须支持最后一个的克隆方法.有关涉及的内容,请参阅this或其他参考.

如果你想在不创建另一个对象的情况下这样做,(1)你可能不能,(2)你为什么限制自己创建对象?这就是OO编程的全部内容.

对于字符串,您通常不会有同样的担忧.为什么?因为它们是不可改变的.

另一个(IMO更好)解决方案是使Point类不可变

public class Point { // possibly add "final class"

final int x;

final int y;

public Point(int x, int y) {

this.x = x;

this.y = y;

}

}

现在没有人可以改变Point,你的代码变得“更安全”.