所以我剛剛在網上發現了這個代碼示例,並且我再次重複它,但很困惑。Java - 接口,實例化一個接口?
從我看來,我收集到的(可能是錯誤的)是它傳遞給NumberPrinter類中的print方法的一個Printer對象。然而,接口也被稱爲打印機,所以我們不是實例化一個打印機接口的匿名類,定義方法然後傳遞它?
我的基本問題是,我最初的假設是否正確?如果是的話,我認爲你不能實例化一個接口?
public class NumberPrinter {
public interface Printer {
public void print (int idx);
}
public static void print (Printer p) {
for (int i = 0; i < 4; i++) {
p.print(i);
}
}
public static void main(String[] args) {
print(new Printer() {
@Override
public void print(int idx) {
System.out.println(idx);
}
});
}
}
這看起來可能是一個重複的問題。嘗試去這裏http://stackoverflow.com/questions/4000062/can-we-create-an-object-of-an-interface – astidham2003 2012-04-18 00:44:59