There's no actual casting here - just an implicit conversion from Stack<Integer>
to Iterable<Integer>
because Stack<E>
implements Iterable<E>
(implicitly, by extending Vector<E>
, which extends AbstractList<E>
, which extends AbstractCollection<E>
, which implements Collection<E>
, which extends Iterable<E>
).
If it didn't implement the interface, the implicit conversion would be forbidden at compile-time, and an explicit cast would fail at execution time. Java doesn't use duck-typing.