[英]Interface -> anonymous class
為什么下面的代碼不打印???
?
public class TestInterface {
interface I {};
I tester = new I() {{System.out.println("???");}};
static public void main(String[]args){
System.out.println("OGOGO");
}
}
Output:
OGOGO
它不打印,因為new I() {{System.out.println("???");}};
永遠不會被執行。 請注意,您有一個成員變量,一個字段,沒有static
,那里。 字段與 class 的相應實例一起初始化,此處為TestInterface
。 如果您希望它打印某些內容,請創建一個TestInterface
實例,其字段將使用您指定的內容進行初始化。 或者簡單地用static
標記它,使其成為class 變量,並在 class 本身初始化時進行初始化。
阿庫茲米尼赫是對的!
當我更改為
static I tester
它打印。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.