java中物件的建立(clone)
阿新 • • 發佈:2018-12-09
[java] view plain copy print?
- staticclass 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;
- }
- }
- staticclass Head implements Cloneable{
- public Face face;
- public Head() {}
- public Head(Face face){this.face = face;}
- @Override
- protected Object clone() throws CloneNotSupportedException {
- returnsuper.clone();
- }
- }
- staticclass Face{}
- publicstaticvoid 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));
- }
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