问题是,在Java中为什么不能定义抽象静态方法?例如

abstract class foo {
    abstract void bar( ); // <-- this is ok
    abstract static void bar2(); //<-- this isn't why?
}

当前回答

An abstract method is defined only so that it can be overridden in a subclass. However, static methods can not be overridden. Therefore, it is a compile-time error to have an abstract, static method. Now the next question is why static methods can not be overridden?? It's because static methods belongs to a particular class and not to its instance. If you try to override a static method you will not get any compilation or runtime error but compiler would just hide the static method of superclass.

其他回答

在一行中,这种危险的组合(抽象+静态)违反了面向对象的原则,即多态性。

在继承情况下,JVM将在运行时根据实现决定实例的类型(运行时多态性),而不是根据引用变量的类型(编译时多态性)。

@Overriding:

静态方法不支持@ override(运行时多态性),而只支持方法隐藏(编译时多态性)。

@Hiding:

但是在抽象静态方法的情况下,父(抽象)类没有方法的实现。因此,子类型引用是唯一可用的,而且它不是多态性。

子引用是唯一可用的:

出于这个原因(抑制oop特性),Java语言认为抽象+静态是非法(危险)的方法组合。

糟糕的语言设计。直接调用静态抽象方法要比为使用该抽象方法而创建实例有效得多。当使用抽象类作为枚举无法扩展的变通方法时尤其如此,这是另一个糟糕的设计示例。希望他们能在下一个版本中解决这些限制。

根据Java文档:

静态方法是与其中的类相关联的方法 它是定义的,而不是与任何对象。类的每个实例 共享它的静态方法

在Java 8中,除了默认方法外,接口中还允许使用静态方法。这使得我们更容易在库中组织helper方法。我们可以在同一个接口中保留特定于某个接口的静态方法,而不是在一个单独的类中。

一个很好的例子是:

list.sort(ordering);

而不是

Collections.sort(list, ordering);

另一个使用静态方法的例子也在doc中给出:

public interface TimeClient {
    // ...
    static public ZoneId getZoneId (String zoneString) {
        try {
            return ZoneId.of(zoneString);
        } catch (DateTimeException e) {
            System.err.println("Invalid time zone: " + zoneString +
                "; using default time zone instead.");
            return ZoneId.systemDefault();
        }
    }

    default public ZonedDateTime getZonedDateTime(String zoneString) {
        return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }    
}

因为abstract是应用于abstract方法上的关键字,所以abstract方法不指定主体。而静态关键字则属于类区域。

首先,关于抽象类的一个关键点—— 抽象类不能被实例化(参见wiki)。因此,您不能创建抽象类的任何实例。

现在,java处理静态方法的方法是与该类的所有实例共享该方法。

所以,如果你不能实例化一个类,这个类就不能有抽象静态方法,因为抽象方法需要扩展。

繁荣。