Inheritance with generics and overloading a method

96 Views Asked by At

I have a class with the following method:

public abstract class TypedMessage<T>{

    public TypedMessage<T> setBody(byte[] body) {
        this.body = body;
        return this;
    }

In a subclass of TypedMessage, I want to overload this method. So I do the following:

public class ThriftMessage<T extends TBase> extends TypedMessage<T>{

    public TypedMessage<T> setBody(T body) {
        byte[] data = ThriftMessageUtils.messageBodyToByteArray(body);
        this.body = data;
        return this;
    }

Note the constraint on the T generic. That it must extend TBase. This all compiles fine. Now when I go to use it in a class declared like this:

public abstract class CQSTask<CQSEvent extends TBase>{

    protected void sendCQS(CQSEvent cqsEvent) throws Exception{
        TypedMessage<CQSEvent> message = 
            new ThriftMessage<CQSEvent>(getCQSEventClass())
                .setBody(cqsEvent) //<---Compile error

The setBody() throws a compile error. It is trying to reference the:

public TypedMessage<T> setBody(byte[] body)

version of the method in TypedMessage and not the overloaded version in ThriftMessage.

This is confusing because in my class where I declare the generic param CQSEvent I have the constraint that it extends TBase as well. Can anyone help me understand why its not trying to reference the overloaded version?

Update:

Here is the error message

error: incompatible types: CQSEvent cannot be converted to byte[]
            .setBody(cqsEvent);
                     ^

where CQSEvent is a type-variable: CQSEvent extends TBase declared in class CQSTask

0

There are 0 best solutions below