Java: 在克隆之前进行类型转换?

Java: Type cast before clone?

编辑:当我需要克隆一个对象时遇到这个问题,我已经搜索过但没有问题解决我的问题。

当我学习 Java 中的原型模式时,我遵循了一些教程并且对 (Bike)super.clone() 的类型转换感到困惑。

哪个先做? (Bike)super 还是 super.clone()?为什么需要 (Bike)

public interface Prototype extends Cloneable
{
    public Prototype clone() throws CloneNotSupportedException;
}

public class Bike implements Prototype
{
    // Constructor and other methods...

    // My question is here
    public Prototype clone() throws CloneNotSupportedException {
        return (Bike)super.clone();
    }
}

首先执行 class super.clone(),然后使用 (Bike) 转换结果(转换应用于后面表达式的结果)。

您需要强制转换,因为您要覆盖 Object#clone(),它可以追溯到前泛型 JDK1.0,并且具有 return 类型的 Object

转换的优先级低于函数调用:

(Foo) a.f1().f2().f3() // Casts to Foo at the end of the calls chain

在您的情况下,强制转换是必要的,因为您正在调用 super.clone(),这是从 Object.clone() 继承的方法,其中 returns 和 Object

由于 Prototype 是自行车的超级 class,当调用 super.clone() 时,将返回一个克隆对象,然后将其显式类型转换为更具体的子 class原型,即自行车。

需要类型铸造以满足自行车的要求 class。 更一般的观点是,每个创建的对象都有 Object class 作为它的 super class 但也有用户定义的方法,这些方法没有定义到 super class(Object class) .一旦将其类型转换为子对象 class,您就可以从同一对象访问父方法和子方法