Search code examples
javaoverridingmethod-hiding

java non-static to static method -- hiding or overriding


is re-defining a non-static method in a subclass with the same everything but as static overriding or hiding it ?

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html says hiding. but when i declare the superclass method as final, i get an override error.

superclass declaration is

final static void display() { ... }

subclass:

void display() { ... }

gives override error.


Solution

  • Is re-defining a non-static method in a subclass with the same everything but as static overriding or hiding it?

    It's neither, because doing so triggers a compilation error, rendering your program invalid.

    class A {
        void x();
    }
    class B extends A {
        // ERROR!!!
        static void x();
    }
    

    Hiding happens when both methods in the pair are static methods; overriding happens when both methods in the pair are instance methods. When one of the two is a static method and the other one is an instance method, Java considers it an error. It does not matter if the instance method is final or not; it also does not matter if the static method is in the base or in the derived class: Java calls it an error either way.

    The compiler message that says "cannot override" is misleading, though: I think that "name collision" would have been a better name for such conditions, because "overriding" is reserved for situations with two instance methods.