gpt4 book ai didi

java - 协变返回类型是否根据 jls 重写?

转载 作者:行者123 更新时间:2023-12-01 18:32:19 24 4
gpt4 key购买 nike

只是说,我的问题的重点是学会理解jls。我相信jls中的一切都是真的。

考虑 jls 的下一个片段:

8.4.8.1. Overriding (by Instance Methods)

An instance method m1, declared in class C, overrides another instance method m2, declared in class A iff all of the following are true:

C is a subclass of A.

The signature of m1 is a subsignature (§8.4.2) of the signature of m2.

Either:

m2 is public, protected, or declared with default access in the same package as C, or

m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.

Moreover, if m1 is not abstract, then m1 is said to implement any and all declarations of abstract methods that it overrides.

转到签名声明:

The signature of a method m1 is a subsignature of the signature of a method m2 if either:

m2 has the same signature as m1, or

the signature of m1 is the same as the erasure (§4.6) of the signature of m2.

关于相同的签名:

Two methods have the same signature if they have the same name and argument types.

哪条规则允许使用协变返回类型?

最佳答案

这些规则都不允许协变返回类型。方法的签名指的是方法名称及其参数的类型和顺序,但不是返回类型。

From JLS, Section 8.4.8.3 :

If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2, then d1 must be return-type-substitutable (§8.4.5) for d2, or a compile-time error occurs.

This rule allows for covariant return types - refining the return type of a method when overriding it.

指的是Section 8.4.5 ,其中指出:

A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2 iff any of the following is true:

  • 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 one of the following is true:

    • R1, adapted to the type parameters of d2 (§8.4.4), is a subtype of R2.

    • R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9).

    • d1 does not have the same signature as d2 (§8.4.2), and R1 = |R2|.

(强调我的)

我加粗的部分允许协变返回类型。

关于java - 协变返回类型是否根据 jls 重写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23618298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com