views:

139

answers:

3

Hi,

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 }
+8  A: 

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

   }

}
Juha Syrjälä
+3  A: 

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.

Greg Hewgill
+1  A: 

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.

Vincent Ramdhanie