问题是,在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.
其他回答
你不能重写静态方法,所以使它抽象是没有意义的。此外,抽象类中的静态方法将属于该类,而不是覆盖类,因此无论如何都不能使用。
当常规方法要被子类覆盖并提供功能时,它们可以是抽象的。 假设类Foo由Bar1, Bar2, Bar3等扩展。因此,每个人都将根据自己的需要拥有自己的抽象类版本。
静态方法根据定义属于类,它们与类的对象或类的子类的对象无关。它们甚至不需要它们存在,它们可以在不实例化类的情况下使用。因此,它们需要准备就绪,不能依赖于子类向它们添加功能。
将一个方法声明为静态意味着我们可以通过它的类名调用该方法,如果这个类也是抽象的,那么调用它就没有意义了,因为它不包含任何主体,因此我们不能同时将一个方法声明为静态的和抽象的。
静态方法 可以调用静态方法,而不需要创建类的实例。静态方法属于类,而不是类的对象。 静态方法可以访问静态数据成员,也可以改变它的值。 摘要关键字用于实现抽象。 静态方法不能在子类中重写或实现。因此,把静态方法做得抽象是没有用的。
假设有两个类,父类和子类。父母是抽象的。声明如下:
abstract class Parent {
abstract void run();
}
class Child extends Parent {
void run() {}
}
这意味着Parent的任何实例都必须指定如何执行run()。
但是,现在假设Parent不是抽象的。
class Parent {
static void run() {}
}
这意味着Parent.run()将执行静态方法。
抽象方法的定义是“声明但未实现的方法”,这意味着它本身不返回任何东西。
静态方法的定义是“对于相同的参数返回相同值的方法,而不管调用它的实例是什么”。
抽象方法的返回值会随着实例的改变而改变。静态方法则不会。静态抽象方法基本上是这样一种方法,它的返回值是常量,但不返回任何东西。这是一个逻辑矛盾。
同样,使用静态抽象方法的理由也不多。