什么是协变回报类型? [英] What is a covariant return type?

查看:142
本文介绍了什么是协变回报类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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.

为了用一个例子来澄清这一点,一个常见的例子是 Object.clone( ) - 声明返回对象的类型。你可以在你自己的类中重写这个,如下所示:

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:

public class MyFoo
{

   ...

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

这里的好处是任何持有MyFoo明确引用的方法对象将能够调用 clone()并且知道(没有强制转换)返回值是 MyFoo 的实例。如果没有协变返回类型,MyFoo中的重写方法必须声明为返回 Object - 因此调用代码必须显式转发方法调用的结果(甚至认为双方知道它只能是MyFoo的一个实例。)

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).

请注意, clone()并且任何被覆盖的方法都可以有一个协变返回 - 我在这里用它作为一个例子,因为它是一个标准的方法,这通常是有用的。

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.

这篇关于什么是协变回报类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆