-2

Why does the following code not print ????

public class TestInterface {
    interface I {};
    I tester = new I() {{System.out.println("???");}};
    static public void main(String[]args){
        System.out.println("OGOGO");
    }
}

Output:

OGOGO
  • IDE: IntelliJ
  • Jave: jdk-14.0.2
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Dima
  • 1,326
  • 2
  • 13
  • 19
  • Works for me. Can you show your actual code? – markspace Dec 17 '20 at 22:17
  • The question is rather: Why does that print at all? Can someone explain? What method is `{System.out.println("???");}` implementing and why is it called? Is it an initializer block? – akuzminykh Dec 17 '20 at 22:22
  • 1
    It's called an initializer block, and this is not good use of the feature, but it is legal. https://stackoverflow.com/questions/3987428/what-is-an-initialization-block @akuzminykh – markspace Dec 17 '20 at 22:23
  • @markspace Yeah, thanks. I've just got it to mind as you've posted it too. I know the syntax but kinda never have seen someone implementing one for an anonymous class. ^^ – akuzminykh Dec 17 '20 at 22:25
  • 1
    @akuzminykh Anonymous classes like this are used by some folks, it's called double brace initialization. It's not a good idea imo though. https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java – markspace Dec 17 '20 at 22:27
  • Message edited with complete actual code. – Dima Dec 17 '20 at 22:40

2 Answers2

2

It doesn't print because new I() {{System.out.println("???");}}; is never executed. Notice that you have a member variable, a field, no static, there. Fields are initialized together with the corresponding instance of the class, here TestInterface. If you want it to print something, create an instance of TestInterface and its fields will get initialized with what you've specified. Or simply mark it with static so it becomes a class variable and is initialized when the class itself is initialized.

akuzminykh
  • 4,522
  • 4
  • 15
  • 36
  • Well, new creates an instance. No question - an instance of anonymous class is created. Some people wrote it works (prints "???") for them. – Dima Dec 17 '20 at 23:00
  • 1
    We used different code. akuzminykh is correct. `new` is never executed in your code. – markspace Dec 17 '20 at 23:01
0

akuzminykh is right!

When I change to

static I tester

it prints.

Dima
  • 1,326
  • 2
  • 13
  • 19