关于ActivityThread中使用的final关键字的一个困惑
正如ActivityThread类的源代码所示,它是一个final
类,并且该类中的所有方法也是final
方法。由于java中的final
关键字定义,该类不能被继承,但是为什么android开发者保留这些方法final
呢?
可能是我问题没有表达清楚,我在这里修正一下。
ActivityThread 是一个 final
类,它不会有任何子类,也不会重写任何方法,但是你知道这个类中的所有方法都是 final
,我如果想知道为什么他们需要这些 final
关键字,他们可以删除它们而不会产生任何影响。
As the source of the ActivityThread class shows, it's a final
class, and all the methods in this class is also final
methods. As the final
keyword definition in java, this class cannot be inherited, but why android developers keep those methods final
?
Maybe I didn't express the question clear, I fix it here.
ActivityThread is a final
class, it will not have any sub-class, and no method will be overridden, but you know that all the methods in this class is final
, I want to know why they need these final
keywords, they can remove them with no impact.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java 语言规范 清楚地表明
final
类的任何方法都不能被重写。因此,方法上的final
声明似乎是多余的。 (也许是 Android API 测试版留下的,当时 ActivityThread 可能不是最终类?)另一方面,优化器和混淆器有时可以使用声明为
final
的方法做更多事情。尽管他们应该足够聪明,可以推断出最终类不会有任何重写的方法,但给他们额外的提示也没什么坏处。The Java Language Specification makes it clear that no method of a
final
class can be overridden. Thus, thefinal
declaration on the methods appear to be redundant. (Maybe left over from a beta version of the Android API when ActivityThread was perhaps not a final class?)On the other hand, optimizers and obfuscators can sometimes do a little more with methods declared
final
. Although they ought to be smart enough to make the inference that a final class won't have any overridden methods, it can't hurt to give them the extra hint.事实上,Java 工程师就是这样做的。这是一个设计决策:有时您希望禁止对某个类进行子类化。为什么?部分原因是它意味着一些强烈的责任,迫使你做出非常明智的决定。
让我参考 Effective Java 第二版 的第 17 项的部分内容约书亚·布洛赫:
Actually, the Java engineers did that. It's a design decision: sometimes you want to prohibit sub-classing one of your classes. Why? Some of the reason is that it implies some strong responsibility, that forces you to take very smart decisions.
Let me reference part of the item number 17 of Effective Java Second Edition by Joshua Bloch: