为什么Java禁止内部接口的继承? [英] Why is Java prohibiting inheritance of inner interfaces?

查看:197
本文介绍了为什么Java禁止内部接口的继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即。为什么不能执行以下循环依赖?

  public class Something implements Behavior {
public interface Behavior {
// ...
}
}

不应该引用外部类,这应该是允许的;然而,编译器迫使我在类之外定义这些接口。这个行为有什么逻辑的解释吗?

解决方案

规范中的相关规则:



http://java.sun .com / docs / books / jls / third_edition / html / classes.html#8.1.4


取决于类型T,如果T的扩展或实现子句中的T被提及为超类或超级接口,或者作为超类或超级接口名称的限定符。


http:/ /java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.1.3


一个接口我直接依赖于一个类型T,如果T在我的extends子句中被提及作为一个超级接口,或者作为superinterface名称中的限定符。


A extends |实现BC ,A取决于 C B 。规范然后禁止循环依赖。



在依赖关系中包含 B 的动机尚不清楚。正如你所提到的,如果 BC 被提升到顶级 C2 ,就像类型系统是不同的关心,所以为什么 A扩展C2 是可以的,但不是 A延伸BC ?授予一个嵌套类型 BC 确实有一些可以访问 B 的内容,但是我找不到任何东西规则使得 A延伸BC 麻烦。



唯一的问题是当 C 是一个内部类。假设 B = A A扩展A.C 应该被禁止,因为有一个包围实例的循环依赖。这可能是真正的动机 - 禁止外部类继承内部类。实际规则更广泛,因为它们更简单,甚至对于非内部类也是有意义的。


I.e. why is the following "cyclic dependency" not possible?

public class Something implements Behavior {
    public interface Behavior {
        // ...
    }
}

Since interfaces don't reference the outer class this should be allowed; however, the compiler is forcing me to define those interfaces outside the class. Is there any logical explanation for this behavior?

解决方案

Relevant rules in spec:

http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.1.4

A class C directly depends on a type T if T is mentioned in the extends or implements clause of C either as a superclass or superinterface, or as a qualifier of a superclass or superinterface name.

http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.1.3

An interface I directly depends on a type T if T is mentioned in the extends clause of I either as a superinterface or as a qualifier within a superinterface name.

Therefore if A extends|implements B.C, A depends on both C and B. Spec then forbids circular dependencies.

The motivation of including B in the dependency is unclear. As you mentioned, if B.C is promoted to top level C2, not much is different as far as the type system is concerned, so why A extends C2 is ok, but not A extends B.C? Granted a nested type B.C does have some prviledged access to B's content, but I can't find anything in spec that makes A extends B.C troublesome.

The only problem is when C is an inner class. Suppose B=A, A extends A.C should be forbidden, because there's a circular dependency of "enclosing instance". That is probably the real motivation - to forbid outer class from inheriting inner class. The actual rules are more generalized, because they are simpler, and make good sense anyway even for non-inner classes.

这篇关于为什么Java禁止内部接口的继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆