Anonymous class question

人盡茶涼 提交于 2019-12-07 09:22:49

问题


I've a little doubt over this line:

An anonymous class cannot define a constructor

then, why we can also define an Anonymous class with the following syntax:

new class-name ( [ argument-list ] ) { class-body }

回答1:


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

   }

}



回答2:


Your example creates an anonymous subclass of class-name, and you are not permitted to create a constructor specific to your anonymous class. The argument list you give is the same as the argument list for the class-name constructor.




回答3:


This implies that an abstract class exist called class-name with the defined constructor. You are making use of that constructor in your anonymous class similar to using super() in the constructor of a sub class.



来源:https://stackoverflow.com/questions/1758189/anonymous-class-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!