在Java中,this/super关键字可以代表类/枚举以外的任何东西吗?
我注意到:
class A {
ClassB b = new ClassB() { // anonymous class
/* some expression using this */
}
}
每当我在匿名类中使用 this
关键字时,this
都会引用封闭的外部类/枚举,而不是匿名类。
这是否意味着 this
永远不能代表匿名类?只是“普通”类和枚举?
另外,this
或 super
可以代表一个接口吗?
I've noticed that:
class A {
ClassB b = new ClassB() { // anonymous class
/* some expression using this */
}
}
Whenever I use the this
keyword inside an anonymous class, the this
refers to the enclosing outer class/enum and not to the anonymous class.
Does this mean this
can never represent an anonymous class? Just "normal" classes and enums?
Also, can this
or super
represent an interface?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您最初的假设是错误的 -
this
始终代表当前实例,即当前类的实例,即使它是匿名的。Your initial assumption is wrong -
this
always represents the current instance, that is the instance of the current class, even if it's anonymous.您关于使用
this
的声明不正确。当您在匿名类中使用this
时,它始终引用匿名类。它永远不会引用封闭的外部类,除非您使用OuterClassName.this
。this
或super
永远不能表示接口,因为接口不能具有已定义的方法。Your statement about using
this
is incorrect. When you usethis
inside an anonymous class, it always refers to the anonymous class. It never refers to the enclosing outer class unless you useOuterClassName.this
.this
orsuper
can never represent an interface, since an interface cannot have defined methods.在 Java 中,
this
始终是当前类,即使它是匿名类。不,this
或super
不能表示接口。In Java
this
is always the current class even if it is an anonymous class. No,this
orsuper
cannot represent an interface.你的匿名类总是扩展另一个类。即使您显式实现接口,您也是在扩展
java.lang.Object
,并且只能通过super
调用java.lang.Object
的方法> 来电。Your anonymous class always extends another class. Even if you explicitly implement an interface, you are extending
java.lang.Object
and you can only call methods ofjava.lang.Object
viasuper
calls.使用内部类中的
A.this
。它不能表示接口,因为您不能在接口内定义任何非静态类,因为永远不会有接口的实例。
编辑:通过添加评论中的信息进行澄清。
Use
A.this
from the inner class.And it cannot represent an interface, because you cannot define anynomous non-static classes within interfaces, because there wil never be an instance of the interface.
EDIT: Clarified by adding info from the comment.