简体   繁体   中英

Declaring interface method to allow only implemented class

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?

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

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> T extends Syncable<? super T> .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM