You need to sign in to do that
Don't have an account?
Shikibu
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 |
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.