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

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

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

Can overridden methods have different return types?

推荐答案

Java 支持覆盖方法的* 协变返回类型.这意味着被覆盖的方法可能具有 更多 特定的返回类型.也就是说,只要新的返回类型可以分配给您要覆盖的方法的返回类型,就可以使用.

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.

例如:

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

这在 中指定Java 语言规范的第 8.4.5 节:

如果返回类型是引用类型,则返回类型可能因相互覆盖的方法而异.返回类型可替换性的概念支持协变返回,即将返回类型特化为一个子类型.

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.

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

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:

  • 如果 R1 为空,则 R2 为空.

  • If R1 is void then R2 is void.

如果 R1 是原始类型,则 R2 与 R1 相同.

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

如果 R1 是引用类型,则:

If R1 is a reference type then:

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

  • 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|"指的是R2的擦除,定义在JLS §4.6.)

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

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

* 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:43:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有所不同   重写   类型   方法

发布评论

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

>www.elefans.com

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