问题是,在Java中为什么不能定义抽象静态方法?例如
abstract class foo {
abstract void bar( ); // <-- this is ok
abstract static void bar2(); //<-- this isn't why?
}
问题是,在Java中为什么不能定义抽象静态方法?例如
abstract class foo {
abstract void bar( ); // <-- this is ok
abstract static void bar2(); //<-- this isn't why?
}
当前回答
糟糕的语言设计。直接调用静态抽象方法要比为使用该抽象方法而创建实例有效得多。当使用抽象类作为枚举无法扩展的变通方法时尤其如此,这是另一个糟糕的设计示例。希望他们能在下一个版本中解决这些限制。
其他回答
我也问了同样的问题,原因如下
因为抽象类说,它不会给出实现,并允许子类给出它
所以子类必须重写超类的方法,
规则1 -静态方法不能被覆盖
因为静态成员和方法是编译时元素,这就是为什么允许重载(编译时多态性)静态方法而不是重写(运行时多态性)
所以它们不可能是抽象的。
Java宇宙中不允许有抽象静态<——之类的东西
将一个方法声明为静态意味着我们可以通过它的类名调用该方法,如果这个类也是抽象的,那么调用它就没有意义了,因为它不包含任何主体,因此我们不能同时将一个方法声明为静态的和抽象的。
因为abstract是应用于abstract方法上的关键字,所以abstract方法不指定主体。而静态关键字则属于类区域。
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.
因为“抽象”意味着方法是要被重写的,而不能重写“静态”方法。