sf8193
sf8193

Reputation: 635

Using generics in Java, can someone please explain what I'm doing wrong

I have a class like so

public interface Handler<T> {

    /**
     * @param request
     * @return
     * @throws ServiceErrorResponse
     */

    public Credit handle(T request) throws ServiceErrorResponse;

    public Data handle() throws ServiceErrorResponse;
}

And it is implemented by this

public class DataHandlerImpl implements Handler {

    public Credit handle(T request) {
        return new Policy();
    }

    public Data handle() {
        return new Data();
    }
}

However, this throws an error because it cannot resolve the symbol T. I have tried multiple things like doing this as the signature but it also doesn't work

public class DataHandlerImpl implements Handler<T> {

I have also tried

public class DataHandlerImpl implements Handler {

    public Policy handle(String request) {
        return new Policy();
    }

    public Data handle() {
        return new Data();
    }
}

which doesn't work because I must implement handle(T)

but seem to have a fundamental misunderstanding of generics. Can someone please explain?

I want this "handle" method to be able to accept strings or integers.

Upvotes: 0

Views: 50

Answers (2)

Thomas
Thomas

Reputation: 5094

You can't really have the same method take both strings and ints, assuming that the implantation of the method will be different to handle different types. For generics, when you write your implementing class you need to specify which argument it will take. Your compiler should actually be giving you a warning for having implements without a type.

public class DataHandlerStringImpl implements Handler<String> 
public class DataHandlerIntegermpl implements Handler<Integer> 

The non-generics way to do this would be overloaded methods, which are simpler but less extensible/powerful. The compiler will know which implemention to use based on the type passed in.

public Credit handle(String request) 
public Credit handle(int request) 

Upvotes: 2

boot-and-bonnet
boot-and-bonnet

Reputation: 761

You need to decide what type you want handle(...) to take and apply that as the Handler<T> type. For String example:

    public static class DataHandlerImpl implements Handler<String> {
        @Override
        public Credit handle(String request) {
            return new CreditPolicy();
        }

        @Override
        public Data handle() {
            return new CreditPoliciesData();
        }
    }

Upvotes: 0

Related Questions