Casting Stack to Iterable

In the following code, the method returns a Stack object which gets casted to an Iterable.

public Iterable<Integer> getRoute(int x) {
    Stack<Integer> stack = new Stack<Integer>();
    ...
    stack.push(x);
    return stack;
}

Iterable is an interface and not a class. Could you please let me know, how does casting work here for this case?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow