问题是,在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?
}
当前回答
首先,关于抽象类的一个关键点—— 抽象类不能被实例化(参见wiki)。因此,您不能创建抽象类的任何实例。
现在,java处理静态方法的方法是与该类的所有实例共享该方法。
所以,如果你不能实例化一个类,这个类就不能有抽象静态方法,因为抽象方法需要扩展。
繁荣。
其他回答
你不能重写静态方法,所以使它抽象是没有意义的。此外,抽象类中的静态方法将属于该类,而不是覆盖类,因此无论如何都不能使用。
因为“抽象”意味着方法是要被重写的,而不能重写“静态”方法。
您可以使用Java 8中的接口来实现这一点。
这是关于它的官方文件:
https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
抽象类不能有静态方法,因为抽象是为了实现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.