Java Reference
In-Depth Information
System.out.println(ptArray[0].getX()); // Output: 10
System.out.println(ptArray[0].getY()); // Output: 20
//
System.out.println(ptArray[0].getColor()); // Il-
legal
}
}
one element. It then instantiates this class and assigns the object's reference to this
element. Because
ColoredPoint[]
is a subtype of
Point[]
,
main()
is able to
upcast
cptArray
's
ColoredPoint[]
type to
Point[]
and assign its referen-
ce to
ptArray
.
main()
then invokes the
ColoredPoint
instance's
getX()
and
getY()
methodsvia
ptArray[0]
.Itcannotinvoke
getColor()
because
ptAr-
ray
hasnarrowerscopethan
cptArray
.Inotherwords,
getColor()
isnotpartof
Point
's interface.
Abstract Classes and Abstract Methods
Supposenewrequirementsdictatethatyourgraphicsapplicationmustincludea
Rect-
angle
class.Also,thisclassmustincludea
draw()
method,andthismethodmustbe
In contrast to
Circle
, which is a
Point
with a radius, it does not make sense to
thinkofa
Rectangle
asabeinga
Point
withawidthandheight.Rather,a
Rect-
angle
instance would probably be composed of a
Point
indicating its origin and a
Point
indicating its width and height extents.
Because circles,points,andrectangles areexamplesofshapes,itmakesmoresense
todeclarea
Shape
classwithitsown
draw()
methodthantospecify
class Rect-
Listing 2-36.
Declaring a
Shape
class
class Shape
{
void draw()
{
}
}