代码如下,我想复制一份Person类的对象(通过浅复制的方法),并且想通过改变原对象的String引用的内容来改变Copy对象引用的内容,为什么不可以?public class CloneTest
{
public static void main(String[] args) throws Exception
{
Person person1 = new Person();
Person person2 = (Person)person1.clone();
System.out.println(person1.name);
person2.name = "李四";
System.out.println(person1.name);
}
}class Person implements Cloneable
{
public String name = "张三";
@Override
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
{
public static void main(String[] args) throws Exception
{
Person person1 = new Person();
Person person2 = (Person)person1.clone();
System.out.println(person1.name);
person2.name = "李四";
System.out.println(person1.name);
}
}class Person implements Cloneable
{
public String name = "张三";
@Override
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
也就是说,final类型的不能复制吗?
{
String a = "123";
String b = a;
a="456";
Assert.assertEquals(b, "123");
}
class Address implements Cloneable{
public String address ;
public Address(String address){
this.address = address;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Person implements Cloneable {
public String name = "张三";
public Address address = new Address("address1");;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class CloneTest {
public static void main(String[] args) throws Exception {
Person person1 = new Person();
Person person2 = (Person) person1.clone(); System.out.println(person1.name);//张三
System.out.println(person1.address.address);//address1 person2.name = "李四";
person2.address.address="address2";
System.out.println(person1.name);//张三
System.out.println(person1.address.address);//address2
}
}
对,就是这个问题了,为什么经过两次调用就可以改变String的值?如果都不能改变的话还好理解
引用没有问题,但是String这个类型是不能引用的。看我上面的那个测试程序。
{
public static void main(String[] args) throws Exception
{
Student s1 = new Student();
Student s2 = (Student) s1.clone();
System.out.println(s2.name);
s1.name = "李四";
System.out.println(s2.name);
System.out.println(s2.teacher.name);
s1.teacher.name = "李老师";
System.out.println(s2.teacher.name);
}
}
class Teacher implements Cloneable
{
public String name = "张老师";
}class Student implements Cloneable
{
public String name = "张三";
public Teacher teacher = new Teacher(); @Override
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}我首先想通过改变原对象的学生姓名来改变Copy对象的学生姓名,不行;但我通过改变原对象的老师姓名来改变Copy对象的老师姓名,好玩的来了,居然可以(学生类里有老师类的引用)。不行的可以试试