被覆盖的方法可以在返回类型上有所不同吗?

编程入门 行业动态 更新时间:2024-10-14 10:44:55
本文介绍了被覆盖的方法可以在返回类型上有所不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

解决方案

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.

更多推荐

被覆盖的方法可以在返回类型上有所不同吗?

本文发布于:2023-07-19 08:44:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154831.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:被覆   有所不同   类型   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!