0
点赞
收藏
分享

微信扫一扫

clone(深复制)

爱上流星雨 2022-11-04 阅读 77

package com.ygl.annotion;



public class TestClone {

public static void main(String[] args) {

Teacher teacher=new Teacher();

teacher.setAge(35);

teacher.setName("ll");

Student2 student=new Student2();

student.setAge(26);

student.setName("ygl");

student.setTeacher(teacher);


try {

Student2 stu=(Student2)student.clone();

System.out.println(stu.getName());

System.out.println(stu.getTeacher().getName());

teacher.setName("teacher");


System.out.println(stu.getTeacher().getName());


} catch (CloneNotSupportedException e) {


e.printStackTrace();

}


}

}



class Student2 implements Cloneable {


private int age;

private String name;

private Teacher teacher;

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Teacher getTeacher() {

return teacher;

}

public void setTeacher(Teacher teacher) {

this.teacher = teacher;

}




@Override

public Object clone() throws CloneNotSupportedException {

Student2 stu=(Student2)super.clone();

stu.setTeacher((Teacher)(stu.getTeacher().clone()));

return stu;

}


}

class Teacher implements Cloneable{

private int age;

private String name;

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}




@Override

public Object clone() throws CloneNotSupportedException {

Object obj=super.clone();

return obj;

}


}

举报

相关推荐

0 条评论