被覆盖的方法可以有不同的返回类型吗?
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.
更多推荐
重写的方法可以在返回类型上有所不同吗?
发布评论