Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are anonymous classes compiled in Java?

I've heard that Java bytecode actually doesn't support any kind of unnamed classes. How does javac translate unnamned classes to named ones?

like image 419
keiter Avatar asked Apr 27 '11 18:04

keiter


People also ask

Can Anonymous classes be implemented an interface?

No, anonymous types cannot implement an interface. We need to create your own type. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

Can anonymous class have multiple methods?

You can't. The only way to be able to call multiple methods is to assign the anonymous class instance to some variable.

Does Anonymous class have constructor?

Since anonymous inner class has no name, an anonymous inner class cannot have an explicit constructor in Java.


Video Answer


1 Answers

It synthesizes a name of the form EnclosingClass$n, where "n" is a counter for anonymous classes in EnclosingClass. Because using $ in identifiers is discouraged, these names should not collide with any user-specified names.

like image 198
erickson Avatar answered Oct 11 '22 13:10

erickson