日期:2014-05-20  浏览次数:20694 次

面向对象深浅拷贝问题求大神解答~
public class Person {
protected String name;
protected MyDate birthday;
private static int count = 0;

public Person(String name,MyDate birthday)
{
this.name = name;
this.birthday = birthday;
count++;
}
public Person(String name)
{
this(name,new MyDate());
}
public Person()
{
this("",new MyDate());
}
public Person(Person p)
{
this(p.name,new MyDate(p.birthday));
}
public void set(String name)
{
this.name = name;
}
public void set(MyDate birthday)
{
this.birthday = new MyDate(birthday);
}
public void set(String name,MyDate birthday)
{
this.set(name);
this.set(birthday);
}
public String getName()
{
return this.name;
}
public MyDate getBirthday()
{
return this.birthday;
}
public String toString()
{
return this.name+","+this.birthday.toString()+","+this.getAge()+"岁";
}
public int getAge(int year)
{
return year-this.birthday.getYear();
}
public int getAge()
{
return getAge(MyDate.getThisYear());
}
public int olderThen(Person p)
{
return p.birthday.getYear()-this.birthday.getYear();
}
public static void howMany()
{
System.out.println(count+"个Person对象");
}
public void finalize()
{
System.out.println("释放对象("+this.toString()+")");
count--;
}


public static void main(String args[])
{
Person p1 = new Person("李小明",new MyDate(1979,3,15));
Person p2 = new Person(p1);
p2.set(p2.getName().substring(0,2)+"dong");
MyDate d = p2.getBirthday();
d.set(d.getYear()+2,d.getMonth(),d.getDay());
p2.set(d);
Person.howMany();
System.out.println("p1: "+p1+", p2: "+p2);
System.out.println(p1.getName()+"比"+p2.getName()+"大"+p1.olderThen(p2)+"岁");
p1.finalize();
Person.howMany();

}

}



我的疑问是 我认为 Person p2 = new Person(p1); 既是通过 浅拷贝 建立一个新的 Person 类的 p2对象,其中p2的成员变量 String 指向 p1对象中的String   也就是我认为 p1与p2的String指向同一个String区域 如果我调用p2.set(p2.getName().substring(0,2)+"dong"); 我认为也会改变p1对象中的String 的值。但是结果并没有改变p1中String的值。
实验结果如下:

2个Person对象
p1: 李小明,1979年3月15日,30岁, p2: 李小dong,1981年3月15日,28岁
李小明比李小dong大2岁
释放对象(李小明,1979年3月15日,30岁)
1个Person对象

面向对象 string java

------解决方案--------------------
string类型有个静态常量池的概念,是不可变的,举个例子
String s1= new String("abc");
String s2=s1;
s1 ="123";
这时候s1的值为123   ,s2为abc


------解决方案--------------------
string类型有个静态常量池的概念,是不可变的,举个例子
String s1= new String("abc");
String s2=s1;
s1 ="123";
这时候s1的值为123   ,s2为abc