2

I have a third party library class which I cannot change, and this has a protected instance variable which I wont to set to a non-default value on instantiating. This class has no setter nor a constructor that would allow me to set this instance variable.

I tried

// The library class I cannot change:
public class LibraryClass {
    protected boolean instanceVar = false;
}

// My code:
public class MyClass {
    LibraryClass myInstance = new LibraryClass() {
        instanceVar = true;
    };
}

but got the compiler error "<identifier> expected" on the line instanceVar = true;. I also tried to preceed this line by this. and super., but got the same error message.

Of course, I can create a non-anonymous descendant class and set the variable in its constructor. But is there a possibility to initialize the ancestor instance variable directly in an anonymous class?

FrankPl
  • 573
  • 4
  • 19

2 Answers2

1

You need to use an instance initializer block:

LibraryClass myInstance = new LibraryClass() {
    {
        instanceVar = true;
    }
};

Note the additional pair of braces.

Thomas Behr
  • 761
  • 4
  • 10
1

You could use the initialisation block:

public class MyClass {
    LibraryClass myInstance = new LibraryClass() { 
        {
            instanceVar = true;
        }
    };
}
Anatolii
  • 14,139
  • 4
  • 35
  • 65