Understanding the compiler error message when hiding final static methods

Well, all of us know about method overriding and method hiding. Have you tried extending static methods, specially when they are final in parent class. Lets see my observations.

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();
	}
}

Observations and conclusions:

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”.

3) 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”

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.

Happy Learning !!

Ads by Google

One thought on “Understanding the compiler error message when hiding final static methods”

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Want to ask any question? Or suggest anything?