Search code examples
javagenericsfactoryabstract

Java generics Factory Pattern with multiple Generics


I'm trying to learn how to use generics, but I am having a hard time with implementing a factory pattern. I want my DataFactory interface to have a method that returns an object of a class that extends Data. I believe the following code will work, but I'm having a hard time understanding something. Is there a way to avoid having to explicitly specify the second type in the DataFactory interface? Message extends Data<String>, so if T extends Data<U>, shouldn't the U be implied already?

Data class:

public abstract class Data<T> {

    private final long id;
    private final T content;
    private final User sender;
    ...
}

Message class:

public class Message extends Data<String> {
    ...
}

DataFactory Interface:

public interface DataFactory<T extends Data<U>, U> {
    T newInstance(U content, User sender);
}

MessageFactory Class:

public class MessageFactory implements DataFactory<Message, String> {

    @Override
    public Message newInstance(String content, User sender) {
        return new Message(content, sender);
    }
}

Why can't I just write:

public class MessageFactory implements DataFactory<Message>

I'm sorry if this is not a well worded question, I'm not exactly sure how to express it. Originally I didn't want to add type parameters to the class itself, just to the method, but I had more issues trying to make that work. I'm not even sure if I am implementing this correctly. Any help would be appreciated.


Solution

  • Because the type system itself doesn't know that, in the general case, you won't write GenericData<T> extends Data<T>. In this specific case, your Message class has a specific class for the generic type, but you could supply other parameters that wouldn't.