Behaviour of final static method

Harish picture Harish · Nov 16, 2009 · Viewed 48k times · Source

I have been playing around with modifiers with static method and came across a weird behaviour.

As we know, static methods cannot be overridden, as they are associated with class rather than instance.

So if I have the below snippet, it compiles fine

//Snippet 1 - Compiles fine
public class A {
    static void ts() {
    }
}

class B extends A {
    static void ts() {
    }
}

But if I include final modifier to static method in class A, then compilation fails ts() in B cannot override ts() in A; overridden method is static final.

Why is this happening when static method cannot be overridden at all?

Answer

NawaMan picture NawaMan · Nov 16, 2009

Static methods cannot be overridden but they can be hidden. The ts() method of B is not overriding(not subject to polymorphism) the ts() of A but it will hide it. If you call ts() in B (NOT A.ts() or B.ts() ... just ts()), the one of B will be called and not A. Since this is not subjected to polymorphism, the call ts() in A will never be redirected to the one in B.

The keyword final will disable the method from being hidden. So they cannot be hidden and an attempt to do so will result in a compiler error.

Hope this helps.