0

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?

  • The field is visible from inner class.
  • The problem persists for non-static methods in outer class.
  • The visibility of the field does not matter. Its visible from inner class either way.
  • The field could be accessed through a (private) getter in inner class, but one of the reasons for my problem is, that i would like to avoid those.
  • It's supposed to become a variation of the immutable builder pattern, so outer and inner class are developed in close coherence. That's the only reason I would dare to access the fields directly w/o getters.
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
Malte
  • 75
  • 7

1 Answers1

0

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.

kumesana
  • 2,495
  • 1
  • 9
  • 10
  • Thanks for the quick answer. I guess that answers my question, but is there an easy and elegant workaround I am not seeing which prevents me from implementing a copy of outerField in InnerClass, to be able to create instances of each class with an instance of the respective other class without loosing the information of the field? – Malte Jun 15 '18 at 11:53