为什么 Java 不允许覆盖静态方法? [英] Why doesn't Java allow overriding of static methods?

查看:38
本文介绍了为什么 Java 不允许覆盖静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能覆盖静态方法?

Why is it not possible to override static methods?

如果可能,请举例说明.

If possible, please use an example.

推荐答案

覆盖依赖于一个类的实例.多态性的要点是您可以对一个类进行子类化,并且实现这些子类的对象对于在超类中定义的相同方法(并在子类中被覆盖)将具有不同的行为.静态方法不与类的任何实例相关联,因此该概念不适用.

Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.

有两个因素影响了 Java 的设计.一个是对性能的关注:有很多批评 Smalltalk 说它太慢(垃圾收集和多态调用是其中的一部分),而 Java 的创建者决心避免这种情况.另一个决定是 Java 的目标受众是 C++ 开发人员.使静态方法按照它们的方式工作对 C++ 程序员来说很熟悉,而且速度也非常快,因为无需等到运行时才确定要调用哪个方法.

There were two considerations driving Java's design that impacted this. One was a concern with performance: there had been a lot of criticism of Smalltalk about it being too slow (garbage collection and polymorphic calls being part of that) and Java's creators were determined to avoid that. Another was the decision that the target audience for Java was C++ developers. Making static methods work the way they do had the benefit of familiarity for C++ programmers and was also very fast, because there's no need to wait until runtime to figure out which method to call.

这篇关于为什么 Java 不允许覆盖静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆