Overriding final static method in Java

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?

  1. 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.
  2. 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 !!

Leave a Reply

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial