function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Bo LaurentBo Laurent 

Access to outer class instance variable from inner class constructor

Can an inner class access an instance variable of its outer class?



I have a bit of code which, simplified, looks like this. In context, it produces the error " Method does not exist or incorrect signature" on line 8, but for some reason this simplified version produces the error "User-defined type not allowed here" on line 4.


The apex manual says "Inner classes can have instance member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this

keyword)." (link)





1: public class MyClass {
2: public Map<String,Statistical_Datum__c> dataMap;
4: public class Datum {
5: Statistical_Datum__c datumObject;
7: public Datum( String statistic ) {
8: datumObject = dataMap.get( statistic );
9: }
10: }
11: }





Did you find a solution to this - I have been looking.  For now I have created an instance variable in the inner class (of the same type as the outer class) and populate it by passing in a reference to 'this' when constructing.  Then you can access the outer variables.


Be nice if there was a keyword for this?


Hi Pault,


Sorry, I did not find a solution. Your solution sounds appropriate.


I tried using Global and Public access modifiers but it seems you  can not acheive it directly. One way can be to pass variable as constructor argument while creating inner class object


Yes, as vinaysharma_jpr suggested, the right solution to this is to pass an instance variable of the outer class to the constructor.


Here is an example:


public class OuterClass {
    Integer selectedOppIndex;
    WrappedOpp[] oppList = new List<WrappedOpp>();
    public class WrappedOpp {
        OuterClass oc; // instance of containing class
        Opportunity theOpp;
        Integer myIndex;
        Boolean isSelected {
            get { return myIndex == oc.selectedOppIndex; }
            set { oc.selectedOppIndex = myIndex; }
        public WrappedOpp(OuterClass oc, Opportunity o; Integer myIndex) {
            this.oc = oc;
            this.theOpp = o;
            this.myIndex = myIndex;



This can be used to display a list of opportunities on a VisualForce page, and have a checkbox in each row act like a radio button to select zero or one opportunities.


In the OP case, wouldn't it be easier to just pass dataMap to the inner class constructor instead of the entire outer class?