I’ve read about the substitutability of super and this in Java, so that a reference to super is legal in the same places where this is legal in the superclass (with the exception of the code of class Object, in which super cannot appear). When I put this to the test it seems to fail as shown in the following example:
class OuterSuper {
public int oneNumber() { return 5; }
class Inners {}
int i1 = OuterSuper.this.oneNumber();
OuterSuper.Inners si1 = OuterSuper.this.new Inners();
}
class Outer extends OuterSuper {
class Inner {
int i1 = Outer.this.oneNumber();
int i2 = Outer.super.oneNumber();
OuterSuper.Inners si1 = Outer.this.new Inners();
OuterSuper.Inners si2 = Outer.super.new Inners();
}
}
The compiler balks at the last declaration, of member si2. In this example, I am able to write declarations for int i1 and i2 and it is just like the specification says, I can replace whatever I pass to super, to this in the superclass. For the inner class I am stuck and have to use this. Is this this a different this? I’m writing “Outer.this” and “Outer.super” in both instances…
I would like to share that I am using javac (the commandline JDK from Oracle 1.6) and NetBeans. The error I get from javac is:
Exe.java:32: <identifier> expected
OuterSuper.Inners si2 = Outer.super.new Inners();
^
Exe.java:32: invalid method declaration; return type required
OuterSuper.Inners si2 = Outer.super.new Inners();
^
2 errors
So, here are my two-cents. I was under the impression that
supercould only be used in a class to reference its own base class. I didn’t think it was allowed to reference another class’supereven given the inner class relationship. This is because no class other that the class itself should be able to bypass method overriding.So, according to the Java Specification:
Given this, your code should compile.