Monday, April 16, 2012

Behaviour of final static method


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?


Source: Tips4all

6 comments:

  1. Static methods cannot be overridden but they can be hidden. ts() method of B is not overridden (not subject to polymorphism) ts() of A but 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.

    ReplyDelete
  2. static methods cannot be overriden


    This is not exactly true. The example code really means that the method ts in B hides the method ts in A. So its not exactly overriding. Over on Javaranch there is a nice explanation.

    ReplyDelete
  3. Static methods belong to the class, not the instance.

    A.ts() and B.ts() are always going to be separate methods.

    The real problem is that Java lets you call static methods on an instance object. Static methods with the same signature from the parent class are hidden when called from an instance of the subclass. However, you can't override/hide final methods.

    You would think the error message would use the word hidden instead of overridden...

    ReplyDelete
  4. I think the compilation error was quite misleading here. It should not have said "overridden method is static final.", but it should instead have said "overridden method is final.". The static modifier is irrelevant here.

    ReplyDelete
  5. The ts() method in B is not overriding the ts() method in A, it simply is another method. The B class does not see the ts() method in A since it is static, therefore it can declare its own method called ts().

    However, if the method is final, then the compiler will pick up that there is a ts() method in A that should not be overridden in B.

    ReplyDelete
  6. Not an answer. But isn't this an issue because language (Java, in this case) allows calling a static method via an instance variable?

    ReplyDelete