• 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 instantiated

 
Ranch Hand
Posts: 204
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
interface ITest{
public void setVal();
}
public class Test {
private String a;
void aMethod(){
final String b = " World";
ITest it = new ITest() {
public void setVal(){
a = "Hello" + b;
}};
it.setVal();
System.out.println(a);
}
public static void main(String[] args) {
Test t = new Test();
t.aMethod();
}
}
prints Hello World.
Please could somone explain .I thought that interface cannot be instantiated and the above code should give compiler error
Thanx in advance
Neha
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Neha :
What is happening here is the Anonymous inner class is implementing the interface ITest providing the implementation for the method setval().
This is a good example of anonymous class.
Later
 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi neha,
it's just same as defining ActionListener or any other listener object inline with your code. It is just that we don't want to name the implementing object. Its inner anonymous class as Harsha pointed out.
regards,
maulin
 
Do not meddle in the affairs of dragons - for you are crunchy and good with ketchup. Crunchy tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic