以下接口和类已成功编译。
下面的输出中提到了问题:
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") ;
}
}
output :
X
瞧,MyInterface 是一个接口,
那么为什么编译器允许编译
mi.getClass()、mi.wait()。
或者如何在接口中使用对象类的方法。
Y
Edited:-
我接受否认的答案,因为这是最有解释性的。但读完答案后,又出现了一个问题:-
"请记住,如果接口尝试在 Object 类中声明一个声明为“final”的公共实例方法,那么它将导致编译时错误。例如,“public Final Class getClass()”是在 Object 类中声明为“final”的公共实例方法,因此如果接口尝试声明具有此签名的方法,则编译将失败“(引自解释)。
那么为什么以下代码能够成功编译:-
interface MyInter{
public void method() ;
}
class MyClass implements MyInter{
public final void method() {
.......
.......
.......
}
}
您正确指出的异常是在 Java 语言规范中指定的。接口将自动获取添加的 java.lang.Object 类中的所有成员。从here:
Java语言规范明确规定接口的成员是在接口中声明的成员和从直接超级接口继承的成员。如果接口没有直接超接口,则该接口隐式声明与 Object 类中声明的每个公共实例方法相对应的公共抽象成员方法,除非显式声明具有相同签名、相同返回类型和兼容的 throws 子句的方法那个界面。这使得编译器可以使用对象方法的签名,并且代码编译时不会出现任何错误。请记住,如果接口尝试在 Object 类中声明一个声明为“final”的公共实例方法,那么它将导致编译时错误。例如,“public Final Class getClass()”是在 Object 类中声明为“final”的公共实例方法,因此如果接口尝试声明具有此签名的方法,则编译将失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)