Search code examples
javagenericsinheritanceinterface

Implement interface with two generics


I've got a task as a part of my homework and I can not get over it. enter image description here

The code of the transformer interface is the following:

public interface Transformer<FROM, TO> {
    TO transform(FROM value);
}

The code of the PersonSubscriberTransformer class looks like this so far:

public class PersonSubscriberTransformer<FROM, TO> implements Transformer {
    private Predicate<Person> predicate;
    public PersonSubscriberTransformer(Predicate<Person> predicate) {
        this.predicate = predicate;
    }
    @Override
    public Object transform(Object value) {
        return null;
    }
  }

The paramether of the transform method should be List<Person> and it should return a List<Subscriber>. As I'm changing the paramether I got an error saying I should pull the method to the Transformer interface.

What would be the solution to implement this method in the correct way?


Solution

  • Based on the intended signature of transform, FROM should be List<Person> and TO should be List<Subscriber>. The class itself should not be generic.

    public class PersonSubscriberTransformer implements Transformer<List<Person>, List<Subscriber>> {
        // constructor...
        
        @Override
        public List<Subscriber> transform(List<Person> persons) {
            // complete this method...
            return null;
        }
    }