[英]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>
.完全有可能编写一个实现
Animal<Wolf>
的Cat
类。
Try this:尝试这个:
public interface Animal {
String getName();
ArrayList<? extends Animal> getPack();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.