• 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
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Instantiate an interface?

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can an interface can be instantiated in an anonymous class? Does this code have an instance of an interface?
// From Kathy Sierra's book page 471
interface Cookable {
public void cook();
}
class Food {
Cookable c = new Cookable(){ // instantiates an interface
public void cook() {
System.out.println("Anonymous cookable implementer");
}
};
}
public class Test {
public static void main(String arg[]){
Food f = new Food();
f.c.cook();
}
}
I bring the question up because of Marcus Green's Mock Exam 2 Question 57.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nope. What it's doing is instantiating a subclass of Object which happens to implement the Cookable interface. It's an anonymous class instance.
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This code doesn't really instantiate an interface. What it does is creates an object that implements the interface. Because the object implements that interface, it must provide implementations for all methods defined within that interface - in this case, the cook() method.
I hope that helps,
Corey
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cookable c = new Cookable(){ // instantiates an interface
public void cook() {
System.out.println("Anonymous cookable implementer");
}
};
this code does create an anonymous class which implements the interface cookable. and stores the reference of the same in to interfaces reference variable C [ perfectly valid widening reference conversion ]
hope that would helps
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic