This is called shadowing.
According to JLS 6.4.1
Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.
It's convenient to have shadowing in programming language. For example, in constructors, you can have both parameters and class field variables the same name, and use this
to distinguish them.
class Person {
private String name;
Person (String name) {
this.name = name;
}
}
In some other languages, variables may be shadowed by code blocks, for example, in C++ you can write code like:
// C++ code:
int i = 10;
for(int i = 0; i != 5; ++i) {
// use i from 0 to 4 here
}
for(int i = 100; i > 0; --i) {
// use i from 100 to 1 here
}
// the first i is still 10 and can be used here
The variable i
inside the loop is different from the outside i
.
Why is the language designed like that?
As you can see in the constructor example, sometimes variables may really mean the same thing. Shadowing makes you can use the same names without creating a new name, which is kind of bothering because naming a variable is not quiet simple.
And in the loop sample, which is not supported in Java but is a great sample to show the advantage of shadowing, sometimes in code block you may declared some temporary variables without modifying other variables outside the block.
Why method shadowing is based on method name not method signature?
In JLS 15.12, there's a explanation about method invocation.
You can see that in step 1, compiler will search for the scope that can call this method. In the end, it found Enclosing.Inner
.
And at step 2, compiler will check signature of the methods.
Therefore, compiler will take Enclosing.Inner.method()
as the only method that is available to call. That's why you can't call Enclosing.method(String str)
directly, even though they have different method signature.
If you want to call Enclosing.method(String str)
inside the Inner
class, you can do:
class Inner {
void method(){
Enclosing.this.method("test");
}
}