匿名课程问题
我对这一行有点怀疑:
匿名类无法定义构造函数
那么,为什么我们还可以使用以下语法定义Anonymous类:
new class-name ( [ argument-list ] ) { class-body }
您没有在匿名类中定义构造函数,而是从超类调用构造函数。
您无法为匿名类添加适当的构造函数,但是,您可以执行类似的操作。 即初始化块。
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() { } }
您的示例创建了一个class-name
的匿名子 class-name
,并且不允许您创建特定于您的匿名类的构造函数。 您提供的参数列表与class-name
构造函数的参数列表相同。
这意味着使用定义的构造函数存在一个名为class-name
的抽象类。 您正在匿名类中使用该构造函数,类似于在子类的构造函数中使用super()。