質問

Just say, that point of my question is learn to understand jls. I believe that all in jls are true.

Consider next snippet from 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.

Go to subsignature declaration:

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.

About same signature:

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

Which rule does allow to use covariant return type?

役に立ちましたか?

解決

Neither of these rules allows covariant return types. Signatures of a method refer to the method name and the types and order of its arguments, but not to the return type.

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.

That refers to Section 8.4.5, which states:

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|.

(emphasis mine)

That part I bolded allows covariant return types.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top