Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instantiate an interface?

 
Stan Forest
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • 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.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • 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.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • 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
 
sharana sharana
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic