Because any ArrayList
is a List
but not all List
s are ArrayList
s, for example LinkedList
.
Is casting the ONLY solution or I should go for another OOP approach?
NO. The best bet is to always code to a high level interface/abstract class:
List<Pelicula> peliculas = YIFY.obtenerPeliculasPorVenir();
More info:
- What does it mean to "program to an interface"?
- Interface vs Base class
- Interface vs Abstract Class (general OO)
When should you use downcasting?
When the framework only provides access to the data as higher level classes. For example, in Java Web Development, retrieving an attribute from the session through HttpSession
//example to validate if user is logged
HttpSession session = request.getSession();
User loggedUser = (User)session.getAttribute("user"); //it returns Object
if (loggedUser == null) {
//there's no user logged in!
//do something about it!
}
//the user is logged, he/she can continue working...