java为什么不能重写静态方法
Question:
Why is it not possible to override static methods?
If possible, please use an example.
Answer:
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.
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.
译:
Q:为什么不可以重写静态方法?
A:重写依赖于拥有一个class实例对象。多态性的关键就是你可以继承一个类或对象,然后可以子类可以重写父类中的方法,实现不同的行为。一个静态方法是和类实例无关的,所以这个重写就不适用。
有两个考虑影响到了Java的设计者,让他这么做。一个是性能方面的问题:曾经有很多关于smalltalk的批评,说它太慢(主要是因为垃圾回收和多态调用这些方面)。所以Java创造者决定避免这么做。另一个原因是,java的主要开始使用者是面对C++的,因为不需要等到运行时才知道调用的是哪个方法,所以让静态方法像以前工作可以让他们自己的习惯并且保持很快的运行速度。