日期:2014-05-20 浏览次数:20726 次
public class Test {
public static void main(String[] args) throws CloneNotSupportedException{
User2 user2=new User2();
user2.name="April_1";
user2.age=11;
Book2 book2=new Book2();
book2.user=user2;
book2.price=1111;
book2.name="TEST_1";
Book2 cloneBook2= book2.clone();
cloneBook2.user.name="April_2";
cloneBook2.user.age=22;
cloneBook2.name="TEST_2";
cloneBook2.price=2222;
//output:April_2 , TEST_1 ,1111,22
System.out.format("%s , %s ,%d,%d",book2.user.name,book2.name,book2.price,book2.user.age);
}
}
class User2 implements Cloneable{
String name;
int age;
@Override
public User2 clone() throws CloneNotSupportedException {
return (User2) super.clone();
}
}
class Book2 implements Cloneable{
User2 user;
String name;
int price;
@Override
public Book2 clone() throws CloneNotSupportedException {
Book2 book2=null;
book2=(Book2)super.clone();
if(user==null){
book2.user=user.clone();
}
return book2;
}
}