Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and casting for List Objects

I'm having trouble casting a List of Fruit down to the Fruit subclass contained in the List.

public class Response {
    private List<Fruit> mFruitList;
    public List<Fruit> getFruitList() {
        return mFruitList;
    }
} 

public class Fruit {
}

public class Orange extends Fruit {
}

List<Fruit> oranges = response.getFruitList();

How do I cast oranges so that it is a List of class Orange? Is this a bad design pattern? Basically I am getting a JSON Response from a server that is a List of Fruit. For each specific call to the Web Service, I know what subclass of Fruit I will get and so I need to cast that List appropriately.

like image 770
Will Curran Avatar asked Jun 15 '11 16:06

Will Curran


1 Answers

If you known for each specific call that what subclass of Fruit you will get then you should use generics instead of casting lists.

public class Response<T extends Fruit> {
    private List<T> mFruitList;
    public List<T> getFruitList() {
        return mFruitList;
    }
} 

Response<Orange> response = // create
List<Orange> oranges = response.getFruitList();

EDIT: By templates I meant generic types. Sorry, I had too much C++ nowadays

like image 120
Zoltan Balazs Avatar answered Oct 11 '22 04:10

Zoltan Balazs