• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Interface accepting instance

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic