[英]Using a nested type as a generic type argument in the enclosing class' supertype declaration
I basically have a question about why the following does not work. 我基本上有一个问题,为什么以下不起作用。 I have an abstract class:
我有一个抽象类:
public abstract class Abstrct <T> {
}
I then define a class that makes use of that class with a public inner class defined that I want to use for the generic parameter, as follows: 然后我定义了一个类,该类使用了一个定义了公共内部类的类,我想将它用于泛型参数,如下所示:
public class Outer extends Abstrct<Inner> {
public class Inner {
}
}
As I am learning Java still, I am more interested in why it does not work. 当我正在学习Java时,我更感兴趣的是它为什么不起作用。 Not so much as to how to make it work, but I would be interested in that also.
与其如何使其工作无关,但我也会对此感兴趣。
Inner
is not in scope for the class declaration of Outer
. Inner
不在Outer
的类声明范围内。 It's not a known type name when used in the extends
clause. 在
extends
子句中使用时,它不是已知的类型名称。 Use a qualified reference: 使用合格的参考:
class Outer extends Abstract<Outer.Inner>
Or import it: 或者导入它:
import com.example.Outer.Inner;
From the specification, regarding 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.的成员的声明的范围
m
中声明或由类继承的类型C
(§8.1.6) 是整个身体C
,包括任何嵌套类型声明。
The extends
clause is part of the class' Superclass
declaration, as described in the Specification . extends
子句是类的Superclass
声明的一部分,如规范中所述。 It's not part of the class body. 它不是班级机构的一部分。
The scope of a type used in an import
statement, however, 但是,
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 .
[..] 是出现导入声明的编译单元中的所有类和接口类型声明(第7.6节),以及编译单元的包声明(如果有)的任何注释。
您可以使用Abstrct<Outer.Inner>
使类型明确且有效。
You have to be explicit since the inner class you defined is not static so it only exists within the scope of the containing class. 您必须明确,因为您定义的内部类不是静态的,因此它只存在于包含类的范围内。 (See https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html )
(参见https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html )
In your case try following: 在你的情况下尝试以下:
public class Outer extends Abstrct<Outer.Inner> {
public class Inner {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.