The point of an interface is:
- You cannot directly create an instance of the interface, an object, you are correct.
- A class may implement the interface. It declares that it implements the interface and it contains all the methods that the interface contains (unless it’s an abstract class, but then again you can’t create objects from it, so let’s forget this situation for now).
- You may assign a reference to an instance (object) to a variable (or parameter) that is declared to have the interface type.
So to answer your questions:
Iterator itr = myPrecious.iterator();
Is the "itr" not an object?? …
myPrecious.iterator()
returns a real object, and a reference to the object is stored into itr
. The object probably belongs to some class that we haven’t heard of and do not need to care about. All that we know is that that class implements the Iterator
interface. This means that we can use the iterator as specified by that interface.
wasn't it
new Iterator();
to instantiate an object??
Good question. Answer: In the end it is. However, very often in real-world programming we are calling an ordinary method in order to get a new object. That method must in turn use new
. Or call another method that uses new
(etc.). And this is where things go nicely hand in hand: since we don’t know the actual class of the object, we cannot use new
ourselves. But myPrecious
, your collection object, does know the class to use for instantiating an iterator object, so it can use new
for us. And return the created iterator object to us.
One way to check is through this little code experiment:
List<String> myList = new ArrayList<>();
Iterator itr = myList.iterator();
System.out.println(itr.getClass());
On my Java 11 it prints:
class java.util.ArrayList$Itr
Output on other java versions may be different. You notice that the output doesn’t mention the Iterator
interface as the class of the iterator object, but instead some ArrayList$Itr
. This means a class named Itr
declared inside the ArrayList
class. So yes, the iterator is really an object belonging to a class.