*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Instantiate an interface? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Instantiate an interface?" Watch "Instantiate an interface?" New topic
Author

Instantiate an interface?

Stan Forest
Greenhorn

Joined: Mar 03, 2003
Posts: 12
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

Joined: Aug 03, 2002
Posts: 7729
Nope. What it's doing is instantiating a subclass of Object which happens to implement the Cookable interface. It's an anonymous class instance.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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


SCJP Tipline, etc.
sharana sharana
Greenhorn

Joined: Mar 14, 2003
Posts: 24
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


sharana
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Instantiate an interface?
 
Similar Threads
Anonymous inner class
Is this a subclass of Foo?
Anonymous Inner class
anonymous class
inner class query