0

In the example below the Car<M> is defined with generic <M> and it implements interface Vehicle which does not have generic in its definition. When casting the object back to Car<M> after assigning it to Vehicle,

Car<CarModel> car = (Car) carVehicle;

it shows see this warning (s):

Unchecked assignment: 'com.test.Car' to 'com.test.Car<com.test.CarModel>'

Is there a way to avoid this warning?

public class Main {

  public static void main(String[] args) {
    Main main = new Main();

    Vehicle carVehicle = new Car<>(new CarModel("XM"), 100);
    Car<CarModel> car = (Car) carVehicle;  // Unchecked assignment: 'com.test.Car' to 'com.test.Car<com.test.CarModel>'
  }
}

interface Vehicle {
  long getVehicleIdNum();
}

class CarModel {
  String model;

  CarModel(String model) {
    this.model = model;
  }
}

class Car<M> implements Vehicle {
  M model;
  long vin;

  Car(M model, long vin) {
    this.model = model;
    this.vin = vin;
  }

  @Override
  public long getVehicleIdNum() {
    return vin;
  }

  M getModel() {
    return model;
  }
}
user31986
  • 1,558
  • 1
  • 14
  • 29
  • 5
    You can't get rid of the unchecked cast warning, because it *is* an unchecked cast. I mean, other than not assigning it to a `Vehicle` variable in the first place; or making the variable `Car>`. But you shouldn't use raw types: the cast should be `(Car)` – Andy Turner Aug 26 '18 at 20:04
  • @AndyTurner thanks. I think this is a perfectly valid requirement. Suppose the `Vehicle` interface comes from a library that one cannot change, but wants to use it this way. In that case, not being able to assign it back to the subclass (without this warning) seems like a severe limitation.. – user31986 Aug 26 '18 at 20:08
  • Even if one can modify `Vehicle` is there a way to design it in a way that avoids the warning? I am sure, someone must have already stumbled across this. :) – user31986 Aug 26 '18 at 20:11
  • 1
    There is no way to avoid the unchecked cast warning because, well, you're doing a cast which isn't checked at runtime. You can perhaps do something to ensure that the type is correct, e.g. declaring a redundant variable `{ CarModel cm = car.getModel(); }`. This will actually do a checked cast, so thereafter you can be sure that the unchecked cast was correct. This is simply a limitation of type erasure. – Andy Turner Aug 26 '18 at 20:23

0 Answers0