Originally posted by Abdulla Mamuwala: Hi An interface is [b]100% abstract class. We know that an abstract class cannot be instantiated, therefore the same applies to an interface.[/B] An interface is not the same as an abstract class - they are quite different. However, it is correct that you can not instantiate an interface. If you look at some mock exam questions, though, you might be lead to believe that you can have instances of interfaces. Check out this example:
ActionListener is an interface and it appears that we're instantiating it. However, it's important to realize that we're not actually making a new instance of an interface, we're creating an anonymous object that implements ActionListener and that's certainly legal. I hope that helps. If you have some specific examples that you're still confused about, post them here and I'll try to help. Corey
Originally posted by Serena: Can a interface have a instance? It doesn't compile when I tried in websphere. But I have seen mock questions that has instance of interface and it didn't report compilation error. Why?
maybe u saw something like this
...in this case, u are actually creating an object of HashSet, which is an implementation of Set. (I am new to java but I think I am right)
Serena, Hmmm. I'm not entirely sure what it is you're confused about. You can have a variable with an Interface type, such as Comparable, but you can't have an instance of an interface - that variable would have to reference some object that implements that interface. In your examples, that's exactly what you have. That aspect of it is no different from having a variable with the type of an abstract class. We know that we can't instantiate the abstract class so the only use of the variable would be to reference a subclass of that abstract class. Perhaps if you can point out the line(s) that are giving you trouble, I can be of more help. Corey
Ok, I understand it from your following explanation: You can have a variable with an Interface type, such as Comparable, but you can't have an instance of an interface - that variable would have to reference some object that implements that interface. Thank you very much!