被覆盖的方法可以在返回类型上有所不同吗? [英] Can overridden methods differ in return type?

查看:188
本文介绍了被覆盖的方法可以在返回类型上有所不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重写方法可以不同的返回类型吗?

解决方案

Java支持 * 重写方法的协变返回类型。这意味着重写的方法可能具有更多特定的返回类型。也就是说,只要新的返回类型可以分配给你要覆盖的方法的返回类型,就允许这样做。



例如:

  class ShapeBuilder {
...
public Shape build(){
....
}

类CircleBuilder扩展ShapeBuilder {
...
@Override
public Circle build(){
....
}

这是在 Java语言规范的第8.4.5节


如果返回类型是引用类型,则返回类型可能会因覆盖彼此的方法而异。 return-type-substitutability的概念支持协变返回,即返回类型到子类型的特化。



返回类型为R1的方法声明d1返回-type-可替代另一个返回类型为R2的方法d2,当且仅当以下条件成立时:




  • 如果R1是如果R2是基本类型,则R2与R1相同。


  • 如果R1是引用类型,则:




    • R1是R2的子类型或R1可以是通过未经检查的转换(第5.1.9节)转换为R2的子类型,或


    • R1 = | R2 |




(| R2 |指的是R2的擦除,如 JLS的§4.6中所定义。)






*在Java 5之前,Ja va有不变返回类型,这意味着需要方法覆盖的返回类型才能与被覆盖的方法完全匹配。


Can overridden methods have different return types?

解决方案

Java supports* covariant return types for overridden methods. This means an overridden method may have a more specific return type. That is, as long as the new return type is assignable to the return type of the method you are overriding, it's allowed.

For example:

class ShapeBuilder {
    ...
    public Shape build() {
    ....
}

class CircleBuilder extends ShapeBuilder{
    ...
    @Override
    public Circle build() {
    ....
}

This is specified in section 8.4.5 of the Java Language Specification:

Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns, that is, the specialization of the return type to a subtype.

A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:

  • If R1 is void then R2 is void.

  • If R1 is a primitive type, then R2 is identical to R1.

  • If R1 is a reference type then:

    • R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or

    • R1 = |R2|

("|R2|" refers to the erasure of R2, as defined in §4.6 of the JLS.)


* Prior to Java 5, Java had invariant return types, which meant the return type of a method override needed to exactly match the method being overridden.

这篇关于被覆盖的方法可以在返回类型上有所不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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