Can we override static method in java? Well, all of us know about method overriding and method hiding. Have you tried to override static method, specially when method is final
in parent class.
Java program to override final static method
Below is the program, I written for testing various combinations of keywords. So, please refer to this program for further discussion.
package staticTest; class SuperClass { static void display() { System.out.println("Super"); } } class SubClass extends SuperClass { static void display() { System.out.println("Sub"); } } public class Test { public static void main(String[] args) { // Prints "Super" in console SuperClass sup = new SubClass(); sup.display(); // Prints "Sub" in console SubClass sub = new SubClass(); sub.display(); } }
Is it method overriding or method hiding?
- Above code will compile successfully without warning or error. This is the case of method hiding where sub class’s static method hide the static method from super class.
- If we remove the static keyword from display method in subclass, compiler complains that you can not override static method from super class.
As we know, static methods can not be overridden. They can only be hidden from child classes. So, the compiler message in this case should be considered wrong. The correct message should have been “The instance method cannot “hide” the static method from super class”.
Now in above code sample, add final to super class’s display method. Again the compiler start complaining that “Cannot override the final method from SuperClass”.
This is also misleading for above given reasons. Here also the correct message should have been “Cannot hide the final method from SuperClass”
Summary
Why static method cannot be overridden in Java? In my point of view, method overriding is only valid when we are talking in terms of instance methods. As soon as we start talking in terms of static methods, term should be used is method hiding.
Fortunately, above terms are in use in most of the Java literature (even in Java Language Specification) , but still it has to be updated, I guess.
Please let me know of your thoughts around Java override final static method, why static method cannot be overridden in java and can we override a non-static method as static in Java.
Happy Learning !!
Nice articale
Hi Team,
Nice article,
But i want to give some input on overloading and static overloading.
overloading :- Think a new function
overriding :- subclass override method of parent class
More information (looks concept of method area)
References :- create in compile time
Object :- Create in runtime
Static :- Class level
instance method :- depends on object
Might be @Bharat Shivram will be got his answer
i.e static method depends only and only references not instance (object)
so that you will get a,d
superb