【发布时间】:2015-10-20 09:42:21
【问题描述】:
让我们有这样的类结构:
public interface TypeIdentifiable {}
public interface TypeCloneable extends Cloneable {
public Object clone() throws CloneNotSupportedException;
}
public class Foo implements TypeCloneable, TypeIdentifiable {
@Override
public Object clone() throws CloneNotSupportedException {
// ...
return null;
}
}
public abstract class AbstractClass<T extends TypeCloneable & TypeIdentifiable> {
public void foo(T element) throws Exception {
TypeCloneable cloned = (TypeCloneable) element.clone();
System.out.println(cloned);
}
}
我有这个编译错误(尽管 IDE,在我的例子中是 Intellij,在编码时无法显示错误)
Error:(4, 37) java: clone() in java.lang.Object cannot implement clone() in foo.TypeCloneable attempting to assign weaker access privileges; was public
我知道编译器试图从Object 而不是TypeCloneable 调用clone() 方法,但我不明白为什么。我还尝试将它转换为 TypeCloneable(我假设编译器会知道在这种情况下调用哪个 clone() 方法,但同样的问题)。
public void foo(T element) throws Exception {
TypeCloneable typeCloneable = (TypeCloneable) element;
TypeCloneable cloned = (TypeCloneable) typeCloneable.clone();
}
我有点困惑...我可以在这里做些什么来强制从 TypeCloneable 调用 clone() 吗?
谢谢你的帮助
【问题讨论】:
-
如果我正确理解 JLS,这应该可以编译。我认为这是一个错误。 stackoverflow.com/questions/33023332/…
-
所以是的...这似乎是一个错误。我没有找到这个问题。谢谢!
标签: java generics intellij-idea compiler-errors clone