摘要:本文主要向大家介绍了JAVA语言:对象的复制(深复制和浅复制),通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
本文主要向大家介绍了JAVA语言:对象的复制(深复制和浅复制),通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
1、浅复制表示复制目标对象本身,并不会复制目标对象的引用
2、深复制表示复制目标对象本身,并且复制目标对象的引用
3、对象复制的步骤:
3.1:实现Cloneable这个标志接口
3.2:重写Object类的clone方法,并将该方法访问修饰符改成Public
3.3:必须调用父类的clone方法,因为可以识别要复制对象的类型等 super.clone();
public class clone {
public static void main(String[] args) throws CloneNotSupportedException {
Student s1=new Student();
s1.setAge(20);
s1.setName(new Teacher());
Student s2=(Student)s1.clone();
//此行代码可以证明浅赋值 因为两个对象的地址一样
System.out.println(s1.getName()==s2.getName());
System.out.println("------------------------------------------");
Student2 s3=new Student2();
s3.setName(s1);
Student2 s4=(Student2)s3.clone();
//此行代码可以证明深赋值 因为两个对象的地址不一样
System.out.println(s4.getName()==s3.getName());
}
}
//对象的浅复制
class Student implements Cloneable{
private int age;
private Teacher tname;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Teacher getName() {
return tname;
}
public void setName(Teacher name) {
this.tname = tname;
}
@Override
public Object clone() throws CloneNotSupportedException {
Object obj=super.clone();
return obj;
}
}
class Teacher{
}
class Student2 implements Cloneable{
private int age;
private Student tname;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student getName() {
return tname;
}
public void setName(Student name) {
this.tname = name;
}
@Override
public Object clone() throws CloneNotSupportedException {
Student2 obj=(Student2)super.clone();
obj.tname=(Student)this.tname.clone();
return obj;
}
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号