Anonymous class question

I doubt this line a little:

Anonymous class cannot define constructor

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

new class-name ( [ argument-list ] ) { class-body } 
+4
source share
3 answers

You do not define a constructor in an anonymous class; you call a constructor from a superclass.

You cannot add the correct constructor for the anonymous class, however you can do something like this. Namely, the 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() { } } 
+9
source

This example creates an anonymous subclass of class-name , and you are not allowed to create a constructor specific to your anonymous class. The argument list you specify matches the argument list for the class-name constructor.

+3
source

This means that there is an abstract class called class-name with a specific constructor. You use this constructor in your anonymous class, similar to using super () in a subclass constructor.

+1
source

All Articles