Java Reference
In-Depth Information
the type hierarchy (from the Circle subclass to the Point superclass). It is also an
example of covariance in that a type with a wider range of values ( Circle ) is being
converted to a type with a narrower range of values ( Point ).
After upcasting Circle to Point , you cannot call Circle 's getRadius()
methodbecausethismethodisnotpartof Point 'sinterface.Losingaccesstosubtype
featuresafternarrowingittoasuperclassseemsuseless,butisnecessaryforachieving
subtype polymorphism.
Inadditiontoupcastingthesubclassinstancetoavariableofthesuperclasstype,sub-
type polymorphism involves declaring a method in the superclass and overriding this
methodinthesubclass.Forexample,suppose Point and Circle aretobepartofa
graphics application, and you need to introduce a draw() method into each class to
drawapointandacircle,respectively.Youendwiththeclassstructureshownin Listing
2-33 .
Listing 2-33. Declaring a graphics application's Point and Circle classes
class Point
{
private int x, y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
@Override
public String toString()
{
return "("+x+", "+y+")";
}
 
Search WWH ::




Custom Search