有一个类:
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。 如果为了使代码更安全而想要摆脱其中一个变量,除了编写构造函数以避免创建额外对象之外,是否还有其他方法可以做到这一点?
new Rectangle ( new Point ( x, y ) )
;这样你只有一个对原点的引用。(提示:使用 getter 方法访问origin
,如public getOrigint() { return origin; }
)。 - Hungry Blue Dev