Lec26 Notes
-
Upload
mawuena-melomey -
Category
Documents
-
view
214 -
download
0
Transcript of Lec26 Notes
![Page 1: Lec26 Notes](https://reader030.fdocuments.in/reader030/viewer/2022021223/577cdfb51a28ab9e78b1d3cd/html5/thumbnails/1.jpg)
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](https://reader030.fdocuments.in/reader030/viewer/2022021223/577cdfb51a28ab9e78b1d3cd/html5/thumbnails/2.jpg)
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: