Search code examples
javagenericsinterfacedelegation

How to create generic interface methods?


is it possible to create a generic method in interfaces?

say I want to create an interface

public interface Merge {
    public void merge(Object host, Object other);
}

then I want the implementing class to implement this, but define the type of host and other.

e.g.

public class FooBazMerge implements Merge {
    public void merge(Foo host, Baz other){
        // merge some properties
    }
}

the reason why I want to do this is so that I can do something like this

public class SomeObject {
    private Merge merge;
    private Foo foo;
    private Baz baz;        

    public setMerge(Merge merge){
        this.merge = merge
    }

    public void merge(SomeObject anotherObject){
        merge.merge(this.foo, anotherObject.getBaz()); 
    }
}

I basically want to delegate the merging responsibility/logic of someObject to FooBazMerge. that way I can change the implementation of how it's merged without having to muck with the domain models every time an adjustment needs to be made.


Solution

  • public interface Merge<A,B> {
        public void merge(A host, B other);
    }
    

    is this what you are looking for? This is valid syntax. Your implementing class would look like:

    public class FooBazMerge implements Merge<Foo, Baz> {
        public void merge(Foo host, Baz other){
            // merge some properties
        }
    }