Hi gautam,
Though at first site, you may sound to be correct, it is NOT true. Yes, interfaces can not be instantiated directly as below
-
interface MyInterface{}
-
-
class MyClass
-
{
-
public void myMethod()
-
{
-
MyInterface myIntObj = new MyInterface();
-
}
-
}
-
The above codes throws a compiler exception saying that an interface can't be instantiated (more precisely, using a new operator).
-
MyInterface is abstract; cannot be instantiated
-
However, what the code is doing is supplying an anonymous class which is implementing that interface. That is very valid and legal in Java.
FYI, I have added a small line of code (line #13) to test the implementing object is an instance-of Interface or not (using instance-of). I have also made the necessary indentation for an easy read.
-
interface TestA
-
{
-
String toString();
-
}
-
public class Test
-
{
-
public static void main(String[] args)
-
{
-
System.out.println(new TestA() {
-
-
public String toString()
-
{
-
System.out.println("instanceoftest -> "+ (this instanceof TestA));
-
return "test";
-
}
-
});
-
}
-
}
-
The output is as follows
-
instanceoftest -> true
-
test
-
Hope this clarifies and helps.