66 CHAPTER5. OBJECTSANDGRAPHICS
x:
60
50
p:
y:
Point
Figure5.4:Conceptualpictureoftheresultofp = Point(50,60). Thevariablepreferstoa freshly
createdPointhavingthegivencoordinates.
p.getX()
p.getY()
ThegetXandgetYmethodsreturnthexandyvaluesofa point,respectively. Methodssuchastheseare
sometimescalledaccessors, becausethey allowustoaccessinformationfromtheinstancevariablesofthe
object.
Othermethodschangethevaluesofanobject’s instancevariables,hencechangingthestateoftheobject.
Allofthegraphicalobjectshave amovemethod.Hereis a specification:
move(dx, dy):Movestheobjectdxunitsinthexdirectionanddyunitsintheydirection.
To move thepointptotheright 10 units,wecouldusethisstatement.
p.move(10,0)
Thischangesthexinstancevariableofpbyadding 10 units.If thepointis currentlydrawninaGraphWin,
movewillalsotake careoferasingtheoldimageanddrawingit initsnew position.Methodsthatchangethe
stateofanobjectaresometimescalledmutators.
Themovemethodmustbesuppliedwithtwo simplenumericparametersindicatingthedistancetomove
theobjectalongeachdimension.Somemethodsrequireparametersthatarethemselvescomplex objects.For
example,drawingaCircleintoaGraphWininvolves two objects.Let’s examinea sequenceofcommands
thatdoesthis.
circ = Circle(Point(100,100),30)
win = GraphWin()
circ.draw(win)
ThefirstlinecreatesaCirclewitha centerlocatedat thePoint
100 100 anda radiusof30.Noticethat
weusedthePointconstructortocreatea locationforthefirstparametertotheCircleconstructor. The
secondlinecreatesaGraphWin. Doyouseewhatis happeninginthethirdline?Thisis a requestforthe
Circleobjectcirctodraw itselfintotheGraphWinobjectwin. Thevisibleeffectofthisstatementis
a circleintheGraphWincenteredat
100 100 andhavinga radiusof30.Behindthescenes,a lotmoreis
happening.
Remember, thedrawmethodlivesinsidethecircobject. Usinginformationaboutthecenterand
radiusofthecirclefromtheinstancevariables,thedrawmethodissuesanappropriatesequenceoflow-
level drawingcommands(asequenceofmethodinvocations)totheGraphWin. A conceptualpictureofthe
interactionsamongthePoint,CircleandGraphWinobjectsis showninFigure5.5.Fortunately, we
don’t usuallyhave to worryaboutthesekindsofdetails;they’re alltakencareofbythegraphicalobjects.We
justcreateobjects,calltheappropriatemethods,andletthemdothework.That’s thepowerofobject-oriented
programming.
Thereis onesubtle“gotcha”thatyouneedtokeepinmindwhenusingobjects.It is possiblefortwo
differentvariablestorefertoexactlythesameobject;changesmadetotheobjectthroughonevariablewill
alsobevisibletotheother. Supposewearetryingtowritea sequenceofcodethatdrawsa smiley face.We
wanttocreatetwo eyesthatare 20 unitsapart.Hereis a sequenceofcodeintendedtodraw theeyes.