gpt4 book ai didi

java - 对java中对象的双重引用

转载 作者:搜寻专家 更新时间:2023-11-01 02:09:01 25 4
gpt4 key购买 nike

有一个类:

public class Rectangle {
public int width = 0;
public int height = 0;
public Point origin;

public Rectangle(Point p) {
origin = p;
}
}

可以看出,该类有一个Point类型的对象。当我声明一个 Rectangle 类型的对象时,

Rectangle rectOne = new Rectangle(originOne)

其中 originOne 是 Point 类型,那么在对象初始化之后,我将有两个不同的 originOne 对 Point 引用的引用,即 rectOne.origin 和 originOne。如果为了使代码更安全我想去掉其中一个变量怎么办?除了以不创建额外对象的方式编写构造函数之外,还有其他方法可以做到这一点吗?

最佳答案

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();
}

它必须支持最后一个的clone 方法。参见 this或涉及的其他引用资料。

如果您想在不创建另一个对象的情况下执行此操作,(1) 您可能不能,以及 (2) 为什么要限制自己创建对象?这就是 OO 编程的全部内容。


您通常不会对 String 有同样的担忧。为什么?因为它们是不可变的。

另一个(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,您的代码变得“更安全”。

关于java - 对java中对象的双重引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22587549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com