Why static medthods cant be abstract ?

Recommended Answers

All 2 Replies

Instance methods can be overidden, but static methods cannot (they can only be masked).
When the virtual machine invokes an instance method, it selects the method to invoke based on the actual class of the object, which may only be known at run time. On the other hand, when the Java virtual machine invokes a class method, it selects the method to invoke based on the type of the object reference, which is always known at compile-time.
So an abstract instance method is useful because you can write your code using the abstract superclass, and the non-abstract overriding subclass methods wil be invoked at run time.
But an abstract static method is useless; you can't call it and you can't override it; there is no way ever to use it.

In abstract method is usually defined in an abstract class or an interface,for which implementation is provided in a subclass or a class implementing the interface.As static methods just have single copy per class and are interpreted at code compile time,not at runtime, so it is impossible to have polymorphic behaviour out of them.In other words, they cannot be overridden.

An abstract class is one which cannot be instantiated but a static method defined in abstract class can be invoked without creating an instance.So there is no mechanism to ensure call of an abstract static method.

Also
The abstract annotation to a method indicates that the method MUST be overriden in a subclass. In Java, a static member (method or field) cannot be overridden by subclasses (this is not necessarily true in other object oriented languages, see SmallTalk.)
Since static members cannot be overriden in a subclass, the abstract annotation cannot be applied to them.

It might be

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.