0
点赞
收藏
分享

微信扫一扫

clone(浅复制)

秀妮_5519 2022-11-04 阅读 66

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) {

// TODO Auto-generated catch block

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 {

Object obj=super.clone();

return obj;

}


}

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;

}




}

举报

相关推荐

0 条评论