?
自驗(yàn)證:創(chuàng)建Class Student兩個(gè)類, Student中含有Class對(duì)象
public class Class implements Cloneable {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
public Class(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Student implements Cloneable {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Class getClazz() {
return clazz;
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
private String name;
private int age;
private Class clazz;
public Student(String name, int age, Class clazz) {
this.name = name;
this.age = age;
this.clazz = clazz;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
測(cè)試代碼:
public class Copy {
public static void main(String[] args) throws CloneNotSupportedException {
Class clazz = new Class("一班");
Student student = new Student("張三", 18, clazz);
Student newStudent = (Student) student.clone();
student.getClazz().setName("二班");
System.out.println("=== student===");
System.out.println(student);
System.out.println(student.getName());
System.out.println(student.getAge());
System.out.println(student.getClazz());
System.out.println(student.getClazz().getName());
System.out.println("=== newStudent===");
System.out.println(newStudent);
System.out.println(newStudent.getName());
System.out.println(newStudent.getAge());
System.out.println(newStudent.getClazz());
System.out.println(newStudent.getClazz().getName());
}
}
輸出:
可以看到不同的Student對(duì)象,但是有相同的Class對(duì)象
修改Student clone方法:
@Override
protected Object clone() throws CloneNotSupportedException {
Student student = (Student) super.clone();
student.setClazz((Class) clazz.clone());
return student;
}
可以看到不同的class對(duì)象,不同的值:
知識(shí)來源:
【23版面試突擊】什么是淺拷貝和深拷貝_嗶哩嗶哩_bilibili
強(qiáng)引用、弱引用介紹:文章來源:http://www.zghlxwxcb.cn/news/detail-669277.html
https://www.cnblogs.com/Scott007/archive/2013/05/15/3080739.html文章來源地址http://www.zghlxwxcb.cn/news/detail-669277.html
到了這里,關(guān)于java八股文面試[java基礎(chǔ)]——淺拷貝和深拷貝的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!