匿名类问题

Jav*_*bts 4 java constructor anonymous-class

我对这一行有点怀疑:

匿名类无法定义构造函数

那么,为什么我们还可以使用以下语法定义Anonymous类:

new class-name ( [ argument-list ] ) { class-body }
Run Code Online (Sandbox Code Playgroud)

Juh*_*älä 9

您没有在匿名类中定义构造函数,而是从超类调用构造函数.

您不能为匿名类添加适当的构造函数,但是,您可以执行类似的操作.即初始化块.

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() {

   }

}
Run Code Online (Sandbox Code Playgroud)