简体   繁体   中英

Incompatible types when using static method generics

When I try to compile the following code, compilation fails with the following error. I'm not sure why it should as I am only returning a class that implements the contract

public interface Contract {
  static <T extends Contract> T get() {
    return new ConcreteContract();
  }
}

class ConcreteContract implements Contract {
}

Contract.java:3: error: incompatible types: ConcreteContract cannot be converted to T
    return new ConcreteContract();
           ^
  where T is a type-variable:
    T extends Contract declared in method <T>get()
1 error

Does anyone have a clue why java behaves this way (or) am I missing something obvious

PS: I have read more than 10 top searches in SO before posting this query

Since your method returns a generic type T , and T can be any class that implements Contract , it can be called (for example) with:

OtherConcreteContract variable = Contract.get();

and you can't assign a ConcreteContract to a OtherConcreteContract variable (assuming ConcreteContract is not a sub-class of OtherConcreteContract ).

To avoid that error, you should either return the interface type:

static Contract get() {
    return new ConcreteContract();
}

or the concrete type:

static ConcreteContract get() {
    return new ConcreteContract();
}

The former (returning the interface type) is usually the better choice.

Generics don't help you here.

You need to typecast the final return type into the type T.

With you are specifying the if T must be either Contract or subclass of it. Means you are bounding the type which will be used as generic.

At the time of return, you should be strict to the generic type which is defined at the time of using that's why the compiler is complaining you to return the type T instead of What you are trying to return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM