Sub topic 5
Shadowing between inner and outer names
This chapter assumes you can write basic Java classes and know the difference between instance and static members. It also assumes you have seen the inner class syntax from the previous chapters, including Outer.this. Here you will learn how Java decides which declaration a plain name refers to when an inner class, its enclosing class, and a method all use the same identifier.
What shadowing is
Shadowing happens when a declaration in an inner scope has the same name as a declaration in an outer scope. Inside the inner scope, the simple name refers to the inner declaration. The outer one still exists, but a plain use of the name no longer reaches it.
Nested classes create more scopes than a single class does. A name used inside an inner class body can be:
- a local variable or parameter of the current method,
- a member (field or method) of the inner class, including members it inherits,
- a member of the enclosing class,
- a local variable or parameter of a method that encloses a local or anonymous class,
- a member of a further enclosing class.
The compiler checks these scopes from the innermost outward. The first match wins.
Fields: three levels, three spellings
You can reach each level of a shadowed name with an explicit form:
| You write | It refers to |
|---|---|
| `x` | The innermost declaration in scope (parameter, then inner field, then outer field) |
| `this.x` | The field `x` of the current object (the inner instance) |
| `Outer.this.x` | The field `x` of the enclosing instance |
This example uses all three at once.
public class Shadow {
private int x = 1;
class Inner {
private int x = 2;
void show(int x) {
System.out.println(x); // 3 (parameter)
System.out.println(this.x); // 2 (Inner field)
System.out.println(Shadow.this.x); // 1 (outer field)
}
}
public static void main(String[] args) {
new Shadow().new Inner().show(3);
}
}The program prints 3, 2, and 1. The parameter hides the inner field, and the inner field hides the outer field. Qualifying the name with this. or Shadow.this. skips the closer declarations.
You can only write Outer.this where an enclosing instance exists. A static nested class has none, so shadowing there is resolved with the class name instead.
public class StaticShadow {
static int x = 1;
static class Nested {
int x = 2;
void show() {
System.out.println(x); // 2
System.out.println(StaticShadow.x); // 1
}
}
public static void main(String[] args) {
new Nested().show();
}
}StaticShadow.x works because x is a static field. If x were an instance field of the outer class, a static nested class could not read it by simple name at all. It would need an explicit StaticShadow reference passed in.
Methods: shadowing hides every overload
Methods shadow differently from fields, and this catches many people. Java looks for the method by name first. It finds the innermost class that has any member method with that name, and it searches only that class (and its supertypes) for a match. Overload resolution then happens inside that one class. Outer methods with the same name are not considered, even if their parameter lists would match the call.
public class MethodHiding {
void log(String msg) {
System.out.println("outer: " + msg);
}
void log(String msg, int level) {
System.out.println("outer level " + level + ": " + msg);
}
class Inner {
void log(String msg) {
System.out.println("inner: " + msg);
}
void demo() {
log("a"); // inner: a
// log("b", 2); // compile error: no log(String, int) in Inner
MethodHiding.this.log("b", 2); // outer level 2: b
}
}
public static void main(String[] args) {
new MethodHiding().new Inner().demo();
}
}The output is inner: a and then outer level 2: b. If you uncomment the middle call, the compiler reports that Inner.log cannot be applied to (String, int). It does not fall back to the outer overload.
Inherited members count as inner members
An inner class can inherit fields and methods from its superclass. Inherited members are members of the inner class, so they sit at the same level as the ones it declares itself. They hide the enclosing class's members of the same name.
Suppose Outer has a field name, and Inner extends Base where Base also has an accessible field name. Inside Inner, a plain name refers to the inherited Base.name, not Outer.name. Nothing in the code points this out, so a rename in Base can silently change which field an inner class reads. When the inner class could confuse two sources, write this.name or Outer.this.name so the reader and the compiler agree.
Local variables captured by local and anonymous classes
Local and anonymous classes add one more scope: the enclosing method's local variables and parameters. A class body is a new declaration space, so its members may reuse the name of a captured local variable.
public class CaptureShadow {
public static void main(String[] args) {
int n = 1;
Runnable anon = new Runnable() {
int n = 2; // legal: a field of the anonymous class shadows the local n
@Override
public void run() {
int total = 10;
System.out.println(n); // 2
System.out.println(total); // 10
}
};
anon.run();
System.out.println(n); // 1
}
}Inside run, n means the anonymous class's field, so the captured local n is unreachable by simple name. There is no syntax like Outer.this for reaching a shadowed local variable. If you need both values, give them different names.
A lambda is different. A lambda body is not a new class, so it shares the scope of the enclosing method. It cannot declare a local variable or parameter whose name matches a local variable already in scope.
public class LambdaScope {
public static void main(String[] args) {
int n = 1;
// Runnable r = () -> { int n = 3; }; // compile error: n is already defined
Runnable r = () -> { int m = 3; System.out.println(n + m); }; // 4
r.run();
}
}This gives a rule to remember. An anonymous class allows shadowing of enclosing locals, and a lambda forbids it.
`this` means different things in different bodies
The meaning of this changes with the construct, which matters when shadowing is involved. Inside an anonymous class, this is the anonymous object. Inside a lambda, this is the enclosing object, because the lambda introduces no new class.
public class ThisDemo {
private final String name = "outer";
void run() {
Runnable anon = new Runnable() {
private final String name = "anon";
@Override
public void run() {
System.out.println(name); // anon
System.out.println(ThisDemo.this.name); // outer
}
};
Runnable lambda = () -> System.out.println(this.name); // outer
anon.run();
lambda.run();
}
public static void main(String[] args) {
new ThisDemo().run();
}
}The output is anon, outer, outer. If you convert an anonymous class to a lambda and its body used this.name or relied on a shadowing field, the behavior changes. Check each this and each shadowed name before you convert.
Common mistakes
- Assigning to the wrong variable. In a setter or constructor of an inner class,
x = x;assigns the parameter to itself. Writethis.x = x;. - Expecting an outer overload to be found. Same-named methods in the inner class hide all outer overloads, as shown above.
- Writing
Outer.thisin a static context. This does not compile in a static nested class or in a static method. There is no enclosing instance. - Reusing a local name in a lambda. The compiler rejects it with "variable already defined". An anonymous class would accept it.
- Relying on shadowing for clarity. Code that works only because of a name collision is hard to review. Prefer distinct names, and use qualification when a collision is unavoidable.
Summary of the rules
- Simple names resolve from the innermost scope outward, and the first match wins.
this.xselects the current object's field.Outer.this.xselects the enclosing object's field.Outer.xselects a static field.- A method name in an inner class hides all outer methods of that name, whatever their parameters.
- Inherited members hide enclosing-class members of the same name.
- Local and anonymous class bodies may shadow enclosing locals. Lambdas may not.
Exercise
What does this program print, and why? Which line would you change to print 10 instead of the last value? public class Quiz { int v = 10; class A { int v = 20; class B { int v = 30; void show(int v) { System.out.println(v); System.out.println(this.v); System.out.println(A.this.v); System.out.println(Quiz.this.v); } } } public static void main(String[] args) { new Quiz().new A().new B().show(40); } }
Show answer
It prints 40, 30, 20, 10, one per line. The plain v is the parameter, this.v is B's field, A.this.v is the field of the enclosing A instance, and Quiz.this.v is the field of the outermost Quiz instance. The last line already prints 10, the Quiz field. To make an earlier line print 10 instead, change it to Quiz.this.v.
Exercise
A class Outer has methods void send(String s) and void send(String s, int retries). Inside an inner class you add a method void send(String s) and then call send("x", 3) from another inner method. Does it compile? How do you fix it?
Show answer
It does not compile. The inner class declares a method named send, so the compiler searches only the inner class for send and finds no two-argument version. Outer overloads are hidden. Fix it by calling Outer.this.send("x", 3), or by renaming the inner method.