javainheritancecompiler-errorssubclassingconcreteclass

How to Subclassing with Concrete Parameters


I have a class Transaction and a Service interface

public class Transaction {}

public interface RequestService {
    public String getRequest(Transaction transaction);
}

Now I want to subclass the Transaction class and have a concrete class for the Service Interface

public class ESPTransaction extends Transaction {}

public class ESPRequestService implements RequestService {
    @Override
    public String getRequest(ESPTransaction espTransaction) {
        StringBuffer buff = new StringBuffer(espTransaction.someMethodThatDoesntExistInParentClass());
        return buff.toString();
    }
}

The IDE complains that, even though ESPTransaction subclasses Transaction, that I am not overriding the supertype method.

How can I implement this?


Solution

  • As the IDE notes, ESPRequestService isn't properly implementing RequestService, since it doesn't have a getRequest(Transaction) method.

    One neat solution is to make the interface generic, so each RequestService implementation can specify the type of Transaction it expects:

    public interface RequestService<T extends Transaction> {
        public String getRequest(T transaction);
    }
    
    public class ESPRequestService implements RequestService<ESPTransaction> {
        @Override
        public String getRequest(ESPTransaction espTransaction) {
            StringBuffer buff = new StringBuffer(espTransaction.someMethodThatDoesntExistInParentClass());
            return buff.toString();
        }
    }