对象的=赋值只是传递引用,其本质还是指向一个引用。当改变一个对象的值时,另一个也会改变
例如:
public class Student implements Cloneable{
private String name;
public Object clone(){
Student s = null;
try {
s = (Student)super.clone();
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<span style="white-space:pre"> </span>public static void main(String[] args) {
Student s = new Student();
Student s2 = new Student();
s.setName("dms");
s2 = s;
// s2=(Student) s.clone();
s2.setName("wy");
System.out.println(s.getName());
System.out.println(s2.getName());
}
输出结果:
wy
wy
public static void main(String[] args) {
Student s = new Student();
Student s2 = new Student();
s.setName("dms");
// s2 = s;
s2=(Student) s.clone();
s2.setName("wy");
System.out.println(s.getName());
System.out.println(s2.getName());
}
结果为:
dms
wy
这样就实现对象间的赋值,不在是指向同一个引用对象。