Why can't static methods be abstract in Java?

后端 未结 25 2941
不思量自难忘°
不思量自难忘° 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条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 08:49

    Assume there are two classes, Parent and Child. Parent is abstract. The declarations are as follows:

    abstract class Parent {
        abstract void run();
    }
    
    class Child extends Parent {
        void run() {}
    }
    

    This means that any instance of Parent must specify how run() is executed.

    However, assume now that Parent is not abstract.

    class Parent {
        static void run() {}
    }
    

    This means that Parent.run() will execute the static method.

    The definition of an abstract method is "A method that is declared but not implemented", which means it doesn't return anything itself.

    The definition of a static method is "A method that returns the same value for the same parameters regardless of the instance on which it is called".

    An abstract method's return value will change as the instance changes. A static method will not. A static abstract method is pretty much a method where the return value is constant, but does not return anything. This is a logical contradiction.

    Also, there is really not much of a reason for a static abstract method.

提交回复
热议问题