外层与超层
super的优先级比outerclass的优先级高吗?
考虑我们有三个类:
- ClassA
- ClassB
- ClassB 中扩展 ClassA 的匿名类
ClassA.java:
public class ClassA {
protected String var = "A Var";
public void foo() {
System.out.println("A foo()");
}
}
ClassB.java:
public class ClassB {
private String var = "B Var";
public void test() {
new ClassA() {
public void test() {
foo();
System.out.println(var);
}
}.test();
}
public void foo() {
System.out.println("B foo()");
}
}
当我调用 new ClassB().test()
时,我得到以下输出(即几乎是预期的):
A foo()
A Var
问题:是否在某个地方定义了内部类首先从超类然后从外部类获取(方法和成员),或者它是否依赖于 JVM 编译器实现?我已经查看了 JLS(§15.12.3),但找不到任何参考资料,也许那里指出了,但我误解了一些术语?
Does super has higher priority than outer class?
Consider we have three classes:
- ClassA
- ClassB
- Anonymous class in ClassB that extends ClassA
ClassA.java:
public class ClassA {
protected String var = "A Var";
public void foo() {
System.out.println("A foo()");
}
}
ClassB.java:
public class ClassB {
private String var = "B Var";
public void test() {
new ClassA() {
public void test() {
foo();
System.out.println(var);
}
}.test();
}
public void foo() {
System.out.println("B foo()");
}
}
When I call new ClassB().test()
, I get the following output (which is pretty much expected):
A foo()
A Var
Question: Is it defined somewhere that inner class takes (methods and members) first from the super class and then from the outer class or is it JVM compiler implementation dependent? I have looked over the JLS(§15.12.3) but couldn't find any reference for that, maybe it is pointed out there but I misunderstood some of the terms?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅6.3.1 隐藏声明:
其中可能被解释为“
foo
的声明(继承自ClassA
)隐藏了任何其他名为foo
的方法的声明” code> 位于foo
发生处的封闭范围 (ClassB
) 中,贯穿整个foo
范围。”同样相关 - 15.12.1 部分:
See 6.3.1 Shadowing Declarations:
Which may be interpreted as "the declaration of
foo
(inherited fromClassA
) shadows the declaration of any other methods namedfoo
that are in an enclosing scope (ClassB
) at the point wherefoo
occurs, throughout the scope offoo
."Also relevant - section 15.12.1:
我认为你总是会得到
“A var”
。这是因为您的
test()
方法实现是在A
的匿名子类上定义的。我认为您无法在test()
方法中访问B.var
实例变量,除非您使用ClassB.this 显式引用外部类。变量
。I think you are always going to get
"A var"
.This is because your
test()
method implementation is being defined on an anonymous subclass ofA
. I don't think you can access theB.var
instance variable within yourtest()
method unless you explicitly refer to the outer class usingClassB.this.var
.