Java Reference
In-Depth Information
Listing 2-39 is similar to Listing 2-35 except that it also demonstrates downcasting.
Noticeitsuseof instanceof toverifythat ptArray 'sreferencedobjectisoftype
ColoredPoint[] .Ifthisoperatorreturnstrue,itissafetodowncast ptArray[0]
from Point to ColoredPoint and assign the reference to ColoredPoint .
Sofar,youhaveencounteredtwoformsofRTTI.Javaalsosupportsathirdformthat
isknownasreflection.IwillintroduceyoutothisformofRTTIwhenIcoverreflection
in Chapter 4 .
Covariant Return Types
A covariant return type isamethodreturntypethat,inthesuperclass'smethoddeclara-
tion,isthesupertypeofthereturntypeinthesubclass'soverridingmethoddeclaration.
Listing 2-40 demonstrates this feature.
Listing 2-40. A demonstration of covariant return types
class SuperReturnType
{
@Override
public String toString()
{
return "superclass return type";
}
}
class SubReturnType extends SuperReturnType
{
@Override
public String toString()
{
return "subclass return type";
}
}
class Superclass
{
SuperReturnType createReturnType()
{
return new SuperReturnType();
}
 
Search WWH ::




Custom Search