Java Reference
In-Depth Information
}
class Subclass extends Superclass
{
@Override
SubReturnType
createReturnType()
{
return new
SubReturnType
();
}
}
class CovarDemo
{
public static void main(String[] args)
{
SuperReturnType
suprt
=
new
Super-
class().createReturnType();
System.out.println(suprt); // Output: superclass re-
turn type
SubReturnType
subrt
=
new
Sub-
class().createReturnType();
System.out.println(subrt); // Output: subclass return
type
}
}
SubReturnType
and
Subclass
subclasses;eachof
Superclass
and
Subclass
declares a
createReturnType()
method.
Superclass
's method has its return
typesetto
SuperReturnType
,whereas
Subclass
'soverridingmethodhasitsre-
turn type set to
SubReturnType
, a subclass of
SuperReturnType
.
Covariant return types minimize upcasting and downcasting. For example,
Sub-
class
's
createReturnType()
method does not need to upcast its
SubReturnType
instancetoits
SubReturnType
returntype.Furthermore,thisin-
stancedoesnotneedtobedowncastto
SubReturnType
whenassigningtovariable
subrt
.
In the absence of covariant return types, you would end up with
Listing 2-41
.
Listing 2-41.
Upcasting and downcasting in the absence of covariant return types