【发布时间】:2011-11-08 05:34:34
【问题描述】:
考虑两个类:
public class Point {
public int x;
public int y;
public Point(int xVal, int yVal) {
x = xVal;
y = yVal;
}
public Point(Point pt) {
x = pt.x;
y = pt.y;
}
}
public class BoundingBox {
public Point topLeft;
public Point bottomRight;
public BoundingBox(Point setTopLeft, Point setBottomRight) {
topLeft = new Point(setTopLeft);
bottomRight = new Point(setBottomRight);
}
}
BoundingBox 应该复制传递给其构造函数的点,如图所示,还是只引用它们?如果它假定它们的参考值,是否保证只要 BoundingBox 存在,那些 Point 对象就会存在?
【问题讨论】:
-
我认为只有原始类型会通过值传递。其他的将通过引用传递。
-
我知道,但我需要知道是复制这些对象中的值(将其克隆到另一个新对象),还是保留它们的引用并继续使用它们
-
虽然和这个问题有很大关系,关于'pass by reference'和'pass by value'的争论确实很乏味,但我想说没有'在 java 中通过引用传递。看看:stackoverflow.com/questions/7301637/…
-
是的,我喜欢将其视为不可变引用。对象将继续以自己的方式存在,而不依赖于变量。