Saturday, April 12, 2008

Hiding and overriding in Java

For some technical terms in this post, please refer to JLS 3.0. And the discussion is not very precise. I have looked for some explicit rules governing this topic in JLS. But I failed. So I am just trying to summarize my personal understanding. Any feedbacks are welcomed.

In the following discussion, A and B are used. Type A extends type B (type means class or interface).

Field


Only hiding applies tojava fields. Hiding happens in the following situation.Both A and B have a variable named as var. And var is of the same kind of variables ( static fields or instance fields).
Java allows a variable belonging to different variable kinds appears in both A and B. But hiding does not happen in such situations.

Method


Method m1 in A . Method m2 in B.

  1. m1 is subsignature of m2

  2. m1's visibility is no less than m2

  3. Both m1 and m2 are instance methods. Or both m1 and m2 are static methods. Otherwise, there will some compile errors.


Overriding


Overriding applies to instance methods.

Hiding


Overriding applies to static methods.

No comments: