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
ShikibuShikibu 

How to access outer instance variable from inner class?

 The following code fails at the first reference to scale in inner class RGB. Is there a right way to do this?
 

public class MyClass {
Integer scale = 1;
class RGB {
Integer red;
Integer green;
Integer blue;
RGB(Integer red, Integer green, Integer blue) {
this.red = red * scale;
this.green = green * scale;
this.blue = blue * scale;
}
}
}

 

 
 
 

Error: Compile Error: Variable does not exist: scale at line 12 column 30

 

 
Message Edited by Shikibu on 04-25-2009 08:21 AM
Michael_KahleMichael_Kahle

Hi Shikibu,

 

it depends what you want to do. There are some ways to do this. You can  set the scale as Parameter in the RGB Constructor too.

public class MyClass { Integer scale = 1; class RGB { Integer red; Integer green; Integer blue; RGB(Integer red, Integer green, Integer blue, Integer scale) { this.red = red * scale; this.green = green * scale; this.blue = blue * scale; } } }

 

 

It requires you to instanciate the RGB Class with the scale too,

Another way would be to make the scale variable static.

 

 

public class MyClass { public static Integer scale = 1; class RGB { Integer red; Integer green; Integer blue; RGB(Integer red, Integer green, Integer blue) { this.red = red * MyClass.scale; this.green = green * MyClass.scale; this.blue = blue * MyClass.scale; } } }

 

 

 

Anyway, you would need to get the scale variable into the RGB class to work with it.