Why can't static methods be abstract in Java?

后端 未结 25 2679
不思量自难忘°
不思量自难忘° 2020-11-22 08:34

The question is in Java why can\'t I define an abstract static method? for example

abstract class foo {
    abstract void bar( ); // <-- this is ok
    ab         


        
25条回答
  •  Happy的楠姐
    2020-11-22 08:46

    A static method can be called without an instance of the class. In your example you can call foo.bar2(), but not foo.bar(), because for bar you need an instance. Following code would work:

    foo var = new ImplementsFoo();
    var.bar();
    

    If you call a static method, it will be executed always the same code. In the above example, even if you redefine bar2 in ImplementsFoo, a call to var.bar2() would execute foo.bar2().

    If bar2 now has no implementation (that's what abstract means), you can call a method without implementation. That's very harmful.

提交回复
热议问题