public class CloneTest {
String name;
int age;
public static void main(String args []) {
CloneTest c1= new CloneTest();
c1.name = "aa";
c1.age = 1;
CloneTest c2 = c1;
System.out.println(c1);
System.out.println(c2);
System.out.println(c1==c2);
}
}
输出
lmlc.test.CloneTest@5304f889
lmlc.test.CloneTest@5304f889
true
看到c1,c2的地址是相同的,他们引用的都是同一个地址。
package lmlc.test;
public class CloneTest implements Cloneable{
String name;
int age;
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String args []) throws CloneNotSupportedException {
CloneTest c1= new CloneTest();
c1.name = "aa";
c1.age = 1;
CloneTest c2 = (CloneTest) c1.clone();
System.out.println(c1);
System.out.println(c2);
System.out.println(c1==c2);
}
}
输出
lmlc.test.CloneTest@7edc93be
lmlc.test.CloneTest@4367e003
false
看到这次2个变量引用的地址是不同的,而且可以看到==是判断对象变量是否指向了相同的地址,如果要根据属性判读2个变量是否相同需要重写equal方法。