Reputation: 925
I have interface Syncable:
public interface Syncable{
public void sync(Syncable other);
}
And two implemented classes:
public class TstA implements Syncable{
@Override
public void sync(Syncable other) {
// TODO Auto-generated method stub
}
}
public class TstB implements Syncable{
@Override
public void sync(Syncable other) {
// TODO Auto-generated method stub
}
}
So this code is legal:
TstA a = new TstA();
TstB b = new TstB();
a.sync(b);
This is not what I want. I want to allow a.sync receive instances of TstA, and b.sync receive instances of TstB.
Probably I have to use generics, but how?
Upvotes: 0
Views: 177
Reputation: 122449
Analogous to Comparable
, this is how you would do it:
public interface Syncable<T> {
public void sync(T other);
}
public class TstA implements Syncable<TstA> {
@Override
public void sync(TstA other) {
// TODO Auto-generated method stub
}
}
public class TstB implements Syncable<TstB> {
@Override
public void sync(TstB other) {
// TODO Auto-generated method stub
}
}
If there were a generic class or method that required a type parameter T
to be syncable to itself, then that class or method would declare the bound T extends Syncable<? super T>
.
Upvotes: 0
Reputation: 213261
Make your interface generic:
public interface Syncable<T extends Syncable<T>> {
public void sync(T other);
}
And implement a parameterized instance of that interface:
public class TstA implements Syncable<TstA> {
@Override
public void sync(TstA other) {
// TODO Auto-generated method stub
}
}
Upvotes: 2