问题是,在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?
}
当前回答
你不能重写静态方法,所以使它抽象是没有意义的。此外,抽象类中的静态方法将属于该类,而不是覆盖类,因此无论如何都不能使用。
其他回答
有一种情况是静态和抽象可以一起使用,那就是当这两个修饰符都放在嵌套类的前面时。
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