Download - Lec26 Notes

Transcript
Page 1: Lec26 Notes

 

ProgrammingII,FirstSemester2011

Lecture26Notes–MoreaboutInterfaces

Lookatthesolutiontotheclassexercisefromthelastlecture.Inthisexercise,wehada

Drawableinterface(shownbelow),andwecreatedtwoclasses,aRectangleandaTriangle,

thatbothimplementthisinterface.Wehadanappletclass,Picture,thatcreatedanarrayof

Drawables.Initsinit()method,thePictureappletcreatedtwoTriangleobjectsandone

Rectangleobject,andputthemallinthearrayofDrawables.Thepaint()methodofPicture

thensteppedthroughthearraytodrawalltheitems.Seethejavacodeforthesolutionstothe

classexercisefordetailsoftheseclasses.

Intoday’slesson,weextend theDrawableinterfacetocreateanewinterfacecalled

ColoredDrawable.TheColoredDrawableinterfacespecifiesanewmethod,setColor(),that

ismeanttospecifythecolorthattheobjectshouldbedrawnwith.ThesetColormethodtakes

asanargument,anobjectoftypeColor,whichisapredefinedclassinJava.Tousethisclass,

weneedtoimportjava.awt.Color.FormoreinformationontheColorclass,see

http://docs.oracle.com/javase/6/docs/api/java/awt/Color.html

Page 2: Lec26 Notes

 

WechosetousetheColorclassastheargumenttooursetColor()methodinthe

ColoredDrawableinterfacebecausetheGraphicsclass(whichiswhattheappletusesto

paintitself)hasamethodcalledsetColorthatrequiresaColorobjectasanargument.Thus,if

wehaveaColorobject,wecanuseittodrawanitemwithaparticularcolor.

NotethatbecausetheColoredDrawableinterfaceextendstheDrawableinterface,anyclass

thatimplementstheColoredDrawableinterfacemustimplementthedrawWithText()and

drawWithGraphics()methodsoftheDrawableinterface,aswellasthesetColor()methodof

theColoredDrawableinterface.

WecreateaclasscalledColoredRectangle1thatimplementstheColoredDrawableinterface.

Thatis,itprovidesbodiesforthedrawWithText(),drawWithGraphics(),andsetColor()

methods.NotethattheconstructoroftheColoredRectangle1classcallsitssetColormethod

tosetitsdefaultcolortored.Itdoesthisusingthestatement:

setColor(Color.RED)

Color.REDisaconstantdeclaredintheColorclass.BelowisascreenshotfromtheJavaAPI

pagefortheclassColor:

Lastly,wemodifiedthePictureapplettocreateanarraythatholdsaRectangle,a

ColoredRectangle,andaTriangle.Thisistheresultwhentheappletisrun: