Why are all anonymous classes implicitly final?

后端 未结 1 467
自闭症患者
自闭症患者 2021-01-18 13:02

According to the JLS:

15.9.5 Anonymous Class Declarations An anonymous class declaration is automatically derived from a class instance creation expre

相关标签:
1条回答
  • 2021-01-18 14:06

    Well, it would be pretty useless to be able to subclass an anonymous class. The only spot where you would be able to refer to the anonymous class would be in the statement where it's defined (as your hypothetical pseudocode example shows). This means that the program would be guaranteed never to create any instances of the anonymous superclass—and that a smart compiler should be able to collapse the two definitions into one class.

    More practically, when a class is final, compilers and VMs are free to inline its methods at the calling sites. So in any situation where it is naturally impossible to extend a given class, it makes sense to make such classes intrinsically final.

    0 讨论(0)
提交回复
热议问题