(Java面试题)
其实,Java里一般没有必要复制对象。一般都是多个引用,指向同一个对象。注意不要套用C/C++的思想。
比如,
Rectangle a = new Rectangle ( 0, 0, 100, 40);
Rectangle b = a;
这里并没有复制对象,b和a指向的是同一个对象。那么,如果想根据a 复制一个新的对象,该怎么做呢?
(注: 这里的 Rectangle 在来自 Java Swing 里的 Rectangle 类)
Rectangle a = new Rectangle ( 0, 0, 100, 40);
Rectangle b = new Rectangle();
b.x = a.x;
b.y = a.y;
b.width = a.width;
b.height = a.height;
以上代码,创建了两个 Rectangle 对象,它们的值完全相同。可以认为,基于a对象复制出一个新的对象b。
再来看一下,其实还有更简洁的写法:
Rectangle a = new Rectangle ( 0, 0, 100, 40);
Rectangle b = new Rectangle( a ); // 此处即复制出一个对象
为什么可以这么写? 因为在 java swing 里的 Rectangle类,还有一个构造方法:
public class Rectangle
{
public Rectangle (Rectangle other )
{
this.x = other.x;
this.y = other.y;
this.width = other.width;
this.height = other.height;
}
...
}
所以,在 b = new Rectangle ( a ) 时,即执行的是这个构造方法。