开发者

Are there any legitimate reasons to hide static methods? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why doesn开发者_如何学运维't Java allow overriding of static methods?

Is there any legitimate reason why one would want a derived class to override hide a static method of the base class?


Terminology aside, static methods in Java do have a kind of overriding relation, implied by binary compatibility section 13.4.12. If T extends S, S declared m(), T.m() can refer to a method in T or S, depending on if m() is declared in T; and it's ok to add or remove m() from T, without breaking any code calling T.m(). (This implies JVM invokestatic instruction does a sort of dynamic method lookup up the super class chain)

However, this is nothing but trouble. It is really dangerous if the meaning of T.m() silently changes because now it's pointing to a different method. (Instance methods shall inherit contracts so that's not a problem; there's no such understanding in static methods.)

So this "feature" should never be used; the language shouldn't have enabled it to begin with.

The good practice: If we call T.m(), m() must be declared in T; and it should never be removed from T without removing all T.m() first.


Static methods cannot be overriden

In order to override a method, the method must first be inherited. If the method is not inherited there is no chance for overriding. Therefore, you can never override a private method as they are not inherited.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜