Modify variable in Inner class Java
inner-classes, java, variables
Solution
You cannot have a statement outside a method. One technique would be to use an instance initializer block:
class Outer
{
int outer = 0;
class Inner
{
int inner = Outer.this.outer; //(or just outer as it is not shadowed)
// instance initializer block:
{
inner = 3; //or whatever, even outer = 3
}
}
}
Alternatively, define a constructor:
class Outer
{
int outer = 0;
class Inner
{
int inner = Outer.this.outer; //(or just outer as it is not shadowed)
Inner() {
inner = 3; //or whatever, even outer = 3
}
}
}
Problem
I have a problem with Java inner classes which I can't figure out. Suppose you have ``` class Outer { int outer = 0; class Inner { int inner = Outer.this.outer; //(or just outer as it is not shadowed) inner = 3; //or whatever, even outer = 3 } } ``` Well, when I write the last assignment I get the compilation error ``` Syntax error on token ";", , expected ``` on the precedent line. Why I cannot modify inner? Thank you!