Issue
In the example code below I'm trying to return but at the very least I get a warning. The other scenarios (2 and 3) result in an error. Is there a correct way to return that does not result in a warning?
static class Cars<C extends Car> {
private C c;
Cars(C c) {
this.c = c;
}
}
static class Car { }
static <C extends Car> Cars<C> cars() {
// 1. WARNING: 'Raw use of parameterized class 'Cars''
// return new Cars(new Car());
// 2. ERROR: 'Cannot infer arguments'
// return new Cars<>(new Car());
// 3. ERROR: 'Required C provided Car'
// return new Cars<C>(new Car());
}
Solution
I think you are misusing, or at least misunderstanding, generics here. It is very important to understand that generic parameters are decided by the caller not the callee.
From the implementation of your cars
method, you seem to want to return a Cars<Car>
object, but your method signature says otherwise. Your method signature says
this method can return a
Cars<C>
whereC
isCar
or any subclass ofCar
, and you, the caller, gets to decide whatC
is.
Your method doesn't do that, does it? If I wrote a subclass of Car
called Lorry
, can your method give me a Cars<Lorry>
? Nope.
(And before you say it, no, a Cars<Lorry>
is not "a kind of" Cars<Car>
. See here if you don't understand why.)
So you need to change the signature to a more "humble" one :) (without the generic parameter)
static Cars<Car> cars()
And use this line as the return statement:
return new Cars<>(new Car());
Answered By - Sweeper
Answer Checked By - Candace Johnson (JavaFixing Volunteer)