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

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

当前回答

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

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

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

繁荣。

其他回答

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

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

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

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

抽象类不能有静态方法,因为抽象是为了实现DYNAMIC BINDING,而静态方法是静态绑定到它们的功能上的。静态方法的意思是 行为不依赖于实例变量,因此没有实例/对象 是必需的。只是上课而已。静态方法属于类而不是对象。 它们存储在一个称为PERMGEN的内存区域中,每个对象都从这里共享它们。 抽象类中的方法动态地绑定到它们的功能上。

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.

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

例子

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
}

假设有两个类,父类和子类。父母是抽象的。声明如下:

abstract class Parent {
    abstract void run();
}

class Child extends Parent {
    void run() {}
}

这意味着Parent的任何实例都必须指定如何执行run()。

但是,现在假设Parent不是抽象的。

class Parent {
    static void run() {}
}

这意味着Parent.run()将执行静态方法。

抽象方法的定义是“声明但未实现的方法”,这意味着它本身不返回任何东西。

静态方法的定义是“对于相同的参数返回相同值的方法,而不管调用它的实例是什么”。

抽象方法的返回值会随着实例的改变而改变。静态方法则不会。静态抽象方法基本上是这样一种方法,它的返回值是常量,但不返回任何东西。这是一个逻辑矛盾。

同样,使用静态抽象方法的理由也不多。