How to implement a method from a derived class that doesn't need to be applied

Suppose I have 2 Vehicle and Car classes

public class Vehicle {
    public List<? extends Vehicle> getList() {
        return new ArrayList<Vehicle>();
    }
}

@Override
public class Car extends Vehicle {
    public List<? extends Vehicle> getList() {
        return new ArrayList<Car>();
    }
}

      

If I want to get a list from the class that the Vehicle outputs, is there a way I can use getList () without having to cast?

It doesn't work (and I understand why:

List<Car> list = new Car().getList();

      

And it does:

List<Car> list = (List<Car>)new Car().getList();

      

Is there a way to prevent this?

0


source to share


2 answers


Modify the method getList()

in the class Car

to return instead List<Car>

.



@Override
public List<Car> getList() {
    return new ArrayList<Car>();
}

      

+1


source


@Marv is right and you can also change your assignment like below



List<? extends Vehicle> list = new Car().getList();

      

0


source







All Articles