对象克隆实例

A.java

package second;



public class B {

    public static void main(String[] args){

        C c = new C();

        c.i = 200;

        c.haha();

        System.out.println("==========");

        C cl = (C)c.clone();

        cl.i = 500;

        cl.haha();

        c.haha();

    }

}

B.java

package second;



class C implements Cloneable{ //实现克隆接口

    public int i = 100;

    void haha() {

        System.out.println(i);

    }

    public Object clone(){

        C handler = null;

        try{

            handler = (C)super.clone();

        }catch(CloneNotSupportedException e){

            e.printStackTrace();

        }

        return handler;

    }

}

结果:

200

==========

500

200

 

你可能感兴趣的:(对象)