The reason is that Java uses the concept of the lexical domain to resolve variables.
In essence, there are two possibilities for solving free variables in a function (“free” means not local and not tied to function parameters):
1) against the environment in which the function is declared
2) against the environment in which the function is performed (called)
Java goes the first way, therefore free variables in methods are resolved [statically, at compile time] in relation to their lexical area (environment), which includes:
- method parameters and local variables of the method
- field declarations in a class containing a method declaration
- open field declarations in the parent class
- etc., up the inheritance chain
You will see that this behavior is implemented in most programming languages, as it is transparent to developers and helps prevent errors with variable shading.
This is the opposite of how methods work in Java:
class A { public void foo() { boo(); } public void boo() { System.out.println("A"); } } class B extends A { @Override public void boo() { System.out.println("B"); } } class Main { public static void main(String[] args) { B b = new B(); b.foo();
This is called a dynamic dispatcher: a method call is dynamically resolved at run time against the actual object on which it is called.
Andrei Tomashpolskiy Jan 27 '14 at 10:46 a.m. 2014-01-27 10:46
source share