Multiple inheritance and method overriding problem in java

I asked a similar question in another post ( How to implement a method from a derived class that doesn't require casting ), but this is a little more specific. Suppose I have 3 classes: car, car, convertible. The car expands the car and the convertible expands the car. I need a method for each class that returns a list that doesn't need to be cast at runtime. I believe this is not possible after some thought, but I also want to hear your opinion

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

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

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

      

To avoid using the listing, I would have to return a specific type of item in the list ( List<Convertible>

), but if I wanted to extend the Convertible class, I could no longer do that.

Is there any way around this situation?

+3


source to share


2 answers


If you want to write

List<Vehicle> list1 = new Vehicle().getList();
List<Car> list2 = new Car().getList();
List<Convertible> list3 = new Convertible().getList();

      

you were unlucky. List<Car>

is not a subtype List<Vehicle>

, so the return types are not compatible. You can get rid of the compiler warnings using your code by writing for example



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

      

However, I'm not sure why the method getList()

should be inherited. If you always know the type Vehicle

you are calling on that method, you can also have a separate method in each class called getVehicleList()

, getCarList()

and getConvertibleList()

, returning List<Vehicle>

a List<Car>

and a, List<Convertible>

respectively.

+1


source


You can write



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

public class Car<C extends Car> extends Vehicle<C> {
}

public class Convertible extends Car<Covertible> {
}

      

+5


source







All Articles