java - 如何在接口(interface)方法中为返回值指定相同类型的类?

标签 java interface

我正在用 Java 创建一个新接口(interface),我想创建一个方法来返回实现该接口(interface)的类的相同类型。

例子:

public interface ModelInterface {
    public (TypeOfClass) getAll();
}

public class Object1 implements ModelInterface {
    public Object1 getAll(){

    }
}

public class Object2 implements ModelInterface {
    public Object2 getAll(){

    }
}

我怎样才能做到这一点?

最佳答案

Java 具有协变返回类型的特性。这意味着子类可以在覆盖/实现方法时指定方法返回类型的子类。就这么简单

public interface ModelInterface {
    public ModelInterface getAll();
}

public class Object1 implements ModelInterface {
    public Object1 getAll(){
        // implement here
    }
}

public class Object2 implements ModelInterface {
    public Object2 getAll(){
        // implement here
    }
}

This tutorial提供协变返回类型的解释。

Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number, which is in turn a subclass of Object.

Now suppose that you have a method declared to return a Number:

public Number returnANumber() {
    ...
}

The returnANumber method can return an ImaginaryNumber but not an Object. ImaginaryNumber is a Number because it's a subclass of Number. However, an Object is not necessarily a Number — it could be a String or another type.

You can override a method and define it to return a subclass of the original method, like this:

public ImaginaryNumber returnANumber() {
    ...
}

This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.

关于java - 如何在接口(interface)方法中为返回值指定相同类型的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110178/

相关文章:

java - 您可以使用 Java 8 编译一个类,然后在 Java 7 中使用它吗?

go - 无效操作 : a > b (operator > not defined on interface)

java - 什么 unicode 字符最适合在字符串中绘制方波

java - 结果集过早关闭

java.lang.ClassNotFoundException : org. json.JSONException

go - 避免Golang界面中的getter的解决方案

c - 这是接口(interface)还是函数原型(prototype)?

java - 如何删除 ArrayList<ArrayList<String>> 的重复项并对数组进行排序

java - 为什么在 Kotlin 类中实现 Cloneable 接口(interface)会导致 "error: no interface expected here"?

c# - 如何编写两个参数都是接口(interface)的重载运算符