tro*_*oig 5 java generics clone compiler-errors intellij-idea
让我们有这个类结构:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我有这样的编译错误(虽然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
Run Code Online (Sandbox Code Playgroud)
我知道编译器试图从而不是调用clone()方法,但我不明白为什么.我也试过它转换为(我认为编译器会知道在这种情况下调用哪个方法,但同样的问题).ObjectTypeCloneableTypeCloneableclone()
public void foo(T element) throws Exception {
TypeCloneable typeCloneable = (TypeCloneable) element;
TypeCloneable cloned = (TypeCloneable) typeCloneable.clone();
}
Run Code Online (Sandbox Code Playgroud)
我有点困惑......我可以在这里做些什么来强制从TypeCloneable调用clone()吗?
谢谢你的帮助
这对我有用,(我猜测这是 Type & Type upperbound 语法的问题):
interface TypeIdentifiable {}
interface TypeCloneable extends Cloneable {
public Object clone() throws CloneNotSupportedException;
}
class Foo implements TypeCloneable, TypeIdentifiable {
@Override
public Object clone() throws CloneNotSupportedException {
// ...
return null;
}
}
interface TypeCloneableAndIndetifiable extends TypeCloneable, TypeIdentifiable {
}
abstract class AbstractClass<T extends TypeCloneableAndIndetifiable> {
public void foo(T element) throws Exception {
TypeCloneable cloned = (TypeCloneable) element.clone();
System.out.println(cloned);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
621 次 |
| 最近记录: |