Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any legitimate reasons to hide static methods? [duplicate]

Possible Duplicate:
Why doesn't Java allow overriding of static methods?

Is there any legitimate reason why one would want a derived class to override hide a static method of the base class?

like image 899
Saket Avatar asked Sep 23 '11 04:09

Saket


2 Answers

Terminology aside, static methods in Java do have a kind of overriding relation, implied by binary compatibility section 13.4.12. If T extends S, S declared m(), T.m() can refer to a method in T or S, depending on if m() is declared in T; and it's ok to add or remove m() from T, without breaking any code calling T.m(). (This implies JVM invokestatic instruction does a sort of dynamic method lookup up the super class chain)

However, this is nothing but trouble. It is really dangerous if the meaning of T.m() silently changes because now it's pointing to a different method. (Instance methods shall inherit contracts so that's not a problem; there's no such understanding in static methods.)

So this "feature" should never be used; the language shouldn't have enabled it to begin with.

The good practice: If we call T.m(), m() must be declared in T; and it should never be removed from T without removing all T.m() first.

like image 133
irreputable Avatar answered Sep 20 '22 00:09

irreputable


Static methods cannot be overriden

In order to override a method, the method must first be inherited. If the method is not inherited there is no chance for overriding. Therefore, you can never override a private method as they are not inherited.

like image 42
Gregory Nozik Avatar answered Sep 22 '22 00:09

Gregory Nozik