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

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

当前回答

因为抽象方法总是需要通过子类来实现。但是如果你将任何方法设置为静态,那么就不可能重写这个方法

例子

abstract class foo {
    abstract static void bar2(); 
}


class Bar extends foo {
    //in this if you override foo class static method then it will give error
}

其他回答

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.

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

您可以使用Java 8中的接口来实现这一点。

这是关于它的官方文件:

https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

因为如果你在类中使用任何静态成员或静态变量,它将在类加载时加载。

有一种情况是静态和抽象可以一起使用,那就是当这两个修饰符都放在嵌套类的前面时。