为什么不可能重写静态方法?

如果可能,请举例说明。


当前回答

通过重写,可以实现动态多态。 当您说覆盖静态方法时,您试图使用的词语是矛盾的。

静态表示-编译时,重写用于动态多态性。 两者在性质上是相反的,因此不能同时使用。

动态多态行为发生在程序员使用对象并访问实例方法时。JRE将根据您使用的对象类型映射不同类的不同实例方法。

当你说覆盖静态方法时,我们将使用类名访问静态方法,它将在编译时被链接,因此没有在运行时将方法与静态方法链接的概念。因此,术语“重写”静态方法本身没有任何意义。

注意:即使你用一个对象访问一个类方法,java编译器仍然有足够的智能来发现它,并会做静态链接。

其他回答

简短的回答是:这是完全可能的,但Java没有做到。

下面是一些代码,说明了Java中的当前状态:

文件Base.java:

package sp.trial;
public class Base {
  static void printValue() {
    System.out.println("  Called static Base method.");
  }
  void nonStatPrintValue() {
    System.out.println("  Called non-static Base method.");
  }
  void nonLocalIndirectStatMethod() {
    System.out.println("  Non-static calls overridden(?) static:");
    System.out.print("  ");
    this.printValue();
  }
}

文件Child.java:

package sp.trial;
public class Child extends Base {
  static void printValue() {
    System.out.println("  Called static Child method.");
  }
  void nonStatPrintValue() {
    System.out.println("  Called non-static Child method.");
  }
  void localIndirectStatMethod() {
    System.out.println("  Non-static calls own static:");
    System.out.print("  ");
    printValue();
  }
  public static void main(String[] args) {
    System.out.println("Object: static type Base; runtime type Child:");
    Base base = new Child();
    base.printValue();
    base.nonStatPrintValue();
    System.out.println("Object: static type Child; runtime type Child:");
    Child child = new Child();
    child.printValue();
    child.nonStatPrintValue();
    System.out.println("Class: Child static call:");
    Child.printValue();
    System.out.println("Class: Base static call:");
    Base.printValue();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Child:");
    child.localIndirectStatMethod();
    System.out.println("Object: static/runtime type Child -- call static from non-static method of Base:");
    child.nonLocalIndirectStatMethod();
  }
}

如果你运行这个(我在Mac上做的,从Eclipse,使用Java 1.6),你会得到:

Object: static type Base; runtime type Child.
  Called static Base method.
  Called non-static Child method.
Object: static type Child; runtime type Child.
  Called static Child method.
  Called non-static Child method.
Class: Child static call.
  Called static Child method.
Class: Base static call.
  Called static Base method.
Object: static/runtime type Child -- call static from non-static method of Child.
  Non-static calls own static.
    Called static Child method.
Object: static/runtime type Child -- call static from non-static method of Base.
  Non-static calls overridden(?) static.
    Called static Base method.

在这里,唯一可能令人惊讶的情况(也是这个问题所涉及的)似乎是第一种情况:

运行时类型并不用于确定调用哪些静态方法,即使是在使用对象实例(obj.staticMethod())调用时也是如此。

最后一种情况:

当从类的对象方法中调用静态方法时,选择的静态方法是类本身可访问的方法,而不是定义对象运行时类型的类可访问的方法。

使用对象实例调用

静态调用在编译时解析,而非静态方法调用在运行时解析。注意,尽管静态方法是继承的(从父方法),但它们不会被(子方法)覆盖。如果你另有期待,这可能会是一个惊喜。

从对象方法中调用

对象方法调用使用运行时类型解析,但静态(类)方法调用使用编译时(已声明)类型解析。

改变规则

要更改这些规则,以便示例中的最后一个调用Child.printValue(),静态调用必须在运行时提供类型,而不是编译器在编译时使用对象(或上下文)声明的类解析调用。然后,静态调用可以使用(动态)类型层次结构来解析调用,就像现在的对象方法调用一样。

这是很容易做到的(如果我们改变Java:-O),并不是完全不合理的,然而,它有一些有趣的考虑。

主要需要考虑的是,我们需要决定哪个静态方法调用应该执行此操作。

目前,Java语言中有这种“怪癖”,即obj.staticMethod()调用被ObjectClass.staticMethod()调用取代(通常带有警告)。[注意:ObjectClass是obj的编译时类型。]这些将是很好的候选人,以这种方式重写,采用obj的运行时类型。

如果我们这样做了,就会使方法体更难阅读:父类中的静态调用可能会被动态地“重新路由”。为了避免这种情况,我们必须使用类名调用静态方法——这使得调用更明显地用编译时类型层次结构来解析(就像现在一样)。

调用静态方法的其他方法更加棘手:this. staticmethod()的意思应该与obj.staticMethod()相同,接受this的运行时类型。然而,这可能会给现有程序带来一些麻烦,这些程序调用(显然是本地的)没有修饰的静态方法(可以说相当于this.method())。

那么无修饰调用staticMethod()会怎样呢?我建议他们像今天一样,使用本地类上下文来决定要做什么。否则就会产生巨大的混乱。当然,如果method是非静态方法,则method()意味着this.method(),如果method是静态方法,则意味着ThisClass.method()。这是另一个困惑的来源。

其他的考虑

如果我们改变了这种行为(并使静态调用具有潜在的动态非本地性),我们可能会希望重新审视final、private和protected作为类静态方法的限定符的意义。然后,我们都必须习惯这样一个事实:私有静态方法和公共final方法不会被覆盖,因此可以在编译时安全地解析,并且可以“安全”地作为本地引用读取。

重写依赖于类的实例。多态性的意义在于,您可以子类化一个类,而实现这些子类的对象对于父类中定义的相同方法将具有不同的行为(并且在子类中被重写)。静态方法不与类的任何实例相关联,因此这个概念不适用。

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.

Here is a simple explanation. A static method is associated with a class while an instance method is associated with a particular object. Overrides allow calling the different implementation of the overridden methods associated with the particular object. So it is counter-intuitive to override static method which is not even associated with objects but the class itself in the first place. So static methods cannot be overridden based on what object is calling it, it will always be associated with the class where it was created.

Well... the answer is NO if you think from the perspective of how an overriden method should behave in Java. But, you don't get any compiler error if you try to override a static method. That means, if you try to override, Java doesn't stop you doing that; but you certainly don't get the same effect as you get for non-static methods. Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods). Okay... any guesses for the reason why do they behave strangely? Because they are class methods and hence access to them is always resolved during compile time only using the compile time type information. Accessing them using object references is just an extra liberty given by the designers of Java and we should certainly not think of stopping that practice only when they restrict it :-)

示例:让我们试着看看如果我们尝试重写一个静态方法会发生什么:-

class SuperClass {
// ......
public static void staticMethod() {
    System.out.println("SuperClass: inside staticMethod");
}
// ......
}

public class SubClass extends SuperClass {
// ......
// overriding the static method
public static void staticMethod() {
    System.out.println("SubClass: inside staticMethod");
}

// ......
public static void main(String[] args) {
    // ......
    SuperClass superClassWithSuperCons = new SuperClass();
    SuperClass superClassWithSubCons = new SubClass();
    SubClass subClassWithSubCons = new SubClass();

    superClassWithSuperCons.staticMethod();
    superClassWithSubCons.staticMethod();
    subClassWithSubCons.staticMethod();
    // ...
}
}

输出: SuperClass:在staticMethod内部 SuperClass:在staticMethod内部 子类:staticMethod内部

注意输出的第二行。如果staticMethod被重写,这一行应该与第三行相同,因为我们在运行时类型的对象上调用'staticMethod()'作为'子类'而不是'超类'。这证实了静态方法总是只使用它们的编译时类型信息进行解析。

一般来说,允许“重写”静态方法是没有意义的,因为没有好的方法来确定在运行时调用哪个方法。以Employee为例,如果我们调用regularemploee . getbonusmultiplier()——应该执行哪个方法?

以Java为例,人们可以想象这样一种语言定义:只要静态方法是通过对象实例调用的,就可以“覆盖”它们。然而,这样做只是重新实现常规的类方法,在没有真正带来任何好处的情况下为语言增加冗余。