Java Reference
In-Depth Information
8.4.8.3. Requirements in Overriding and Hiding
If a method declaration d 1 with return type R 1 overrides or hides the declaration of another
method d 2 with return type R 2 , then d 1 must be return-type-substitutable (§ 8.4.5 ) for d 2 , or
a compile-time error occurs.
This rule allows for covariant return types - refining the return type of a method when
overriding it.
If R 1 is not a subtype of R 2 , a compile-time unchecked warning occurs unless suppressed
by the SuppressWarnings annotation (§ 9.6.3.5 ).
A method that overrides or hides another method, including methods that implement abstract
methods defined in interfaces, may not be declared to throw more checked exceptions than
the overridden or hidden method.
In this respect, overriding of methods differs from hiding of fields (§ 8.3 ), for it is per-
missible for a field to hide a field of another type.
More precisely, suppose that B is a class or interface, and A is a superclass or superinterface
of B , and a method declaration n in B overrides or hides a method declaration m in A . Then:
• If n has a throws clause that mentions any checked exception types, then m must
have a throws clause, or a compile-time error occurs.
• For every checked exception type listed in the throws clause of n , that same excep-
tion class or one of its supertypes must occur in the erasure (§ 4.6 ) of the throws
clause of m ; otherwise, a compile-time error occurs.
• If the unerased throws clause of m does not contain a supertype of each exception
type in the throws clause of n , a compile-time unchecked warning occurs.
It is a compile-time error if a type declaration T has a member method m 1 and there exists a
method m 2 declared in T or a supertype of T such that all of the following conditions hold:
m 1 and m 2 have the same name.
m 2 is accessible from T .
• The signature of m 1 is not a subsignature (§ 8.4.2 ) of the signature of m 2 .
• The signature of m 1 or some method m 1 overrides (directly or indirectly) has the
same erasure as the signature of m 2 or some method m 2 overrides (directly or indir-
ectly).
These restrictions are necessary because generics are implemented via erasure.
The rule above implies that methods declared in the same class with the same
Search WWH ::




Custom Search