java - 在封闭类的父类(super class)型声明中使用嵌套类型作为泛型类型参数

标签 java generics inner-classes

我基本上有一个问题,为什么以下不起作用。我有一个抽象类:

public abstract class Abstrct <T> {

}

然后,我定义了一个类,该类使用了一个公共(public)内部类,我想将其用于泛型参数,如下所示:

public class Outer extends Abstrct<Inner> {
    public class Inner {

    }
}

由于我仍在学习 Java,所以我对它为什么不起作用更感兴趣。与其说是如何让它发挥作用,不如说是我对此也很感兴趣。

最佳答案

Inner 不在 Outer 类声明的范围内。在 extends 子句中使用时,它不是已知的类型名称。使用合格的引用:

class Outer extends Abstract<Outer.Inner>

或者导入它:

import com.example.Outer.Inner;

根据规范,关于 Scope :

The scope of a declaration of a member m declared in or inherited by a class type C (§8.1.6) is the entire body of C, including any nested type declarations.

extends 子句是类的 Superclass 声明的一部分,如 Specification 中所述.它不是类(class)主体的一部分。

import 语句中使用的类型的范围,但是,

[..] is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears, as well as any annotations on the package declaration (if any) of the compilation unit .

关于java - 在封闭类的父类(super class)型声明中使用嵌套类型作为泛型类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510606/

相关文章:

java - 如何将数据从 Cassandra 导出到 mongodb?

Java - 对象列表返回重复值

java - 我怎样才能在java中将通用函数参数设置为protobuf?

Java:重载 java.lang.Number 的(通用)方法

java - 为什么我不能在 Java 的内部类中创建枚举?

java - Groovy Grape 没有下载新的修订版本

generics - 无约束实现泛型接口(interface)时的泛型类型约束

java - 是否鼓励(或不)在 Android 开发中使用内部类?

java - Java 中的公共(public)内部类与私有(private)内部类

java - 什么是事件派发线程?