gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:16:45 25 4
gpt4 key购买 nike

我正在用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com