Randy Smith wrote:Greetings, I would appreciate if someone could explain the purpose of using interface as a type...
I'll leave the "why is it legal" to someone else, because almost always the answer to questions like that is "because the
Java designers thought it was a good idea".
And it is. Here's a real-life example:
I've just written a method that works with 4 different classes (and probably many more), simply because instead of defining its parameter as a class, I defined it as an
interface; and because I did that, it'll work with any class that implements
List (or, in the above case,
List<String>).
And when you define a
field (eg, '
al' above), if you define it using the
interface type, you can
change your mind later. Assuming that all my methods are written to take Lists, rather than ArrayLists, I can change the above definition to:
List<String> al = new AttributeList<String>();
and everything will continue to work just fine.
HIH
Winston