public class Test3
{
public static void main(String[] args)
{
X x=null;
pass(x);
if(x!=null)
System.out.println(x.str);
}
static void pass(X x)
{
X x1=new X("hello");
try{
x=(X)x1.clone();
}
catch(Exception e)
{}
}
}
class X  implements Cloneable{
String str;
X(){}
X(String str)
{
this.str=str;
}
protected Object clone() throws CloneNotSupportedException
{
super.clone();
return this;
}
}
////
我以为它会打印出"hello“,谁知道它什么也没打印出来,那clone还有什么用?

解决方案 »

  1.   

    clone是用来实现深拷贝的,你要自己写方法。
      

  2.   

    class XYZ implements Cloneable{
        String str;    XYZ() {
        }    XYZ(String str) {
            this.str = str;
        }    protected Object clone() throws CloneNotSupportedException {
            super.clone();
            return this;
        }    public static void main(String[] args) {
            XYZ x = null;
            pass(x);
            if (x != null) {
                System.out.println(x.str);
            } else {
                System.out.println("x is null");
            }
            XYZ x2 = new XYZ("hi");
            try {
                x = (XYZ) x2.clone();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(x.str);
        }    static void pass(XYZ x) {
            XYZ x1 = new XYZ("hello");
            try {
                x = (XYZ) x1.clone();
                System.out.println(x.str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }输出 
    hello
    x is null
    hi解析,你传入pass的X 是NULL的,所以不是引用,即传入地址。所以即使CLONE成功,你原先的X还是一个NULL。呵呵,只要你将X x=null; 改成X x= new X("aa");就会出现不同的结果,你自己试一下。
    如果改成X x= new X();就又会是另外一种结果,自己看看。