class Test implements Cloneable
{
Object o=null;
String name;
Test(String name)
{
this.name=name;
} public Object clone()
{
try
{
o=super.clone(); //为什么要调用这句?
}
catch(Exception e)
{
System.out.println(e.toString());
}
return o;
}
}super.clone(); 调用父类的 clone() 方法,这里又不是要复制父类对象。
{
Object o=null;
String name;
Test(String name)
{
this.name=name;
} public Object clone()
{
try
{
o=super.clone(); //为什么要调用这句?
}
catch(Exception e)
{
System.out.println(e.toString());
}
return o;
}
}super.clone(); 调用父类的 clone() 方法,这里又不是要复制父类对象。
调用super.clone();就表示在复制子类对象的时候,一定要使得父类对象的那部分数据能够得到复制。
建议读一读《Thinking in java》,附录中有一部分讲这个。
注:上面说的内部成员是指对象,不包括原始类型(int,float等)。
/**
* 实现深复制,通过 (前提,该对象中的各个属性都是可serielization的)
* @return Object
*/
public Object clone(){
ByteArrayOutputStream oo = new ByteArrayOutputStream();
ObjectOutputStream out = null ;
try {
out = new ObjectOutputStream(oo);
}
catch (IOException ex) {
} try {
out.writeObject(this);
}
catch (IOException ex1) {
} ByteArrayInputStream ii = new ByteArrayInputStream(oo.toByteArray());
ObjectInputStream in = null;
try {
in = new ObjectInputStream(ii);
}
catch (IOException ex2) {
} try {
return in.readObject();
}
catch (ClassNotFoundException ex3) {
return null;
}
catch (IOException ex3) {
return null;
}
}
在clone()方法中,只有 o=super.clone(); 一句。难道只要复制父类,而自己不用复制吗?
然后一点就是重写默认的 clone方法,必须使用super.clone()方法,调用父类的clone方法.
重写这个默认的clone方法,还是要把浅克隆通过super.clone()方法实现深克隆.不知道能不能这么说明...最少偶是明白了这个道理了的=.-=
class Test implements Cloneable
{
Object o=null;
String name;
Test(String name)
{
this.name=name;
}
public Object clone()
{
try
{
o=super.clone(); //为什么要调用这句?
}
catch(Exception e)
{
System.out.println(e.toString());
}
return o;
}
public static void main(String[] args)
{
Test one=new Test("one");
Test two=(Test)one.clone();
System.out.println(two.name);
}}那就看上面的代码:
Test two=(Test)one.clone();
调用 one 的 clone 方法,也就是调用 super.clone()。 然而在下面的语句 System.out.println(two.name); 却打印出 one ,为什么?super.clone() 只复制了父类对象,并没有复制子类的 name 属性。