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.
eg
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.
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
}
}
It seems like you want something like...
public interface Merge<T,S> {
public void merge(T host, S other);
}
Check out this page for nice examples of generic interface implementation. This should help of how to implement one.
http://www.java2s.com/Code/Java/Language-Basics/Agenericinterfaceexample.htm
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.