0

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?

Andrey
  • 853
  • 9
  • 27
  • possible duplicate of [declare paramter subtype in Java interface, use subtypes in Java implementing methods](http://stackoverflow.com/questions/4820159/declare-paramter-subtype-in-java-interface-use-subtypes-in-java-implementing-me) – Sotirios Delimanolis Mar 29 '14 at 19:54

2 Answers2

2

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      
    }
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

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>.

newacct
  • 119,665
  • 29
  • 163
  • 224