Java Basics - Where are the implementations taking place?
For instance, a method returns an object of type List.
public List<Foo> bojangles ()
...
Some piece of code calls the method FooBar.bojangles.iterator();
I'm new to Java, but from what I开发者_JAVA百科 can tell.. List is an interface, so the iterator method has to be implemented somewhere else. When digging for the source code for Java.Util and that's exactly what I found, an iterface. Iterator itself is an iterface...so somewhere, I'm guessing there are classes or abstract classes being called that actually have the logic for these methods: next() and hasNext(). But where?
Take a look at the javadoc for List. It gives a list of known implementing classes. Each of these classes must implement the iterator() method.
If you dig into the source code for those classes, you'll find that they generally implement the Iterator interface in a private nested class.
At first your question confused me, but I think you meant to say FooBar.bojangles().iterator()
. That would make more sense (note the added parentheses).
The method bojangles()
returns an object, that implements List
. For example, it might be an ArrayList
or LinkedList
.
By calling the iterator()
method on either of these lists, you will be returned an Iterator
. This Iterator
was created in the SimpleListIterator
inner class of AbstractList
(that's the actual source code, and in it you will find the implementations you were looking for).
So, by calling the iterator()
method, you are most likely getting a SimpleListIterator
. Although this might not be true in all cases, it will be true in most.
The concrete class does the real job.
In Eclipse, you could run debug mode: run your code step by step and watch 'Variables' view. Then you could find what exactly takes place in runtime.
Or you could print out getClass() of the List to console, then check source.
精彩评论