2

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!

0

5 Answers 5

6

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
          }
     }
}
Sign up to request clarification or add additional context in comments.

Comments

4

You have to place the code in a method or in the constructor:

class Outer
{
     int outer = 0;
     class Inner
     {
          int inner = Outer.this.outer; 
          public Inner() {
               inner = 3; 
          }

          public increment() {
               inner++;
          }
      }
}

Comments

3

Your assignment to inner must be inside a method or constructor, not "loose" in the class.

Comments

0

You need to include the line:

 inner=3;

in a method in the inner class.

Comments

0

Yuo can not directly initialize inner = 3; outside method.Make sure that inner = 3; inside any method or constructor.

 public Inner() 
 {
       inner = 3; 
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.