Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

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?

1 Answer

0 votes
by (46k points)

From the Java Language Specification, section 15.9.5.1:

An anonymous class cannot have an explicitly declared constructor.

Sorry :(

As an option, you can build some final local variables, and/or add 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 assist you. Alternatively, use a peculiar nested class :)

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Apr 3, 2021 in Java by dante07 (13.1k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...