Can we define explicit constructor for an anonymous inner class?

The precise answer to this question is "NO". We can not have an explicit constructor for an anonymous inner class.

Generally to create a constructor for a class, the first and the main requirement is "Constructor name must be exactly the same as its class name". But in the anonymous inner class concept, we don't have a class name (at least not till the class file for anonymous inner class gets created.) and that's why we can not define its constructor explicitly as we don't know its class name. So, the bottom line is, explicit constructor concept is not applicable for an anonymous inner class.

But the drama doesn't end here. As no class exists in the world of java without a constructor (at least one). The same applies to the anonymous inner class as well.

But then immediately question comes to the mind "If we can not write an explicit constructor for an anonymous class then how do we have a constructor in it?"

Our superhero "Mr. Compiler" comes for the rescue here. It creates a constructor for an anonymous inner class at compile time and prevents the anonymous inner class from breaking this basic java rule. 

The below example depicts how the compiler adds constructor in an anonymous inner class.

      

      


After compiling the above code, three class files will get generated.

      


Now let's decompile and check the anonymous inner class definition.

       


We can see, even though we did not add any explicit constructor, the compiler added it at compile time.

Conclusion

Here the bottom line is, we can not write an explicit constructor in an anonymous inner class. Its the compiler's job to add it at compile time.

See you in my next post. Till then keep reading!!

Comments

Post a Comment

Popular posts from this blog

Why we can not throw exception from Thread’s run method?

Most ignored concept in java but very important from interview point of view : SerialVersionUID