When a nested class in instantiated how does it reference the outer class? Does it always extend the outer class or reference it another way? I was told that the inner extends the outer but then why doesn't the following example work?
For Example:
public class OuterClass {
public String fruit = "apple";
public class InnerClass {
public String fruit = "banana";
public void printFruitName(){
System.out.println(this.fruit);
System.out.println(super.fruit);
}
}
}
The above does not compile with an error for super.fruit
saying that 'fruit' cannot be resolved. However if the inner class is specified to extend the outer class then it works:
public class OuterClass {
public String fruit = "apple";
public class InnerClass extends OuterClass {
public String fruit = "banana";
public void printFruitName(){
System.out.println(this.fruit);
System.out.println(super.fruit);
}
}
}
This seems to show that the inner class does not extend the outer class unless specifically specified.
OuterClass.this
and was playing with it in the code posted in the question here, but when I have the inner class extend the outer class then bothOuterClass.this.fruit
andsuper.fruit
do give me the outer instance'sfruit
value. – Despond