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