编辑:当我需要克隆一个对象时,我遇到了这个问题,我已经搜索过,但毫无疑问解决了我的问题。
当我学习 Java 原型(prototype)模式时,我遵循了一些教程,并对 (Bike)super.clone()
的类型转换感到困惑。
哪个先完成? (Bike)super
还是 super.clone()
?为什么需要(自行车)
?
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();
}
}
最佳答案
强制转换的优先级低于函数调用:
(Foo) a.f1().f2().f3() // Casts to Foo at the end of the calls chain
在您的情况下,强制转换是必要的,因为您正在调用 super.clone()
,这是从 Object.clone()
继承的方法。它返回一个对象
关于Java:克隆之前进行类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43204770/