Question

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.

Was it helpful?

Solution

There is no implicit sub-type relationship: your observation/conclusion is correct. (In the first case, super has the type of "Object" and "Object.fruit" does indeed not exist.)

An inner class (as opposed to "static nested class"), as shown, must be created within context of an instance of the outer class; but this is orthogonal to sub-typing.

To access a member of the outer class, use OuterClass.this.member or, if member is not shadowed, just member will resolve; neither super.member nor this.member will resolve to the outer class member.

Extending the outer class "fixes" the compiler error, but the code with this.fruit doesn't access the member of the enclosing OuterClass instance - it simply accesses the member of the InnerClass instance inherited from the superclass it extends.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top