0

Please bear with me as I am fresh to Java and have just ran into various collections and the Iterable interface.

I am a little confused here because the Java API defines iterable as an interface with one method: iterator(), which returns an iterator object that corresponds to the collection you reference when invoking the method.

I know that you cannot instantiate an object directly from an interface. So how is it that iterator() can create an object with return type Iterator if Iterator is an interface.

I'm feel like I am overlooking something simple.

Thanks in advance.

EDIT: Let me try to clarify my misunderstanding.

Iterable is an interface that requires you to define Iterator iterator() within whatever data structure class you program. From what I can gauge from the API, the interface Iterable does not extend Iterator.

So my question is not whether or not can you instantiate an interface (as the mark for duplicate question indicates), but rather how does the implementation of Iterable in a data structure force the programmer to implement the methods defined in the Iterator API.

Are you supposed to define a private iterator class embedded within your public data structure class along with a public constructor that will instantiate an object of Iterator?

Sam S.
  • 348
  • 1
  • 3
  • 15
  • 3
    `iterator()` returns an object of a class that *implements* `Iterator`. – nanofarad Jun 15 '16 at 17:56
  • 1
    How do you create an instance of List, which is an interface? new ArrayList(), right? The iterator method does the same thing. It creates an instance of a concrete class, and this class implements Iterator. – JB Nizet Jun 15 '16 at 17:58

0 Answers0