开发者

A confuse about final keyword used in ActivityThread

开发者 https://www.devze.com 2023-02-07 08:45 出处:网络
As the source of the ActivityThread class shows, it\'s a final class, and all the methods in this class is also finalmethods. As the finalkeyword definition in java, this class cannot be inherited, bu

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 overri开发者_如何转开发dden, 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.


The Java Language Specification makes it clear that no method of a final class can be overridden. Thus, the final 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.


why android developers keep those methods final?

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:

So what does it mean for a class to be designed and documented for inheritance? First, the class must document precisely the effects of overriding any method. In other words, the class must document its self-use of overridable methods. For each public or protected method or constructor, the documentation must indicate which overridable methods the method or constructor invokes, in what sequence, and how the results of each invocation affect subsequent processing. (By overridable, we mean nonfinal and either public or protected.) More generally, a class must document any circumstances under which it might invoke an overridable method. For example, invocations might come from background threads or static initializers.

...

Design for inheritance involves more than just documenting patterns of self- use. To allow programmers to write efficient subclasses without undue pain, a class may have to provide hooks into its internal workings in the form of judi- ciously chosen protected methods or, in rare instances, protected fields.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号