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
abstract static void bar2(); //<-- this isn't why?
}
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
abstract static void bar2(); //<-- this isn't why?
}
Because "abstract" means: "Implements no functionality", and "static" means: "There is functionality even if you don't have an object instance". And that's a logical contradiction.
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.
Assume there are two classes,
Parent
andChild
.Parent
isabstract
. The declarations are as follows:This means that any instance of
Parent
must specify howrun()
is executed.However, assume now that
Parent
is notabstract
.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. Astatic
method will not. Astatic 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.First, a key point about abstract classes - An abstract class cannot be instantiated (see wiki). So, you can't create any instance of an abstract class.
Now, the way java deals with static methods is by sharing the method with all the instances of that class.
So, If you can't instantiate a class, that class can't have abstract static methods since an abstract method begs to be extended.
Boom.
because if you are using any static member or static variable in class it will load at class loading time.
Because if a class extends an abstract class then it has to override abstract methods and that is mandatory. And since static methods are class methods resolved at compile time whereas overridden methods are instance methods resolved at runtime and following dynamic polymorphism.