1. 程式人生 > >java中物件的建立(clone)

java中物件的建立(clone)

[java] view plain copy print?
  1. staticclass Body implements Cloneable{  
  2.     public Head head;  
  3.     public Body() {}  
  4.     public Body(Head head) {this.head = head;}  
  5.     @Override
  6.     protected Object clone() throws CloneNotSupportedException {  
  7.         Body newBody =  (Body) super.clone();  
  8.         newBody.head = (Head) head.clone();  
  9.         return newBody;  
  10.     }  
  11. }  
  12. staticclass Head implements Cloneable{  
  13.     public  Face face;  
  14.     public Head() {}  
  15.     public Head(Face face){this.face = face;}  
  16.     @Override
  17.     protected Object clone() throws CloneNotSupportedException {  
  18.         returnsuper.clone();  
  19.     }  
  20. }   
  21. staticclass Face{}  
  22. publicstaticvoid main(String[] args) throws CloneNotSupportedException {  
  23.     Body body = new Body(new Head(new Face()));  
  24.     Body body1 = (Body) body.clone();  
  25.     System.out.println(”body == body1 : ” + (body == body1) );  
  26.     System.out.println(”body.head == body1.head : ” +  (body.head == body1.head));  
  27.     System.out.println(”body.head.face == body1.head.face : ” +  (body.head.face == body1.head.face));  
  28. }  
   static class Body implements Cloneable{
        public Head head;
        public Body() {}
        public Body(Head head) {this.head = head;}

        @Override
        protected Object clone() throws CloneNotSupportedException {
            Body newBody =  (Body) super.clone();
            newBody.head = (Head) head.clone();
            return newBody;
        }

    }

    static class Head implements Cloneable{
        public  Face face;

        public Head() {}
        public Head(Face face){this.face = face;}
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    } 

    static class Face{}

    public static void main(String[] args) throws CloneNotSupportedException {

        Body body = new Body(new Head(new Face()));

        Body body1 = (Body) body.clone();

        System.out.println("body == body1 : " + (body == body1) );

        System.out.println("body.head == body1.head : " +  (body.head == body1.head));

        System.out.println("body.head.face == body1.head.face : " +  (body.head.face == body1.head.face));


    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
列印結果為: