简体   繁体   English

接口 -> 匿名 class

[英]Interface -> anonymous class

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: Output:

OGOGO
  • IDE: IntelliJ IDE:IntelliJ
  • Jave: jdk-14.0.2贾维:jdk-14.0.2

It doesn't print because new I() {{System.out.println("???");}};它不打印,因为new I() {{System.out.println("???");}}; is never executed.永远不会被执行。 Notice that you have a member variable , a field, no static , there.请注意,您有一个成员变量,一个字段,没有static ,那里。 Fields are initialized together with the corresponding instance of the class, here TestInterface .字段与 class 的相应实例一起初始化,此处为TestInterface If you want it to print something, create an instance of TestInterface and its fields will get initialized with what you've specified.如果您希望它打印某些内容,请创建一个TestInterface实例,其字段将使用您指定的内容进行初始化。 Or simply mark it with static so it becomes a class variable and is initialized when the class itself is initialized.或者简单地用static标记它,使其成为class 变量,并在 class 本身初始化时进行初始化。

akuzminykh is right!阿库兹米尼赫是对的!

When I change to当我更改为

static I tester

it prints.它打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM