Sub topic 2
Shadowing Between Inner and Outer Names
Assume you know instance versus static members, access modifiers, interfaces, and basic method overriding. This chapter focuses on scope: the part of a program where a name can be used.
Shadowing between inner and outer names
Shadowing happens when a nearer declaration uses the same name as a declaration in an outer scope. Java chooses the nearest matching name:
xmeans the method parameter.this.xmeans the current inner object's field.Outer.this.xmeans the enclosing object's field.
public class ShadowDemo {
private int x = 1;
class Inner {
private int x = 2;
void show(int x) {
System.out.println(x); // 3
System.out.println(this.x); // 2
System.out.println(ShadowDemo.this.x); // 1
}
}
public static void main(String[] args) {
new ShadowDemo().new Inner().show(3);
}
}Use distinct names when possible. Qualified names are useful when a design requires the same name at several levels.
Local classes declared inside methods
A local class is declared inside a method, constructor, or block. It is useful when a helper type belongs only to one operation. Its declaration cannot normally be used outside that enclosing block.
Capturing effectively final variables
A local or anonymous class can read a local variable or parameter when that variable is final or effectively final. Effectively final means the variable receives one value and is never reassigned.
static Runnable makeGreeter(String name) {
class Greeter implements Runnable {
@Override
public void run() {
System.out.println("Hello, " + name);
}
}
return new Greeter();
}Reassigning name after the class is created would cause a compile-time error. Java captures the value for use later; it does not provide a changing local variable.
Anonymous classes
An anonymous class is a class without a declared name, created at the point where it is needed. It can implement an interface or extend a class, override methods, and keep fields of its own.
Runnable task = new Runnable() {
private int calls;
@Override
public void run() {
calls++;
System.out.println(calls);
}
};Use an anonymous class when the implementation needs state, several methods, or an abstract-class parent. For a single stateless interface method, a lambda is usually shorter.
Exercise
In an inner class method with parameter x, how do you access the parameter, inner field, and outer field?
Show answer
Use x, this.x, and Outer.this.x, respectively.