以下接口和類已成功編譯。爲什麼Object類方法在接口中可用?
interface MyInterface{}
class MyClass implements MyInterface{}
class InterDoubt{
static MyInterface mi ;//= new MyClass() ;
public static void main(String[] args){
System.out.println("X") ;
try{
synchronized(mi){
try{
mi.wait(4000) ;
}
catch(InterruptedException ie){
System.out.println("Exception occured at main.") ;
}
}
}
catch(Exception e){
System.out.println("voilla, MyInterface is an interface,\n" +
"then why compiler allows compilation of\n" +
"mi.getClass(), mi.wait().\n" +
"Or how the methods of Object class are available in an interface."
);
}
System.out.println("Y") ;
}
}
輸出: 問題是在下面的輸出提到
X
voilla,MyInterface的是一個接口,
那麼爲什麼編譯器允許的彙編
mi.getClass(),mi.wait()。
或者如何在接口中使用Object類的方法。
Ÿ
編輯: - 我接受來自不認的答案,因爲它是最具解釋。但在閱讀答案後,還有一個問題得到填充: -
「請記住,如果接口嘗試聲明Object類中聲明爲」final「的公共實例方法,則會導致編譯時錯誤。例如,'public final Class getClass()'是在Object類中聲明爲'final'的公共實例方法,因此如果一個接口試圖用這個簽名聲明一個方法,那麼編譯將失敗「(引自解釋)。
那麼爲什麼下面的代碼是越來越成功編譯: -
interface MyInter{
public void method() ;
}
class MyClass implements MyInter{
public final void method() {
.......
.......
.......
}
}
你確定嗎?當我嘗試這個(在Eclipse中)時,我得到一個錯誤,說變量mi可能沒有被初始化。 – CPerkins 2009-09-26 15:46:38
另外,它不是引發異常的wait()調用。它是同步的(mi)。 – CPerkins 2009-09-26 15:49:24
至於你的額外陳述 - 當然它編譯,因爲方法'方法'只是實現界面中聲明的內容。 JLS聲明所談論的是在「Object」類本身上聲明的方法。 – 2012-02-06 17:48:08