[SalesForce] How to access outer class instance variables from inner class in controller

I have an outer class with an inner class as part of a controller. I have tried setting the instance variables in the outer class as static, which allows the code to compile, but after the controller constructor has executed, subsequent calls to any outer class methods (e.g. from a command button) have nulled out these static instance variables. If I do not set the instance variables in the outer class to static, any references to those variables in the inner class cause a compile error, stating that those variables are not visible:


public class OuterClassStaticExampleController {
   public static String str1;  // remove keyword static and code will not compile
   public OuterClassStaticExampleController() {
      str11 = 'string1';
   }

   public void doneInvokedByCommandButton() {
       String str2 = str1;  // str1 is now null
   }   

   public class InnerClass {
      public String str3;
      public InnerClass() {
         str3 = str1;  // compiles but str1 is null
      }
   }
}

Best Answer

If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance.

The outer class invokes the inner class constructor passing this as that argument.

public class OuterClass {
  String instanceVbl;


  public void myOuterMethod() {
    InnerClass ic = new InnerClass(this);
    ic.someInnerMethod();
  }
  public class InnerClass {
    OuterClass outer;
    public InnerClass (OuterClass outer) {
       this.outer = outer;
    }
    public void someInnerMethod() {
      String s = outer.instanceVbl + 'appendedStringBits';
      // do something more useful
    }

The example is artificial but illustrates how this can be used to give the Inner Class access to anything the Outer Class instance can reference.

Related Topic