Sub topic 4
Outer.this and outer.new Inner()
This chapter covers the two syntax forms that connect an inner class object to its enclosing object. outer.new Inner() creates an inner object attached to a chosen outer object. Outer.this lets the inner object refer back to that outer object. It assumes you can read basic Java classes, know the difference between instance and static members, and have seen the four kinds of nested class from the overview. The previous chapter showed that an inner class is a non-static member class. Here you learn how the link to the outer object is created and used.
The enclosing instance
Every object of an inner class has a hidden, fixed reference to an instance of its enclosing class. The Java Language Specification calls it the immediately enclosing instance. The reference is set when the inner object is constructed and cannot be changed afterwards.
This is the main difference from a static nested class, which has no such reference. It also explains why an inner class can use the outer object's fields and methods without qualification.
public class Counter {
private int count;
public class Incrementer {
private final int step;
public Incrementer(int step) { this.step = step; }
public void run() { count += step; }
public Counter owner() { return Counter.this; }
}
public int get() { return count; }
public static void main(String[] args) {
Counter c = new Counter();
Counter.Incrementer inc = c.new Incrementer(2);
inc.run();
inc.run();
System.out.println(c.get()); // 4
System.out.println(inc.owner() == c); // true
}
}Two things happen in main:
c.new Incrementer(2)creates anIncrementerwhose enclosing instance isc.run()changescount, which is reallyCounter.this.count, soc.get()reports 4.
Creating inner objects: outer.new Inner()
The compiler needs an enclosing instance every time you construct an inner class. There are three ways to supply one.
| Where you write the `new` | Form | Enclosing instance used |
|---|---|---|
| Instance method or constructor of the outer class | `new Inner()` | `this` |
| Inside another inner class of the same outer class | `new Inner()` | The innermost enclosing instance of the outer type |
| Any code with an outer reference, including `static` methods | `outer.new Inner()` | The object named by `outer` |
In the first case you rarely notice the link:
public class Library {
private final String name;
public Library(String name) { this.name = name; }
class Member {
String card() { return "Card of " + name; }
}
Member join() {
return new Member(); // same as this.new Member()
}
public static void main(String[] args) {
Library a = new Library("North");
Library b = new Library("South");
Library.Member m1 = a.join();
Library.Member m2 = b.new Member();
System.out.println(m1.card()); // Card of North
System.out.println(m2.card()); // Card of South
}
}m1 and m2 have the same class but different enclosing instances, so they read different name values. The type name Library.Member is the same for both. The enclosing instance is part of the object, not part of its type.
The qualified form in detail
In outer.new Inner() the left side is an ordinary expression whose type is the outer class. Three details are easy to miss:
- You write the simple name
Innerafternew, notOuter.Inner. The outer expression already fixes where the name is looked up. Writingc.new Counter.Incrementer(2)does not compile. - If
outerisnull, the expression throwsNullPointerException. - The outer expression is evaluated before the constructor arguments.
The usual mistake: constructing from a static context
A static method has no this, so an unqualified new Inner() has nothing to attach to. This fails in main:
Counter.Incrementer bad = new Counter.Incrementer(2);
// error: an enclosing instance that contains Counter.Incrementer is requiredYou have two fixes. Supply an outer object with c.new Incrementer(2). Or, if the class never uses the outer instance, declare it static and construct it with new Counter.Incrementer(2).
Referring to the outer object: Outer.this
Inside an inner class, this means the inner object. To get the enclosing object, write the outer class name, a dot, and this. The qualified this is useful in these cases:
- Passing the outer object to another method or storing it, as
owner()does inCounter. - Calling an outer method that an inner member hides (see below).
- Comparing or identifying the outer object, for example in
equalsor logging.
Fields and methods of the outer class are also reachable by their plain names. Outer.this.field and field mean the same thing when nothing else called field is in scope. The next chapter section on shadowing covers what happens when something is.
More than one level of nesting
Each level of nesting adds one enclosing instance, and you can name any of them by its class:
public class Levels {
private String name = "level1";
class Middle {
private String name = "level2";
class Deep {
void print() {
System.out.println(Levels.this.name); // level1
System.out.println(Middle.this.name); // level2
}
}
}
public static void main(String[] args) {
Levels l = new Levels();
Levels.Middle m = l.new Middle();
Levels.Middle.Deep d = m.new Deep();
d.print();
}
}Deep has two hidden references: one to a Middle and, through it, one to a Levels. Each new supplies only the immediately enclosing instance. To build Deep you need a Middle, and that Middle already carries its Levels.
Outer.this only works for lexically enclosing classes
X.this is legal only when the code is inside the body of class X (or inside a class nested within it) and an instance of X exists at that point. Inheritance does not count. If Inner extends Base, you cannot write Base.this unless Inner is also nested inside Base.
In a static nested class there is no outer instance, so Outer.this is a compile error:
static class Nested {
Object o() { return Outer.this; } // error: no enclosing instance of type Outer is in scope
}Method names that hide outer methods
Java looks up a method name in the innermost class that has a member with that name. It does not keep searching outward for a better match on the parameter types. An inner method can therefore hide outer methods that have the same name but a different signature.
public class MethodHiding {
void log(String message) { System.out.println("outer: " + message); }
class Inner {
void log() { System.out.println("inner"); }
void test() {
// log("hi"); // compile error: Inner.log() takes no arguments
MethodHiding.this.log("hi");
}
}
public static void main(String[] args) {
new MethodHiding().new Inner().test(); // outer: hi
}
}Fields behave differently: a field in the inner class hides an outer field only if the names match. Qualifying with Outer.this resolves both cases.
Inheriting from an inner class
A subclass of an inner class must also be given an enclosing instance for its superclass part. If the subclass is not itself nested in the same outer class, the constructor must supply one explicitly with outer.super(...):
public class Outer {
class Inner {
String who() { return "inner of " + Outer.this; }
}
static class Sub extends Outer.Inner {
Sub(Outer o) {
o.super(); // the enclosing instance for Inner
}
}
@Override
public String toString() { return "an Outer"; }
public static void main(String[] args) {
System.out.println(new Sub(new Outer()).who()); // inner of an Outer
}
}Without o.super(), the compiler reports that no enclosing instance of type Outer is in scope for the implicit super() call. If Sub were itself an inner class of Outer, the implicit call would work, because Sub would already have an outer instance to pass on.
Common errors
- Writing
new Outer.Inner()in a static method, which gives "an enclosing instance that contains Outer.Inner is required". - Writing
outer.new Outer.Inner()instead ofouter.new Inner(). - Using
Outer.thisin a static nested class or a static method. - Forgetting that an inner method named
loghides every outer method namedlog. - Expecting
outer.new Inner()to work whenInneris static. For a static member class it is a compile error, and you writenew Outer.Inner().
Exercise
A class Shop has an inner class Cart with a method void checkout() and a field int items. In Shop's static void main, you have Shop s = new Shop();. Write the statement that creates a Cart belonging to s. Then say what Shop.this means inside Cart.checkout().
Show answer
Shop.Cart cart = s.new Cart();. Inside checkout(), Shop.this is the Shop object that was used to create that Cart, here s. It is fixed at construction and cannot be reassigned.
Exercise
Inner class Worker is declared in Pool. Pool has void report(String s). Worker declares void report() and wants to call the outer report("done"). Why does the plain call report("done") fail, and how do you fix it?
Show answer
The compiler finds the name report in Worker first and stops searching outward, so only Worker.report() is considered, and it takes no arguments. Write Pool.this.report("done").
Exercise
main contains Levels.Middle m = new Levels().new Middle();. Using the Levels class from this chapter, write the expression that builds a Deep and name the two enclosing instances it ends up referencing.
Show answer
Levels.Middle.Deep d = m.new Deep();. Its immediately enclosing instance is m (a Middle), and through m it also reaches the Levels object created by new Levels(), available as Levels.this inside Deep.