Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

In Java, whenever an object is created, it is created as an object of a certain Class. A pointer to this object can then be stored in any variable of either the same Class, or a SuperClass of this class!

Casting is used when you want to go back from storing it as a superclass, to storing it as the same class that created it, or one of its lower superclasses.

A simple example, assuming that Sub is extending Super:

Super super = new Sub();
if (super instanceof Sub)
    Sub sub = (Sub) super;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top