0

Consider the following code:

class Containing {

    public char ch = 'a';

    class MemberClass {
        void printVars() {
            System.out.println(ch);
        }
    }
}

class NonStaticTest {

    public static void main(String[] args) {

        Containing outerObj = new Containing();
        Containing.MemberClass memObj = outerObj.new MemberClass();
       
        memObj.printVars();

        System.out.println("accessing containing class field from non-static member class reference" + memObj.ch);
    }
}

As the member class instance is associated with the containing class instance, can we not access the members of the Containing class through an object of its member class?

I tried to access the "ch" field of the Containing class through the reference to the MemberClass:

System.out.println("accessing containing class field through its non-static member class instance: " + memObj.ch);

But this gives an error:

error: cannot find symbol System.out.println("accessing containing class field from non->static member class reference" + memObj.ch);

symbol: variable ch location: variable memObj of type Containing.MemberClass

But every non-static member class is linked/associated to its containing class instance right. Then why is this an error? Why couldn't it find the symbol, besides having a public access?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • It is likely dup of https://stackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the-inner-class-object (with answer "no") but that's outside of my Java knowledge. – Alexei Levenkov Mar 23 '23 at 21:35

0 Answers0