简体   繁体   中英

How an interface can return a strict implementation of itself

Let's say that we have the following interface

public interface Animal {

    String getName();

    ArrayList<Animal> getPack();

}

And the following implementation of it

public class Wolf implements Animal {

    @Override
    public String getName() {
        return "wolf 1";
    }

    @Override
    public ArrayList<Animal> getPack() {
        return new ArrayList<>();
    }
}

Is there any way to have the following instead?

 @Override
 public ArrayList<Wolf> getPack() {
     return new ArrayList<>();
 }

You can "kind of" do this with a generic interface:

public interface Animal<T extends Animal<T>> {

    String getName();

    ArrayList<T> getPack();

}

public class Wolf implements Animal<Wolf> {
    @Override
    public String getName() {
        return null;
    }

    @Override
    public ArrayList<Wolf> getPack() {
        return null;
    }
}

But the drawback of this is obviously that the responsibility of following rules is passed to the implementers. It is entirely possible to write a Cat class that implements Animal<Wolf> .

Try this:

public interface Animal {

    String getName();

    ArrayList<? extends Animal> getPack();

}

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