Viraj
Viraj

Reputation: 5381

Understanding Java anonymous Class?

I have following code that I came across and having hard time to understand it.

Is this using anonymous class + anonymous method ?

public class TestClass {
   protected boolean getValue() {
      return true;
   }
}

public class Main {
   public static void main(String[] args) {
        TestClass testClass = new TestClass() {
            {
                // call TestClass.getValue()
                boolean value = getValue();
            }
        };
    }
}

Upvotes: 1

Views: 68

Answers (1)

ajb
ajb

Reputation: 31689

The block in the anonymous class declaration isn't an "anonymous method"; it's an "instance initializer". See JLS 8.6, which says "An instance initializer declared in a class is executed when an instance of the class is created". So when the code creates the new object testClass, it also executes the initializer, which calls getValue() and stores the result in a local boolean variable. However, this variable is local to the initializer block, and therefore the value will no longer be accessible after the initializer is done executing. So as written, the instance initializer does not do anything useful. (However, if you cut out a lot of code just to keep your code snippet smaller, I can understand that.)

Upvotes: 4

Related Questions