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!
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With