Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a warning on this Java generic method definition?

Tags:

People also ask

How are generic methods defined in Java?

The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.

How do you define a generic variable in Java?

A generic type is defined using one or more type variables and has one or more methods that use a type variable as a placeholder for an argument or return type. For example, the type java. util. List<E> is a generic type: a list that holds elements of some type represented by the placeholder E .

What does generic question mark mean Java?

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).


I noticed that if I use generics on a method signature to accomplish something similar to co-variant return types, it works like I think it would, except it generates a warning:

interface Car {
    <T extends Car> T getCar();
}

class MazdaRX8 implements Car {
    public MazdaRX8 getCar() { // "Unchecked overriding" warning
        return this;
    }
}

With the code above, my IDE gives the warning: "Unchecked overriding: return type requires unchecked conversion. Found: 'MazdaRX8', required 'T'"

What does this warning mean?

 

It makes little sense to me, and Google didn't bring up anything useful. Why doesn't this serve as a warning-free replacement for the following interface (which is also warning free, as co-variant return types are allowed by Java)?

interface Car {
    Car getCar();
}