Java clone()方法 [英] Java clone() method

查看:116
本文介绍了Java clone()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过J.Bloch的Effective Java,这里写道:

I read Effective Java by J.Bloch and here was wrote:


如果你设计一个继承类,请注意如果你选择不是
来提供一个行为良好的受保护克隆方法,子类实现Cloneable是不可能的

If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

我有A类:

public class A{}

B类扩展A类:

public class B extends A implements Cloneable {

}

所以在这种情况下我无法覆盖 clone()方法?如果是,请解释原因。

So in this case I can't to override clone() method? If yes, than please explain why.

推荐答案

在您的情况下,您可以覆盖 clone()

In your case yes you can override clone():

public class A {
}

public class B extends A implements Cloneable {

    @Override
    public B clone() throws CloneNotSupportedException {
        return (B) super.clone();
    }
}

并且仍然有一个有效的克隆机制 - 因此你是当你陈述实现Cloneable 时说实话。

and still have an effective clone mechanism - you are therefore telling the truth when you state implements Cloneable.

然而,打破这个承诺所需的一切就是给予 A a 私人变量。

However, all that is needed to break that promise is to give A a private variable.

public class A {
    private int a;
}

现在你的承诺被破坏 - 除非A实现克隆,在这种情况下你可以使用 super.clone()

and now your promise is broken - unless A implements clone, in which case you can use super.clone():

public class A {

    private int a;

    @Override
    public A clone() throws CloneNotSupportedException {
        A newA = (A) super.clone();
        newA.a = a;
        return newA;
    }
}

public class B extends A implements Cloneable {

    private int b;

    @Override
    public B clone() throws CloneNotSupportedException {
        B newB = (B) super.clone();
        newB.b = b;
        return newB;
    }
}

基本上 - 正如Joshua Bloch所说 - 如果你不知道实现 clone 您的子类也不能(通常)。

Essentially - as Joshua Bloch states - if you don't implement clone your sub-classes also cannot (generally).

这篇关于Java clone()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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