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

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

问题描述

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

解决方案

Covariant return,意味着当重写一个方法时,重写方法的返回类型可以是被重写方法返回类型的子类型.

>

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

公共类MyFoo{...//注意这里是协变返回,方法不只是返回对象公共 MyFoo 克隆(){//执行}}

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

请注意,clone() 没有什么特别之处,任何被覆盖的方法都可以有一个协变返回 - 我在这里以它为例,因为它是一个标准方法,通常很有用.>

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.

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
   }
}

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

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天全站免登陆