问题是,在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?
}
当前回答
静态方法可以在没有类实例的情况下调用。在你的例子中,你可以调用foo.bar2(),但不能调用foo.bar(),因为bar需要一个实例。 以下代码将工作:
foo var = new ImplementsFoo();
var.bar();
如果您调用一个静态方法,它将始终执行相同的代码。在上面的例子中,即使你在ImplementsFoo中重新定义了bar2,调用var.bar2()也会执行foo.bar2()。
如果bar2现在没有实现(这就是抽象的意思),您可以调用没有实现的方法。这是非常有害的。
其他回答
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文档:
静态方法是与其中的类相关联的方法 它是定义的,而不是与任何对象。类的每个实例 共享它的静态方法
在Java 8中,除了默认方法外,接口中还允许使用静态方法。这使得我们更容易在库中组织helper方法。我们可以在同一个接口中保留特定于某个接口的静态方法,而不是在一个单独的类中。
一个很好的例子是:
list.sort(ordering);
而不是
Collections.sort(list, ordering);
另一个使用静态方法的例子也在doc中给出:
public interface TimeClient {
// ...
static public ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
System.err.println("Invalid time zone: " + zoneString +
"; using default time zone instead.");
return ZoneId.systemDefault();
}
}
default public ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
}
你不能重写静态方法,所以使它抽象是没有意义的。此外,抽象类中的静态方法将属于该类,而不是覆盖类,因此无论如何都不能使用。
因为如果一个类扩展了一个抽象类,那么它必须重写抽象方法,这是强制性的。由于静态方法是在编译时解析的类方法,而覆盖方法是在运行时解析的实例方法,并遵循动态多态性。
根据定义,静态方法不需要知道这些。因此,它不能是一个虚方法(根据通过this获得的动态子类信息重载);相反,静态方法重载仅基于编译时可用的信息(这意味着:一旦引用了父类的静态方法,就调用父类方法,而不调用子类方法)。
根据这一点,抽象静态方法将是非常无用的,因为您永远不会用一些已定义的对象来代替它的引用。