是否有隐藏静态方法的正当理由?
可能的重复:
为什么 Java 不允许重写静态方法? < /p>
是为什么人们希望派生类重写隐藏基类的静态
方法,有什么合理的理由吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
抛开术语不谈,Java 中的静态方法确实具有一种压倒一切的关系,如二进制兼容性第 13.4.12 节所暗示的那样。如果 T 扩展 S,S 声明了 m(),则 Tm() 可以引用 T 或 S 中的方法,具体取决于 T 中是否声明了 m();并且可以在 T 中添加或删除 m(),而不会破坏任何调用 Tm() 的代码。 (这意味着 JVM invokestatic 指令会在超类链中进行某种动态方法查找)
但是,这只是麻烦。如果 Tm() 的含义默默地改变,那真的很危险,因为现在它指向一个不同的方法。 (实例方法应继承契约,因此这不是问题;静态方法中没有这样的理解。)
因此永远不应该使用这个“功能”;该语言一开始就不应该启用它。
好的做法:如果我们调用 Tm(),m() 必须在 T 中声明;如果不首先删除所有 Tm(),则永远不应该将其从 T 中删除。
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.