【发布时间】:2009-09-26 14:28:51
【问题描述】:
以下接口和类已成功编译。 下面的输出中提到了问题:
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
瞧,MyInterface 是一个接口,
那么为什么编译器允许编译
mi.getClass(), mi.wait().
或者 Object 类的方法如何在接口中可用。
是的
已编辑:- 我接受了 disown 的回答,因为这是最能说明问题的。但是在阅读了答案之后,又出现了一个问题:-
"请记住,如果接口试图在 Object 类中声明一个声明为 'final' 的公共实例方法,则会导致编译时错误。例如,'public final Class getClass()' 是在 Object 类中声明为“final”的公共实例方法,因此如果接口尝试使用此签名声明方法,则编译将失败”(引自解释)。
那么为什么下面的代码会被成功编译:-
interface MyInter{
public void method() ;
}
class MyClass implements MyInter{
public final void method() {
.......
.......
.......
}
}
【问题讨论】:
-
以上你确定吗?当我尝试这个(在 Eclipse 中)时,我得到一个错误,说变量 mi 可能没有被初始化。
-
另外,引发异常的不是 wait() 调用。这是同步的(mi)。
-
至于您的附加语句 - 当然它可以编译,因为方法
method只是接口中声明的内容的实现。 JLS 声明所说的是在Object类本身上声明的方法。
标签: java