我真的很困惑,对于克隆对象到底是使用.clone()
方法还是直接在对象之间使用=
符号有什么区别。
谢谢。
Dog a = new Dog("Mike");
接着:
Dog b = a;
Dog
对象和两个指向同一个 Dog
对象的变量。因此,执行以下操作:a.putHatOnHead("Fedora");
if (b.hasHatOnHead()) {
System.out.println("Has a hat: " + b.getHatName());
}
会打印出狗戴着 Fedora 帽子的信息,因为 a
和 b
引用了同一只狗。
相反地,做如下操作:
Dog b = a.clone();
现在你有两只狗的克隆。如果你给每只狗戴上帽子:
a.putHatOnHead("Rayden");
b.putHatOnHead("Fedora");
Object obj = new Object(); //creates a new object on the heap and links the reference obj to that object
案例1:
Object obj2 = obj; //there is only one object on the heap but now two references are pointing to it.
案例2:
Object obj2 = obj.clone(); //creates a new object on the heap, with same variables and values contained in obj and links the reference obj2 to it.
关于克隆方法的更多信息,您可以参考Java API文档。
使用=
只是给同一个对象起不同的名称。而使用.clone
则是创建一个新的对象,它是原始对象的副本。
=
创建一个指向同一对象的新引用。
clone()
创建一个具有与早期对象相同属性的新物理对象。