When you declare an object to be of Stack type, when Stack is an interface, the Compiler will only look for the methods in the Stack interface. It will ignore any other methods, and no you can't use them as things stand.
Look at the API documentation for the java.util.List<T> interface. Lists are random-access collections. Then go and find some classes which implement it, the best known being java.util.ArrayList<T> and java.util.LinkedList<T>. Count how many methods they have, and how many are in the List interface.
Then find the java.util.Queue<T> interface and find out how many of its methods there are in the ArrayList and LinkedList classes. I think it's probably none in ArrayList and all in LinkedList.
You can say
Then you are using the methods of List<XYZ> but it is an ArrayList<XYZ> which implements them. You can write this too, and have the same methods implemented by a LinkedList<XYZ>:
In fact I used ctrl-C and ctrl-V to create that last code snippet. Both cases have the same methods and the same functionality, but a different implementation. Look in the
Java Tutorial for collections. Back to ArrayList: there is one method called ensureCapacity or something similar which is in ArrayList and not in List. That is an implementation-specific method, which is very valuable for ArrayLists but would be useless for LinkedLists. It enlarges the collection so you can add many more members very quickly; you can't do that with a LinkedList. Should you wish to use it, it looks like this:
Note the class cast, with a second pair of round brackets () because the . operator has a higher priority than casting. Also this is one place where
instanceof is really useful; you can only cast an ArrayList to an ArrayList.
You can also declare a Queue (first-in-first-out). A useful way to implement a Queue would be with a LinkedList. So, here goes:
See, a completely different set of methods, but the same class implementing it. Now try
LinkedList has it, but it's not in the Queue interface, so the compiler won't recognise it and won't compile the code.
I am afraid I haven't found an easy explanation of "program to the interface" by using Google. Anybody else able to help?
[edit]Disable "smilies"[/edit]
[ January 04, 2008: Message edited by: Campbell Ritchie ]