Accessing constructor of an anonymous class

124,303

Solution 1

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 :)

Solution 2

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.

Solution 3

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();
    }
}

Solution 4

I know the thread is too old to post an answer. But still i think it is worth it.

Though you can't have an explicit constructor, if your intention is to call a, possibly protected, constructor of the super class, then the following is all you have to do.

StoredProcedure sp = new StoredProcedure(datasource, spName) {
    {// init code if there are any}
};

This is an example of creating a StoredProcedure object in Spring by passing a DataSource and a String object.

So the Bottom line is, if you want to create an anonymous class and want to call the super class constructor then create the anonymous class with a signature matching the super class constructor.

Solution 5

You can have a constructor in the abstract class that accepts the init parameters. The Java spec only specifies that the anonymous class, which is the offspring of the (optionally) abstract class or implementation of an interface, can not have a constructor by her own right.

The following is absolutely legal and possible:

static abstract class Q{
    int z;
    Q(int z){ this.z=z;}
    void h(){
        Q me = new Q(1) {
        };
    }
}

If you have the possibility to write the abstract class yourself, put such a constructor there and use fluent API where there is no better solution. You can this way override the constructor of your original class creating an named sibling class with a constructor with parameters and use that to instantiate your anonymous class.

Share:
124,303

Related videos on Youtube

Saravanan M
Author by

Saravanan M

Updated on September 13, 2021

Comments

  • Saravanan M
    Saravanan M over 2 years

    Lets say I have a concrete class Class1 and I am creating an anonymous class out of it.

    Object a = new Class1(){
            void someNewMethod(){
            }
          };
    

    Now is there any way I could overload the constructor of this anonymous class. Like shown below

    Object a = new Class1(){
            void someNewMethod(){
            }
            public XXXXXXXX(int a){
              super();
              System.out.println(a);
            }
          };
    

    With something at xxxxxxxx to name the constructor?

  • Johannes Schaub - litb
    Johannes Schaub - litb over 15 years
    Arne, i believe him he didnt copy it. he knows enough of java to be fair enough to give credit when he would have copied it i think.
  • Jon Skeet
    Jon Skeet over 15 years
    The language could easily turn the "normal" constructor arguments into arguments for the anonymous class, if desired. The syntax for the constructor declaration would probably look pretty weird though...
  • Johannes Schaub - litb
    Johannes Schaub - litb over 15 years
    couldn't it just say to declare the constructor like if it were the base class constructor? i don't see problems with that
  • user
    user over 11 years
    OMG, did someone blamed THE Jon Skeet for copying?
  • Mark Jeronimus
    Mark Jeronimus about 10 years
    How would I be able to call a method in the superclass of Test from within println, when that method is overridden?
  • Jon Skeet
    Jon Skeet about 10 years
    @Zom-B: It's not clear exactly what you mean - I suspect it's worth you asking a new question with an example of what you're trying to achieve.
  • n611x007
    n611x007 about 10 years
    ah, I wanted to override the superclass constructor... then I understood that no explicitly declared ctor means no overriding whatsoever, too. I suppose.
  • banarun
    banarun about 9 years
    Is there a reason why the variable had to be final?
  • Jon Skeet
    Jon Skeet about 9 years
    @banarun: Yes - because otherwise it couldn't be used in an anonymous inner class. Now as of Java 8, local variables can be "effectively final" so this would still work in Java 8 without being explicitly final... but you still couldn't change it afterwards.
  • Abhi
    Abhi almost 8 years
    @user..maybe arne blamed Jon first so that people dont think he copied it from Jon..i'm not saying he copied it, but he could've said it to protect himself
  • pdem
    pdem about 7 years
    I didn't know Peter Norvig, a Scientific of Google, it is probably one of his early work, it is about java 1.1! Interesting on an historic point of view :)
  • Pacerier
    Pacerier almost 4 years
    (raison detre of anonymous classes) How to have that code within a function?
  • Stefan Steinegger
    Stefan Steinegger over 3 years
    It's actually very much like a constructor. I can access protected members of an abstract base class. Everything else can be done in code before instantiating of the anonymous class.