为什么所有匿名类都隐式为final?

编程入门 行业动态 更新时间:2024-10-24 06:38:46
本文介绍了为什么所有匿名类都隐式为final?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

根据JLS:

15.9.5匿名类声明匿名类声明是由类实例创建表达式自动派生的. 编译器.

15.9.5 Anonymous Class Declarations An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.

匿名类从不抽象(第8.1.1.1节).匿名课程是 始终是内部类(第8.1.3节);它永远不是静态的(第8.1.1节,第8.5.2节). 匿名类始终是隐式最终的(§8.1.1.2).

An anonymous class is never 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).

这似乎是一个特定的设计决定,所以很可能有一定的历史.

This seems like it was a specific design decision, so chances are it has some history.

如果我选择上这样的课:

If I choose to have 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 so choose?

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 I necessarily want to, or can even think of a reason why I would. But I am curious why this is the case.

推荐答案

好吧,能够继承一个匿名类将是毫无用处的.唯一可以引用匿名类的地方是在定义它的语句中(如您的假设伪代码示例所示).这意味着可以保证该程序永远不会创建匿名超类的任何实例,并且智能编译器应该能够将这两个定义折叠为一个类.

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.

实际上,当类为最终类时,编译器和VM可以自由地在调用站点内联其方法.因此,在自然不可能扩展给定类的任何情况下,使此类类本质上最终成为有意义.

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.

更多推荐

为什么所有匿名类都隐式为final?

本文发布于:2023-11-09 20:28:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573354.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:隐式   final

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!