为什么不可能重写静态方法?
如果可能,请举例说明。
为什么不可能重写静态方法?
如果可能,请举例说明。
当前回答
一般来说,允许“重写”静态方法是没有意义的,因为没有好的方法来确定在运行时调用哪个方法。以Employee为例,如果我们调用regularemploee . getbonusmultiplier()——应该执行哪个方法?
以Java为例,人们可以想象这样一种语言定义:只要静态方法是通过对象实例调用的,就可以“覆盖”它们。然而,这样做只是重新实现常规的类方法,在没有真正带来任何好处的情况下为语言增加冗余。
其他回答
这个问题的答案很简单,标记为静态的方法或变量只属于类,因此静态方法不能在子类中继承,因为它们只属于超类。
I like and double Jay's comment (https://stackoverflow.com/a/2223803/1517187). I agree that this is the bad design of Java. Many other languages support overriding static methods, as we see in previous comments. I feel Jay has also come to Java from Delphi like me. Delphi (Object Pascal) was one of the languages implementing OOP before Java and one of the first languages used for commercial application development. It is obvious that many people had experience with that language since it was in the past the only language to write commercial GUI products. And - yes, we could in Delphi override static methods. Actually, static methods in Delphi are called "class methods", while Delphi had the different concept of "Delphi static methods" which were methods with early binding. To override methods you had to use late binding, declare "virtual" directive. So it was very convenient and intuitive and I would expect this in Java.
重写依赖于类的实例。多态性的意义在于,您可以子类化一个类,而实现这些子类的对象对于父类中定义的相同方法将具有不同的行为(并且在子类中被重写)。静态方法不与类的任何实例相关联,因此这个概念不适用。
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.
静态方法被JVM视为全局方法,根本不绑定到对象实例。
如果可以从类对象中调用静态方法(就像在Smalltalk等语言中那样),那么在概念上是可能的,但在Java中却不是这样。
EDIT
你可以重载静态方法,没关系。但是你不能重写静态方法,因为类不是一级对象。您可以使用反射在运行时获取对象的类,但所获得的对象并不与类层次结构并行。
class MyClass { ... }
class MySubClass extends MyClass { ... }
MyClass obj1 = new MyClass();
MySubClass obj2 = new MySubClass();
ob2 instanceof MyClass --> true
Class clazz1 = obj1.getClass();
Class clazz2 = obj2.getClass();
clazz2 instanceof clazz1 --> false
你可以对类进行反射,但它仅限于此。使用clazz1.staticMethod()不会调用静态方法,而是使用MyClass.staticMethod()。静态方法不绑定到对象,因此在静态方法中没有this或super的概念。静态方法是一个全局函数;因此,也没有多态性的概念,因此,方法重写没有意义。
但是,如果MyClass在运行时是一个调用方法的对象,这是可能的,就像在Smalltalk(或者可能是一个评论建议的JRuby,但我对JRuby一无所知)。
哦是的…还有一件事。您可以通过对象obj1.staticMethod()调用静态方法,但这实际上是MyClass.staticMethod()的语法糖,应该避免。在现代IDE中,它通常会引发一个警告。我不知道他们为什么允许走这条捷径。
其实我们错了。 尽管Java默认情况下不允许重写静态方法,但如果你彻底查看Java中Class和Method类的文档,你仍然可以通过以下工作方法来模拟静态方法重写:
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
class RegularEmployee {
private BigDecimal salary = BigDecimal.ONE;
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".02");
}
public BigDecimal calculateBonus() {
return salary.multiply(this.getBonusMultiplier());
}
public BigDecimal calculateOverridenBonus() {
try {
// System.out.println(this.getClass().getDeclaredMethod(
// "getBonusMultiplier").toString());
try {
return salary.multiply((BigDecimal) this.getClass()
.getDeclaredMethod("getBonusMultiplier").invoke(this));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return null;
}
// ... presumably lots of other code ...
}
final class SpecialEmployee extends RegularEmployee {
public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".03");
}
}
public class StaticTestCoolMain {
static public void main(String[] args) {
RegularEmployee Alan = new RegularEmployee();
System.out.println(Alan.calculateBonus());
System.out.println(Alan.calculateOverridenBonus());
SpecialEmployee Bob = new SpecialEmployee();
System.out.println(Bob.calculateBonus());
System.out.println(Bob.calculateOverridenBonus());
}
}
输出结果:
0.02
0.02
0.02
0.03
我们想要达到的目标:)
即使我们将第三个变量Carl声明为regulareemployee并给它分配了SpecialEmployee实例,我们仍然会在第一种情况下调用regulareemployee方法,在第二种情况下调用SpecialEmployee方法
RegularEmployee Carl = new SpecialEmployee();
System.out.println(Carl.calculateBonus());
System.out.println(Carl.calculateOverridenBonus());
看看输出控制台:
0.02
0.03
;)