Java 什么是协变返回类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1882584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:31:23  来源:igfitidea点击:

What is a covariant return type?

javaoopcovariance

提问by Pops

What is a covariant return type in Java? In object-oriented programming in general?

Java 中的协变返回类型是什么?在面向对象的编程一般?

采纳答案by Andrzej Doyle

Covariant return, means that when one overrides a method, the return type of the overriding method is allowed to be a subtype of the overridden method's return type.

协变返回,意味着当一个方法重写时,重写方法的返回类型允许是被重写方法返回类型的子类型。

To clarify this with an example, a common case is Object.clone()- which is declared to return a type of Object. You could override this in your own class as follows:

为了用一个例子来澄清这一点,一个常见的情况是Object.clone()- 它被声明为返回Object. 您可以在自己的类中覆盖它,如下所示:

public class MyFoo
{

   ...

   // Note covariant return here, method does not just return Object
   public MyFoo clone()
   {
       // Implementation
   }
}

The benefit here is that any method which holds an explicit reference to a MyFoo object will be able to invoke clone()and know (without casting) that the return value is an instance of MyFoo. Without covariant return types, the overridden method in MyFoo would have to be declared to return Object- and so calling code would have to explicitly downcast the result of the method call (even thought both sides "know" it can only ever be an instance of MyFoo).

这里的好处是任何持有对 MyFoo 对象的显式引用的方法都能够调用clone()并知道(无需强制转换)返回值是MyFoo. 如果没有协变返回类型,则必须声明 MyFoo 中的重写方法以返回Object- 因此调用代码必须显式向下转换方法调用的结果(即使双方都“知道”它只能是 MyFoo 的实例) )。

Note that there's nothing special about clone()and that any overridden method can have a covariant return - I used it as an example here as it's a standard method where this is often useful.

请注意,没有什么特别之处,clone()并且任何被覆盖的方法都可以具有协变返回 - 我在此处将其用作示例,因为它是通常有用的标准方法。

回答by PresidentPratik

From the release of JDK 1.5, covariant types were introduced in Java. and I'll explain it to you with a simple case, : When we override a function the function is allowed to make changes to it's behaviourthat's what you get to read in most of the books, but what they { authors } miss out on is that we can change the return type too. check below link for clarification we can change the return type as long as it can be assigned to return type of Base version of the method.

从 JDK 1.5 开始,Java 中引入了协变类型。我会用一个简单的案例向你解释:当我们覆盖一个函数时,该函数被允许改变它的行为,这是你在大多数书中读到的,但他们{作者}错过了什么是我们也可以更改返回类型。检查下面的链接以进行澄清,我们可以更改返回类型,只要它可以分配给方法的 Base 版本的返回类型。

So this feature of returning derived types is called COVARIANT...

所以这个返回派生类型的特性叫做 COVARIANT ...

Can overridden methods differ in return type?

重写的方法可以在返回类型上有所不同吗?

回答by Mohamed ALOUANE

Here is another simple example :

这是另一个简单的例子:

Animalclass

Animal班级

public class Animal {

    protected Food seekFood() {

        return new Food();
    }
}

Dogclass

Dog班级

public class Dog extends Animal {

    @Override
    protected Food seekFood() {

        return new DogFood();
    }
}

It's possible to modify the return type of the Dog's seekFood()method to DogFood- a subclass of Food, as shown below:

可以将DogseekFood()方法的返回类型修改为DogFood- 的子类Food,如下所示:

@Override
protected DogFood seekFood() {

    return new DogFood();
}

That's perfectly a legal overriding, and the return type of Dog's seekFood()method is known as covariant return type.

这是完全合法的覆盖,并且DogseekFood()方法的返回类型称为协变返回类型

回答by Dhiraj

covariant Return types simply means returning own Class reference or its child class reference.

协变返回类型仅意味着返回自己的类引用或其子类引用。

class Parent {
 //it contain data member and data method
}

class Child extends Parent { 
//it contain data member and data method
 //covariant return
  public Parent methodName() {
     return new Parent();
          or 
     return Child();
  }

}

回答by snr

  • The covariant return type in java, allows narrowing down return type of the overridden method.
  • This feature will help to avoid down casting on the client side. It allows programmer to program without the need of type checking and down casting.
  • The covariant return type always works only for non-primitive return types.
  • java 中的协变返回类型允许缩小覆盖方法的返回类型。
  • 此功能将有助于避免在客户端进行向下转换。它允许程序员在不需要类型检查和向下转换的情况下进行编程。
  • 协变返回类型始终仅适用于非原始返回类型。
interface Interviewer {
    default Object submitInterviewStatus() {
        System.out.println("Interviewer:Accept");
        return "Interviewer:Accept";
    }
}
class Manager implements Interviewer {
    @Override
    public String submitInterviewStatus() {
        System.out.println("Manager:Accept");
        return "Manager:Accept";
    }
}
class Project {
    public static void main(String args[]) {
        Interviewer interviewer = new Manager();
        interviewer.submitInterviewStatus();
        Manager mgr = new Manager();
        mgr.submitInterviewStatus();
    }
}

Other example is from Java,

另一个例子来自Java,

UnaryOperator.java

一元运算符.java

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {

    /**
     * Returns a unary operator that always returns its input argument.
     *
     * @param <T> the type of the input and output of the operator
     * @return a unary operator that always returns its input argument
     */
    static <T> UnaryOperator<T> identity() {
        return t -> t;
    }
}

Function.java

函数.java

@FunctionalInterface
public interface Function<T, R> {

    ........
    ........
    ........
    ........

    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

回答by Keshav Gera

Covariant return type specifies that the return type may vary in the same direction as the subclass

协变返回类型指定返回类型可以在与子类相同的方向上变化

class One{  
    One get(){return this;}  
}  

class Two extends One{  
  Two get(){return this;}  

void message(){
  System.out.println("After Java5 welcome to covariant return type");
}  

public static void main(String args[]){  
    new Two().get().message();  
}  
}

Before Java 5, it was not possible override any method by changing the return type. But now, since Java5,

在 Java 5 之前,不可能通过更改返回类型来覆盖任何方法。但是现在,从 Java5 开始,

it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.

如果子类覆盖任何返回类型为非原始类型的方法,但它将其返回类型更改为子类类型,则可以通过更改返回类型来覆盖方法。

回答by Arun Raaj

  • It helps to avoid confusing type casts present in the class hierarchy and thus making the code readable, usable and maintainable.
  • We get a liberty to have more specific return types when overriding
    methods.

  • Help in preventing run-time ClassCastExceptions on returns

  • 它有助于避免类层次结构中存在的混淆类型转换,从而使代码可读、可用和可维护。
  • 在覆盖
    方法时,我们可以自由地拥有更具体的返回类型。

  • 帮助防止返回时出现运行时 ClassCastExceptions

reference: www.geeksforgeeks.org

参考:www.geeksforgeeks.org

回答by Arun Raaj

Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.

在 Java5 之前,无法通过更改返回类型来覆盖任何方法。但是现在,从 Java5 开始,如果子类覆盖任何返回类型为非原始类型的方法,但它将其返回类型更改为子类类型,则可以通过更改返回类型来覆盖方法。

回答by Life Of Pai

To add to the above answers, overriding is possible among co-variant return types, with the constraint that the return type of the overriding method (subclass method) should be a subclass of the return type of the overridden method (superclass method). This is valid from Java 5 onwards.

为了补充上述答案,在协变返回类型之间可以进行覆盖,其约束是覆盖方法(子类方法)的返回类型应该是被覆盖方法(超类方法)的返回类型的子类。这从 Java 5 开始有效。