可以使用构造函数克隆方法创建对象 [英] Can clone method create object using constructor

查看:175
本文介绍了可以使用构造函数克隆方法创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为 clone()创建一个对象而不调用构造函数。

I always thought that clone() creates an object without calling a constructor.

但是,在阅读时有效的Java 第11项:明智地覆盖克隆,我发现一条声明说

But, while reading Effective Java Item 11: Override clone judiciously, I found a statement which says that


no的规定构造函数被称为太强大了。一个
表现良好的克隆方法可以调用构造函数来创建正在构建的克隆内部的对象
。如果类是final,clone
甚至可以返回由构造函数创建的对象。

The provision that "no constructors are called" is too strong. A well-behaved clone method can call constructors to create objects internal to the clone under construction. If the class is final, clone can even return an object created by a constructor.

有人可以解释一下这个我?

Can someone please explain this to me?

推荐答案


我一直认为clone()在不调用构造函数的情况下创建一个对象。 / p>

I always thought that clone() creates an object without calling a constructor.

Object.clone()中的实现不会调用构造函数。

The implementation in Object.clone() doesn't call a constructor.

没有什么能阻止你以自己的方式实现它。例如,这是一个完全有效的 clone()实现:

There's nothing to stop you from implementing it yourself in a way which does. For example, this is a perfectly valid clone() implementation:

public final class Foo implements Cloneable {
    private final int bar;

    public Foo(int bar) {
        this.bar = bar;
    }

    @Override
    public Object clone() {
        return new Foo(bar);
    }
}

如果上课,你只能这样做(无条件)是 final ,因为那样你就可以保证返回与原版相同类型的对象。

You can only do this (unconditionally) if the class is final, because then you can guarantee to be returning an object of the same type as the original.

如果这个类不是最终的,我想你可以检查实例是否只是一个覆盖 clone()的类型的实例并处理在不同的情况下它有所不同......但这样做会很奇怪。

If the class isn't final, I guess you could check whether the instance was "just" an instance of the type overriding clone() and handle it differently in different cases... it would be odd to do so though.

这篇关于可以使用构造函数克隆方法创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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