javainner-classesbuilderouter-classes

Accessing outer-class fields through inner-class instance from outer-class


This is a short subquestion of a larger question I am working towards to.

Why can't I access the outer classes field through an instance of inner class in outer class in line 8?

public class OuterClass {

    private static OuterClass instanceOf(InnerClass innerClass) {
        return new OuterClass(innerClass.outerField);
    }

    public static OuterClass instanceOf(int arg) {
        return new OuterClass(arg);
    }

    private int outerField;

    private OuterClass(int arg) {
        this.outerField = arg;
    }

    // Outer class getters...

    public InnerClass build() {
        return new InnerClass(this);
    }

        public class InnerClass {

            private InnerClass(OuterClass outerClass) {
                outerField = outerClass.outerField;
            }

            // Inner class setters......

            public OuterClass build() {
                return OuterClass.instanceOf(this);
            }
        } // End InnerClass

} // End OuterClass

Solution

  • Why can't I access the outer classes field through an instance of inner class in outer class in line 8?

    Because the field is a field of the class OuterClass and not of the class InnerClass. So to access it, you need an instance of the class OuterClass, not of the class InnerClass.

    Sure, inside InnerClass definition, you can implicitly access all the fields of OuterClass. But that's only a matter of access from inside this context. You're not specifying what is the object of which you're trying to access the field, so the language automatically selects that for you. It's usually this.field, but in the case of a field from the containing class, it's actually OuterClass.this.field.

    Once you're trying to indicate what is the object of which you're trying to access a field, rather than let the language implicitly select that object for you, well this object must actually be of the class that contains the field.