匿名类问题 [英] Anonymous class question
本文介绍了匿名类问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对此行有点怀疑:
匿名类无法定义构造函数
An anonymous class cannot define a constructor
那么,为什么我们也可以使用以下语法定义一个Anonymous类:
then, why we can also define an Anonymous class with the following syntax:
new class-name ( [ argument-list ] ) { class-body }
推荐答案
您不是在匿名类中定义构造函数,而是从超类调用构造函数。
You are not defining a constructor in anonymous class, you are calling a constructor from superclass.
您无法为匿名类添加正确的构造函数,但是,您可以执行类似的操作。即初始化块。
You can't add a proper constructor for anonymous class, however, you can do something similar. Namely an initialization block.
public class SuperClass {
public SuperClass(String parameter) {
// this is called when anonymous class is created
}
}
// an anonymous class is created and instantiated here
new SuperClass(parameterForSuperClassConstructor) {
{
// this code is executed when object is initialized
// and can be used to do many same things as a constructors
}
private void someMethod() {
}
}
这篇关于匿名类问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文