class Student implements Cloneable{ //一定要写克隆接口,不然public Object clone()不会实现。
String name = "ab";
int age = 2;
Teacher t;
Student(String name , int age){
this.age = age;
this.name = name;
}
Student(String name , int age, Teacher t){
this.age = age;
this.name = name;
this.t = t;
}
public Object clone() { //方法重写了Lang包里的clone()方法。
Object o = null;
try {
o = super.clone(); //因为lang包下的clone()是有异常抛出的!所以要try catch语句捕获.
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
class Teacher{
String name;
Teacher(String name){
this.name = name;
}
}
public class Clone_Main{
public static void main(String[] args){
Student s1 = new Student("s1",12);
Student s2 ;
s2 = (Student) s1.clone(); //注意要强制转换成目标类.
System.out.println("s1'name: "+s1.name+"/t"+"s1.age "+s1.age);
System.out.println("s2'name: "+s2.name+"/t"+"s2.age "+s2.age);
System.out.println(s1);
System.out.println(s2);
s2.age = 122; //这里是给s2改变年龄,而s1的年龄是没有变的,所以这个和引用的拷贝有
//本质的区别.如果是引用的拷贝,则s1的年龄也改变了!
System.out.println("s1'name: "+s1.name+"/t"+"s1.age "+s1.age);
System.out.println("s2'name: "+s2.name+"/t"+"s2.age "+s2.age);
System.out.println("-------------------------------------------------");//分隔符!
Teacher tt = new Teacher("lisi");
Student s3 = new Student("s3",21,tt); //这次利用构造函数重载,新建立了一个聚合老师类的
//学生类。
Student s4;
s4 = (Student)s3.clone(); //s3与s4克隆
s4.t.name = "new name"; //修改S4里的成员变量teacher的name;
s4.name = "s4";
s4.age = 44;
System.out.println("s3'name: "+s3.name+"/t"+"s1.age "+s3.age);
System.out.println("s24name: "+s4.name+"/t"+"s2.age "+s4.age);
System.out.println("s3'teacher: "+s3.t.name);//打印结果显示S3,S4的teacher的name是一样的,
//说明S3,S4的teacher t是同一个引用值!
System.out.println("s4'teacher: "+s4.t.name);
System.out.println("s3'teacher: "+s3.t); //通过打印S3,S4的teacher的地址则证实了是同一处引用!
System.out.println("s4'teacher: "+s4.t);
}
}