Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top