扩展内部接口?

11
我有一个简单的问题:
为什么Eclipse会强调实现这两个接口?
public abstract class Gateway implements IPlayerity, IItemity {
    public interface IPlayerity { ... }
    public interface IItemity { ... }
    // I...ity
}

我收到了这个错误信息:

IPlayerity无法解析为一种类型


@jason IPlayerity 无法解析为类型。 - imacake
4个回答

5

根据JLS的工作方式,您存在无法解决的循环依赖关系(虽然我不确定JLS在哪里记录了这一点)。

由于IPlayerity和IItemity接口位于NestedInterfaces类内部,因此在NestedInterfaces类头定义中它们是不可见的。可以通过更改程序来解决此问题:

public class NestedInterfaces implements 
      NestedInterfaces.IPlayerity, NestedInterfaces.IItemity 
{
    public interface IPlayerity {}
    public interface IItemity {}
}

但是Eclipse给了我这个错误,它更加清晰明了:
 Multiple markers at this line
 - Cycle detected: the type NestedInterfaces cannot extend/implement itself or one of its own member types
 - Cycle detected: the type NestedInterfaces cannot extend/implement itself or one of its own member types

2
那么我们如何解决“检测到循环依赖”的问题呢? - Pacerier
循环侦测通过在实现类外定义接口解决。 - Ahmed Hegazy

5

在另一个文件中声明接口。对我来说,顶级类无法实现嵌套在自身内部的接口(尽管我不确定原因)。

如果您想将接口保留在同一文件中,则必须将修饰符从public更改为default,并在类定义之后声明它们。


1
我认为原因在于类加载的工作方式。对其他类的普通引用是惰性加载的,但外部类、超类和实现的接口会在类本身加载之前自动加载。当您的外部类实现内部接口并且该构造有效时,在运行时加载类时,您将在类加载器中获得StackOverflowError错误。 - mihi

0

我看到这两个接口不是默认的Java接口,对吧?所以,如果你遇到了“IPlayerity无法解析为类型”的错误,请检查你是否已经导入了正确的包。我应该为此发表评论,但我就是做不到。祝你玩得愉快。


-1
如果无法将其解析为类型,则无法“看到”它。您应该为接口添加一个导入:
import package.Gateway.IPlayerity
import package.Gateway.IItemity

不过我有一种感觉,编译器会抛出其他奇怪的循环错误。

最好在另一个文件中定义接口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接