• Post Reply Bookmark Topic Watch Topic
  • New Topic

Interface accepting instance  RSS feed

 
Mohan Vinukonda
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the following code, interface is accepting creating new instance compiler is not giving any warning or error. Can anybody explain how it works. Any body help appreciated.

interface TestA { String toString(); }
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString() { return "test"; }
});
}
}

-Mohan
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are not instantiating the interface. You have implemented the single method it has, which is by the way implemented in java.lang.Object anyway.
So what you are instantiating is an anonymous inner class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!