Accessing an Outer Class’s Members from an Inner Class

public class Foo {
    public foo() { }
}
public class Outer {
    public Foo foo {get; set;}
    public class Inner {
        public Inner() {
            system.debug(foo);
        }
    }
    public Inner inner {get; set;}
    public Outer() {
        foo = new Foo();
        inner = new Inner();
    }   
}

That code would result in the following error:

Error: Compile Error: Variable does not exist: foo at line ....

How can my inner class access its outer class’s members?

Thanks!

Answer

One option would be to pass an instance of the Outer class to the Inner class constructor and keep it in a member.

public class Foo {
    public foo() { }
}
public class Outer {
    public Foo foo {get; set;}
    public class Inner {
        private Outer o;
        public Inner(Outer out) {
            o = out;
            system.debug(o.foo);
        }
    }
    public Inner inner {get; set;}
    public Outer() {
        foo = new Foo();
        inner = new Inner(this);
    }   
}

Alternatively, you could make foo static and reference it with Outer.foo.

Attribution
Source : Link , Question Author : Matthew Moisen , Answer Author : Daniel Ballinger

Leave a Comment