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-
Listing 2-35 ' s main() method first creates a ColoredPoint array consisting of
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
tested in a manner similar to that shown in Listing 2-34 ' s Graphics class.
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-
angle extends Point . Listing 2-36 presents Shape 's declaration.
Listing 2-36. Declaring a Shape class
class Shape
void draw()
Search WWH ::

Custom Search