Following interface and classes are successfully compiled. Problem is mentioned in the output below :
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
voilla, MyInterface is an interface,
then why compiler allows compilation of
mi.getClass(), mi.wait().
Or how the methods of Object class are available in an interface.
Y
Edited :- I am accepting answer from disown, as it's the most explanatory. But after reading the answer, one more issue get's populated :-
"Remember if the interface tries to declare a public instance method declared 'final' in the Object class then it'll result into a compile-time error. For example, 'public final Class getClass()' is a public instance method declared 'final' in the Object class and therefore if an interface tries to declare a method with this signature then the compilation will fail" (Quoted from explanation).
then why the following code is getting successfully compiled :-
interface MyInter{
public void method() ;
}
class MyClass implements MyInter{
public final void method() {
.......
.......
.......
}
}