问题是,在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.

其他回答

静态方法可以在没有类实例的情况下调用。在你的例子中,你可以调用foo.bar2(),但不能调用foo.bar(),因为bar需要一个实例。 以下代码将工作:

foo var = new ImplementsFoo();
var.bar();

如果您调用一个静态方法,它将始终执行相同的代码。在上面的例子中,即使你在ImplementsFoo中重新定义了bar2,调用var.bar2()也会执行foo.bar2()。

如果bar2现在没有实现(这就是抽象的意思),您可以调用没有实现的方法。这是非常有害的。

将一个方法声明为静态意味着我们可以通过它的类名调用该方法,如果这个类也是抽象的,那么调用它就没有意义了,因为它不包含任何主体,因此我们不能同时将一个方法声明为静态的和抽象的。

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

因为“抽象”意味着方法是要被重写的,而不能重写“静态”方法。

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