Java克隆方法如何工作? [英] How does the Java clone method work?

查看:49
本文介绍了Java克隆方法如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Student implements Cloneable {
    public Student clone() {
        Student clonedStudent = (Student) super.clone();
        return clonedStudent;
    }
}

为什么Java返回学生对象而不是返回对象类对象.由于我们正在使用超级.这是否意味着Java本身在clone方法中提供了浅层克隆?

Why does Java return student object instead of returning object class object. As we are using super. Does it mean Java itself provides shallow cloning in the clone method?

推荐答案

Java克隆是按域复制的字段,即因为Object类对关于clone()的类的结构不了解方法将被调用.

java cloning is field by field copy i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked.

1)如果类仅具有原始数据类型成员,则将创建该对象的全新副本,并返回对新对象副本的引用

1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.

2)如果该类包含任何类类型的成员,则仅复制对那些成员的对象引用,因此原始对象和克隆对象中的成员引用指同一对象.

2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

引用此链接 Java中的对象克隆

这篇关于Java克隆方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆