简体   繁体   中英

Java incompatible types for inherited classes

I'm pretty new to Java, assume these types of questions have been asked before, but after a few hours of search still didn't find the solution for this.

I have an abstract class

public abstract class DBQueryResponse {...}

And two classes inheriting it

public class TransactionKeyResult extends DBQueryResponse {...}
public class SalespersonIdResult extends DBQueryResponse {...}

In another class, I have this function

private DynamoDBQueryExpression<? extends DBQueryResponse> generateQueryExpression() {...}

But whenever I tried to call it somewhere else as such:

DynamoDBQueryExpression<SalespersonIdResult> queryExpression = generateQueryExpression();
DynamoDBQueryExpression<TransactionKeyResult> queryExpression = generateQueryExpression();

It always complains about "Incompatible types", which it expects DBQueryResponse but found else. I always assumed due to polymorphism this is allowed.

The reason I had to use 2 classes is that they are making similar calls to different aws database.

Any advice appreciated. Thanks.

The method should return an exact type rather than wildcard, but the type can be bound:

<T extends DBQueryResponse> DynamoDBQueryExpression<T> generateQueryExpression()

The compiler thinks this is dangerous.Method returns an indeterminate type. Assigning it to a certain type is a sure way to fail compilation.You can continue to use wildcards:

    DynamoDBQueryExpression<? extends DBQueryResponse> queryExpression = generateQueryExpression();
    DynamoDBQueryExpression<? extends DBQueryResponse> queryExpression = generateQueryExpression();

The casting isn't allowed because you're trying to cast from general to specific. Let's say I have two classes B and C that extend a common class A and a method that returns a list of A(or something that extends A).

List<A> foo = method ();

Is valid because no matter if the implementation of method returns B or C, they both extend A. Now for the one more similar to your example.

List<B> baz = method ();

This is not valid because method's return type is A. Even if you know the implementation will return B. As far as the compiler knows it could also return C or any other child of A that can't be cast to B.

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