Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify variable in Inner class Java

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!

like image 232
Luigi Tiburzi Avatar asked Jun 09 '26 14:06

Luigi Tiburzi


1 Answers

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
          }
     }
}
like image 180
Ted Hopp Avatar answered Jun 11 '26 03:06

Ted Hopp