首先,来个demo,引出问题
/**
*@文件名 M.java
*@创建日期 2013-11-19 上午9:39:33
*@作者 小郑
*/
public class M {
/**
*所在包:
* @param args
* @throws CloneNotSupportedException
*/
public static void main(String[] args) throws CloneNotSupportedException {
N n1= new N();
N n2= new N();
n1.name="n1";
n2=n1;
n2.name="n2";
System.out.println(n1.name);
System.out.println(n2.name);
}
}
class N implements Cloneable{
public String name;
@Override
public N clone() throws CloneNotSupportedException {
System.out.println("clone");
return (N) super.clone();
}
}
输出如下:
n2
n2
看下面demo,解决问题:
/**
*@文件名 M.java
*@创建日期 2013-11-19 上午9:39:33
*@作者 小郑
*/
public class M {
/**
*所在包:
* @param args
* @throws CloneNotSupportedException
*/
public static void main(String[] args) throws CloneNotSupportedException {
N n1= new N();
N n2= new N();
n1.name="n1";
n2=n1.clone();
n2.name="n2";
System.out.println(n1.name);
System.out.println(n2.name);
}
}
class N implements Cloneable{
public String name;
@Override
public N clone() throws CloneNotSupportedException {
System.out.println("clone");
return (N) super.clone();
}
}
输出如下:
clone
n1
n2