A normal this
can never be null
in real Java code1, and your example uses a normal this
. See other the other answers for more details.
A qualified this
should never be null
, but is possible to break this. Consider the following:
public class Outer {
public Outer() {}
public class Inner {
public Inner() {}
public String toString() {
return "outer is " + Outer.this; // Qualified this!!
}
}
}
When we want to create an instance of Inner
, we need to do this:
public static void main(String[] args) {
Outer outer = new Outer();
Inner inner = outer.new Inner();
System.out.println(inner);
outer = null;
inner = outer.new Inner(); // FAIL ... throws an NPE
}
The output is:
outer is Outer@2a139a55
Exception in thread "main" java.lang.NullPointerException
at Outer.main(Outer.java:19)
showing that our attempt to create an Inner
with a null
reference to its Outer
has failed.
In fact, if you stick within the "Pure Java" envelope you cannot break this.
However, each Inner
instance has a hidden final
synthetic field (called "this$0"
) that contains the reference to the Outer
. If you are really tricky, it is possible to use "non-pure" means to assign null
to the field.
- You could use
Unsafe
to do it.
- You could use native code (e.g. JNI) to do it.
- You could do it by using reflection.
Either way you do it, the end result is that the Outer.this
expression will evaluate to null
2.
In short, it is possible for a qualified this
to be null
. But it is impossible if your program follows the "Pure Java" rules.
1 - I discount tricks such as "writing" the bytecodes by hand and passing them off as real Java, tweaking bytecodes using BCEL or similar, or hopping into native code and diddling with the saved registers. IMO, that is NOT Java. Hypothetically, such things might also happen as a result of a JVM bug ... but I don't recall every seeing bug reports.
2 - Actually, the JLS does not say what the behavior will be, and it could be implementation dependent ... among other things.