泛型问题:clone()尝试分配较弱的访问权限

时间:2015-10-20 09:42:21

标签: java generics intellij-idea compiler-errors clone

让我们有这个类结构:

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

我知道编译器试图从clone()而不是Object调用TypeCloneable方法,但我不明白为什么。我也试过它转换为TypeCloneable(我认为编译器会知道在这种情况下调用哪个clone()方法,但同样的问题)。

   public void foo(T element) throws Exception {
      TypeCloneable typeCloneable = (TypeCloneable) element;
      TypeCloneable cloned = (TypeCloneable) typeCloneable.clone();
   }

我有点困惑......我可以在这里做些什么来强制从TypeCloneable调用clone()吗?

感谢hellp

1 个答案:

答案 0 :(得分:2)

这对我有用,(我猜这是Type&amp; Type上限语法的问题):

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);
   }
}