Reputation: 19
So it's only been few days that I touched on collection classes and stumbled upon a thing called "Iterator". And after few prying and poking I again stumbled upon docs.oracle.org and there I learned that Iterator is actually an interface and still we create it's object.
Iterator itr = myPrecious.iterator();
Is the "itr" not an object?? or am I missing something?? Wasn't it impossible to make object of an interface??
and what is that special thing
myPrecious.iterator();
??
wasn't it
new Iterator();
to instantiate an object??
Edit : forgot to mention Javas is kinda my first programming language so forgive my stupidity.
Upvotes: 0
Views: 1032
Reputation: 86276
The point of an interface is:
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.
Upvotes: 0
Reputation: 79085
Is the "itr" not an object??
It's a reference.
Wasn't it impossible to make object of an interface??
You can not instantiate an interface. Here, a parent type (Iterator
) reference is referencing an object of child type.
and what is that special thing
myPrecious.iterator();
??
Here iterator
is a function in the class whose object is myPrecious
. Check the definition of the function, iterator
here for an example.
wasn't it
new Iterator();
to instantiate an object??
You can instantiate a non-abstract class using the keyword, new
. You can instantiate an anonymous class by using new
on the interface name as shown here for an example.
Upvotes: 2