java - 通过子类包限定符导入父类的内部接口(interface)

标签 java inheritance import inner-classes

我有两个这样的类:

父类A:

public class A {   
  public interface A2 {
  }
}

B 类 child :

public class B extends A {
}

当我使用 A 的内部接口(interface)时:

import com.company.A.A2;         //statement 1
import com.company.B.A2;         //statement 2 -> error here!

//...
com.company.A.A2 a21;            //statement 3
com.company.B.A2 a22;            //statement 4

除了我标记的那个(statement 2)之外,所有的陈述都是有效的。我想知道:

  • 为什么我可以使用完全限定符“com.company.B.A2”声明为声明 4 但我不能使用声明 2?

附言: 我知道 com.company.A.A2 和 com.company.A.A2 是确切 1 类的 2 个别名。

  • 如果 Java 允许语句 4,它应该允许语句 2
  • 如果 Java 不允许语句 4,它不应该允许语句 4, 也是
  • 如果 Java 允许语句 4 有效,我认为这真的是模棱两可的。

最佳答案

JLS 6.7, Fully Qualified Names and Canonical Names (截断)

Each member class, member interface, and array type may have a fully qualified name:

  • A member class or member interface M of another class or interface C has a fully qualified name if and only if C has a fully qualified name.

    In that case, the fully qualified name of M consists of the fully qualified name of C, followed by ".", followed by the simple name of M.

Each member class, member interface, and array type may have a canonical name:

  • A member class or member interface M declared in another class or interface C has a canonical name if and only if C has a canonical name.

    In that case, the canonical name of M consists of the canonical name of C, followed by ".", followed by the simple name of M.

示例 6.7-2 特别指出您示例中的 *.A.A2*.B.A2 都是接口(interface)的 FQN,但只有 *.A.A2规范 名称,因为那是 A2声明的地方。

JLS 7.5, Import Declarations

  • A single-type-import declaration (§7.5.1) imports a single named type, by mentioning its canonical name (§6.7).

关于java - 通过子类包限定符导入父类的内部接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57351966/

相关文章:

java - Spring aop表达式

java - 这段java代码是什么意思

c++ - 覆盖虚函数和隐藏非虚函数有什么区别?

java - JAX-RS 响应的效用与组合与继承

python - 'import feedparser' 通过 SSH 工作,但在浏览器中时失败

java - 以编程方式将新类添加到项目中

java - Android RecyclerView.Adapter更改图标onClick

java - SimpleDateFormat 未产生预期输出

python - 删除继承类Python中的类属性

javascript - 未捕获的语法错误 : Unexpected identifier when trying to import React