简体   繁体   English

接口如何返回自身的严格实现

[英]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.

相关问题 接口如何包含在其签名或返回类型中引用接口的具体实现类型的方法? - How can an interface include a method that references the concrete implementation type of the interface in its signature or return type? 如果实现不可用,如何实例化接口? - How can I instantiate an interface if implementation is not available? 使用 Kotlin 和 lambda 返回接口实现 - Return interface implementation with Kotlin and lambda java如何知道要返回接口的哪个实现对象? - How does java get to know which implementation object of interface to return? 如何在项目中搜索返回 Collection 接口实现的所有方法? - How to search for all methods in a project that return implementation of Collection interface? java接口方法返回值本身 - java interface method return value is itself 如何自动连接实现接口 - How to Autowire Interface with Implementation 如何确保接口实现扩展特定类? - How can I ensure that an interface implementation extends a particular class? 如何为Fields创建功能接口实现? - How can I create a Functional interface implementation for Fields? 如何使现有的Java类/接口实现单例? - How can I make an existing Java class/interface implementation a singleton?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM