public class Subject {
private String name;
public Subject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Student implements Cloneable {
private String name;
private Subject subject;
public Student(String name, String sub) {
this.name = name;
this.subject = new Subject(sub);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class CopyTest {
public static void main(String[] args) {
Student student = new Student("yang","haodong");
try {
Student studentCopy = (Student) student.clone();
System.out.println("原对象和拷贝对象是否一致"+( student == studentCopy ) );
System.out.println("原对象和拷贝对象的name属性是否一样"+(Objects.equals(student.getName(), studentCopy.getName())));
System.out.println("原对象和拷贝对象的地址属性是否一样"+(student.getSubject() == studentCopy.getSubject()));
student.setName("li");
student.getSubject().setName("hao");
System.out.println("能否更改基本数据类型属性"+studentCopy.getName());
System.out.println("能否更改引用类型属性"+studentCopy.getSubject().getName());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
原对象和拷贝对象是否一致false
原对象和拷贝对象的name属性是否一样true
原对象和拷贝对象的地址属性是否一样true
能否更改基本数据类型属性yang
能否更改引用类型属性hao
Process finished with exit code 0