为什么Object clone()方法仅对实现Cloneable接口的类可用? [英] Why Object clone() method available only to classes that implement Cloneable interface?

查看:70
本文介绍了为什么Object clone()方法仅对实现Cloneable接口的类可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 clone()是一种受保护的方法,但是受保护"意味着特定类的所有子类都可以访问它.

I know that clone() is a protected method, but "protected" means that it is accessible for all subclasses of particular class.

任何Java类都是 Object 的子类,那么这里使用受保护方法的原因是什么?

Any Java class is a subclass of Object, so what is the reason for the protected method here?

为什么我们只能在实现 Cloneable 接口的类上调用 clone()?我不明白它如何与以下事实联系在一起:在 Object 中的 clone()被声明为受保护的.

And why can we call clone() only on classes that implement the Cloneable interface? I can't understand how it connects to the fact that clone() in Object is declared as protected.

推荐答案

对象的clone()方法非常特殊,因为它总是返回当前类的实例,该实例复制了所有字段(甚至最后一个字段).我认为不可能用普通的Java代码来重现它,甚至不能通过反射来实现.

Object's clone() method is quite special, as it always returns an instance of the current class that has all fields copied (even final). I don't think its possible to reproduce this with plain Java code, not even with reflection.

因此,必须使所有类都可以使用它,但是由于默认情况下不应从外部调用它,因为您不希望所有内容都是可克隆的,因此必须对其进行保护.

Because of this, it must be made available to all classes, but since it should not be callable from the outside by default because you don't want everything to be cloneable, it must be protected.

作为另一项检查, clone 检查该类是否实现了 Cloneable ,只是为了确保您不会偶然克隆非克隆对象.

As an additional check, clone checks that the class implements Cloneable, only to ensure you don't clone non-cloneables by accident.

总而言之,克隆有些中断,因为当您需要深度复制最终字段时,克隆将不起作用.我建议您按照此模式手动实施实例复制.

All in all, cloning is somewhat broken because it doesn't work when you need to deep-copy final fields. I recommend you implement instance copying manually, following this pattern.

public class Base {

    /** one or more public constructors */
    public Base() { ... }

    /** copy-constructor */
    protected Base(Base src) { /* copy or deep-copy the state */ }

    public Base copy() { return new Base(this); }
}

public class Derived extends Base {

    /** one or more public constructors */
    public Derived() { ... }

    /** copy-constructor */
    protected Derived(Derived src) { 
        super(src);
        /* copy or deep-copy the state */ 
    }

    @Override
    public Derived copy() { return new Derived(this); }
}

这篇关于为什么Object clone()方法仅对实现Cloneable接口的类可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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