我基本上有一个问题,为什么以下不起作用。我有一个抽象类:
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 typeC
(§8.1.6) is the entire body ofC
, 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/