Why are all anonymous classes implicitly definitive?

According to JLS:

15.9.5 Anonymous class declarations An anonymous class declaration is automatically inferred from the class instance creation expression using the compiler.

An anonymous class is not abstract (ยง8.1.1.1). An anonymous class is always an inner class (ยง8.1.3); it is never static (ยง8.1.1, ยง8.5.2). An anonymous class is always implicitly final (ยง8.1.1.2) .

It seems that this was a specific design decision, so it is likely that he has some history.

If I choose a class like this:

SomeType foo = new SomeType() { @Override void foo() { super.foo(); System.out.println("Hello, world!"); } }; 

Why am I not allowed to subclass it again if I choose this?

 SomeType foo = new SomeType() { @Override void foo() { super.foo(); System.out.println("Hello, world!"); } } { @Override void foo() { System.out.println("Hahaha, no super foo for you!"); } }; 

I'm not saying that I definitely want, or I can even think about the reason why I would do it. But I'm curious why that is.

+6
source share
1 answer

Well, it would be useless to subclass an anonymous class. The only place you could access an anonymous class would be in the statement where it was defined (as an example of a hypothetical pseudocode shows). This means that the program will be guaranteed never to instantiate an anonymous superclass, and that the smart compiler should be able to collapse two definitions into one class.

More practical when the class is final, compilers and virtual machines can embed their methods in calling sites. Therefore, in any situation when, of course, it is impossible to extend a given class, it makes sense to make such classes internally final.

+6
source

Source: https://habr.com/ru/post/904208/


All Articles