Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous class question

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 }
like image 613
Javadoubts Avatar asked Dec 13 '22 01:12

Javadoubts


1 Answers

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

   }

}
like image 85
Juha Syrjälä Avatar answered Dec 25 '22 15:12

Juha Syrjälä