Accessing constructor of an anonymous class Accessing constructor of an anonymous class java java

Accessing constructor of an anonymous class


From the Java Language Specification, section 15.9.5.1:

An anonymous class cannot have an explicitly declared constructor.

Sorry :(

EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:

public class Test {    public static void main(String[] args) throws Exception {        final int fakeConstructorArg = 10;        Object a = new Object() {            {                System.out.println("arg = " + fakeConstructorArg);            }        };    }}

It's grotty, but it might just help you. Alternatively, use a proper nested class :)


That is not possible, but you can add an anonymous initializer like this:

final int anInt = ...;Object a = new Class1(){  {    System.out.println(anInt);  }  void someNewMethod() {  }};

Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.


Here's another way around the problem:

public class Test{    public static final void main(String...args){        new Thread(){            private String message = null;            Thread initialise(String message){                this.message = message;                return this;            }            public void run(){                System.out.println(message);            }        }.initialise(args[0]).start();    }}