Tải bản đầy đủ - 0 (trang)
Chapter 6. Methods: A Deeper Look

Chapter 6. Methods: A Deeper Look

Tải bản đầy đủ - 0trang

Chapter6.Methods:ADeeperLook

Thegreatestinventionofthenineteenthcentury

wastheinventionofthemethodofinvention.

AlfredNorthWhitehead

CallmeIshmael.

HermanMelville

Whenyoucallmethat,smile!

OwenWister

Answermeinoneword.

WilliamShakespeare

O!callbackyesterday,bidtimereturn.

WilliamShakespeare

Thereisapointatwhichmethodsdevour

themselves.

FrantzFanon

OBJECTIVES

Inthischapteryouwilllearn:

Howstaticmethodsandfieldsareassociatedwithanentire

classratherthanspecificinstancesoftheclass.



TousecommonMathmethodsavailableintheJavaAPI.

Tounderstandthemechanismsforpassinginformation

betweenmethods.

Howthemethodcall/returnmechanismissupportedbythe

methodcallstackandactivationrecords.

Howpackagesgrouprelatedclasses.

Howtouserandom-numbergenerationtoimplement

game-playingapplications.

Tounderstandhowthevisibilityofdeclarationsislimitedto

specificregionsofprograms.

Whatmethodoverloadingisandhowtocreateoverloaded

methods.



[Page231]

Outline

6.1Introduction

6.2ProgramModulesinJava

6.3staticMethods,staticFieldsandClassMath

6.4DeclaringMethodswithMultipleParameters

6.5NotesonDeclaringandUsingMethods

6.6MethodCallStackandActivationRecords

6.7ArgumentPromotionandCasting



6.8JavaAPIPackages

6.9CaseStudy:Random-NumberGeneration

6.9.1GeneralizedScalingandShiftingofRandom

Numbers

6.9.2Random-NumberRepeatabilityforTestingand

Debugging

6.10CaseStudy:AGameofChance(Introducing

Enumerations)

6.11ScopeofDeclarations

6.12MethodOverloading

6.13(Optional)GUIandGraphicsCaseStudy:ColorsandFilled

Shapes

6.14(Optional)SoftwareEngineeringCaseStudy:Identifying

ClassOperations

6.15Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises



[Page231(continued)]



6.1.Introduction

Mostcomputerprogramsthatsolvereal-worldproblemsare

muchlargerthantheprogramspresentedinthefirstfew

chaptersofthisbook.Experiencehasshownthatthebestway

todevelopandmaintainalargeprogramistoconstructitfrom

small,simplepieces,ormodules.Thistechniqueiscalled

divideandconquer.WeintroducedmethodsinChapter3.In

Chapter6,westudymethodsinmoredepth.Weemphasize

howtodeclareandusemethodstofacilitatethedesign,

implementation,operationandmaintenanceoflargeprograms.

Youwillseethatitispossibleforcertainmethods,calledstatic

methods,tobecalledwithouttheneedforanobjectofthe

classtoexist.Youwilllearnhowtodeclareamethodwithmore

thanoneparameter.YouwillalsolearnhowJavaisabletokeep

trackofwhichmethodiscurrentlyexecuting,howlocal

variablesofmethodsaremaintainedinmemoryandhowa

methodknowswheretoreturnafteritcompletesexecution.

Wewilltakeabriefdiversionintosimulationtechniqueswith

random-numbergenerationanddevelopaversionofthecasino

dicegamecalledcrapsthatwillusemostoftheprogramming

techniquesyouhaveusedtothispointinthebook.Inaddition,

youwilllearntwotechniquesfordeclaringvaluesthatcannot

change(i.e.,constants)inyourprograms.

Manyoftheclassesyouwilluseorcreatewhiledeveloping

applicationswillhavemorethanonemethodofthesamename.

Thistechnique,calledoverloading,isusedbyprogrammersto

implementmethodsthatperformsimilartasksforargumentsof

differenttypesorpossiblyfordifferentnumbersofarguments.







[Page232]



6.2.ProgramModulesinJava

ThreekindsofmodulesexistinJavamethods,classesand

packages.Javaprogramsarewrittenbycombiningnew

methodsandclassesthattheprogrammerwriteswith

predefinedmethodsandclassesavailableintheJava

ApplicationProgrammingInterface(alsoreferredtoasthe

JavaAPIorJavaclasslibrary)andinvariousotherclass

libraries.Relatedclassesaretypicallygroupedintopackagesso

thattheycanbeimportedintoprogramsandreused.Youwill

learnhowtogroupyourownclassesintopackagesinChapter

8.TheJavaAPIprovidesarichcollectionofpredefinedclasses

thatcontainmethodsforperformingcommonmathematical

calculations,stringmanipulations,charactermanipulations,

input/outputoperations,databaseoperations,networking

operations,fileprocessing,errorcheckingandmanyother

usefuloperations.TheJavaAPIclassesarepartoftheJ2SE

DevelopmentKit(JDK)5.0.



GoodProgrammingPractice6.1

Familiarizeyourselfwiththerichcollectionofclassesand

methodsprovidedbytheJavaAPI

(java.sun.com/j2se/5.0/docs/api/index.html).InSection

6.8,wepresentanoverviewofseveralcommon

packages.InAppendixG,weexplainhowtonavigatethe

JavaAPIdocumentation.



SoftwareEngineeringObservation6.1



Don'ttrytoreinventthewheel.Whenpossible,reuse

JavaAPIclassesandmethods.Thisreducesprogram

developmenttimeandavoidsintroducingprogramming

errors.



Methods(calledfunctionsorproceduresinother

programminglanguages)allowtheprogrammertomodularizea

programbyseparatingitstasksintoself-containedunits.You

havedeclaredmethodsineveryprogramyouhavewritten.

Thesemethodsaresometimesreferredtoasprogrammerdeclaredmethods.Theactualstatementsinthemethod

bodiesarewrittenonlyonce,reusedfromperhapsseveral

locationsinaprogramandarehiddenfromothermethods.

Thereareseveralmotivationsformodularizingaprogramby

meansofmethods.Oneisthedivide-and-conquerapproach,

whichmakesprogramdevelopmentmoremanageableby

constructingprogramsfromsmall,simplepieces.Anotheris

softwarereusabilityusingexistingmethodsasbuildingblocks

tocreatenewprograms.Often,youcancreateprogramsmostly

fromstandardizedmethodsratherthanbybuildingcustomized

code.Forexample,inearlierprograms,wedidnothaveto

definehowtoreaddatavaluesfromthekeyboardJavaprovides

thesecapabilitiesinclassScanner.Athirdmotivationistoavoid

repeatingcode.Dividingaprogramintomeaningfulmethods

makestheprogrameasiertodebugandmaintain.



SoftwareEngineeringObservation6.2

Topromotesoftwarereusability,everymethodshouldbe

limitedtoperformingasingle,well-definedtask,andthe

nameofthemethodshouldexpressthattaskeffectively.

Suchmethodsmakeprogramseasiertowrite,debug,

maintainandmodify.



Error-PreventionTip6.1

Asmallmethodthatperformsonetaskiseasiertotest

anddebugthanalargermethodthatperformsmany

tasks.



[Page233]

SoftwareEngineeringObservation6.3

Ifyoucannotchooseaconcisenamethatexpressesa

method'stask,yourmethodmightbeattemptingto

performtoomanydiversetasks.Itisusuallybestto

breaksuchamethodintoseveralsmallermethod

declarations.



Asyouknow,amethodisinvokedbyamethodcall,andwhen

thecalledmethodcompletesitstask,iteitherreturnsaresult

orsimplycontroltothecaller.Ananalogytothisprogram

structureisthehierarchicalformofmanagement(Figure6.1).

Aboss(thecaller)asksaworker(thecalledmethod)to

performataskandreportback(i.e.,return)theresultsafter

completingthetask.Thebossmethoddoesnotknowhowthe

workermethodperformsitsdesignatedtasks.Theworkermay

alsocallotherworkermethods,unbeknownsttotheboss.This

"hiding"ofimplementationdetailspromotesgoodsoftware



engineering.Figure6.1showsthebossmethodcommunicating

withseveralworkermethodsinahierarchicalmanner.Theboss

methoddividestheresponsibilitiesamongthevariousworker

methods.Notethatworker1actsasa"bossmethod"toworker4

andworker5.



Figure6.1.Hierarchicalboss-method/workermethodrelationship.



[Viewfullsizeimage]







[Page233(continued)]



6.3.staticMethods,staticFieldsandClass

Math

Asyouknow,everyclassprovidesmethodsthatperform

commontasksonobjectsoftheclass.Forexample,toinput

datafromthekeyboard,youhavecalledmethodsonaScanner

objectthatwasinitializedinitsconstructortoobtaininputfrom

thestandardinputstream(System.in).Asyouwilllearnin

Chapter14,FilesandStreams,youcaninitializeaScannerto

obtaininputfromothersources,suchasafileondisk.One

programcouldhaveaScannerobjectthatinputsinformation

fromthestandardinputstreamandasecondScannerthatinputs

informationfromafile.Eachinputmethodcalledonthe

standardinputstreamScannerwouldobtaininputfromthe

keyboard,andeachinputmethodcalledonthefileScannerwould

obtaininputfromthespecifiedfileondisk.

Althoughmostmethodsexecuteinresponsetomethodcallson

specificobjects,thisisnotalwaysthecase.Sometimesa

methodperformsataskthatdoesnotdependonthecontents

ofanyobject.Suchamethodappliestotheclassinwhichitis

declaredasawholeandisknownasastaticmethodoraclass

method.Itisnotuncommonforaclasstocontainagroupof

convenientstaticmethodstoperformcommontasks.For

example,recallthatweusedstaticmethodpowofclassMathto

raiseavaluetoapowerinFig.5.6.



[Page234]

Todeclareamethodasstatic,placethekeywordstaticbefore

thereturntypeinthemethod'sdeclaration.Youcancallany

staticmethodbyspecifyingthenameoftheclassinwhichthe

methodisdeclared,followedbyadot(.)andthemethod

name,asin



ClassName.methodName(arguments)

WeusevariousMathclassmethodsheretopresenttheconcept

ofstaticmethods.ClassMathprovidesacollectionofmethods

thatenableyoutoperformcommonmathematicalcalculations.

Forexample,youcancalculatethesquarerootof900.0withthe

staticmethodcall

Math.sqrt(900.0)



Theprecedingexpressionevaluatesto30.0.Methodsqrttakes

anargumentoftypedoubleandreturnsaresultoftypedouble.To

outputthevalueoftheprecedingmethodcallinthecommand

window,youmightwritethestatement

System.out.println(Math.sqrt(900.0));



Inthisstatement,thevaluethatsqrtreturnsbecomesthe

argumenttomethodprintln.Notethattherewasnoneedto

createaMathobjectbeforecallingmethodsqrt.Alsonotethatall

Mathclassmethodsarestatictherefore,eachiscalledby

precedingthenameofthemethodwiththeclassnameMathand

adot(.)separator.



SoftwareEngineeringObservation6.4

ClassMathispartofthejava.langpackage,whichis

implicitlyimportedbythecompiler,soitisnotnecessary

toimportclassMathtouseitsmethods.



Methodargumentsmaybeconstants,variablesorexpressions.

Ifc=13.0,d=3.0andf=4.0,thenthestatement

System.out.println(Math.sqrt(c+d*f));



calculatesandprintsthesquarerootof13.0+3.0*4.0=

25.0namely,5.0.Figure6.2summarizesseveralMathclass

methods.Inthefigure,xandyareoftypedouble.

Figure6.2.Mathclassmethods.

(Thisitemisdisplayedonpage235intheprintversion)

Method



Description



Example



abs(x)



absolutevalueofx



abs(23.7)is23.7

abs(0.0)is0.0

abs(-23.7)is23.7



ceil(x)



roundsxtothesmallestintegernot

lessthanx



ceil(9.2)is10.0

ceil(-9.8)is-9.0



cos(x)



trigonometriccosineofx(xin

radians)



cos(0.0)is1.0



exp(x)



exponentialmethodex



exp(1.0)is2.71828

exp(2.0)is7.38906



floor(x)



roundsxtothelargestintegernot

greaterthanx



floor(9.2)is9.0

floor(-9.8)is-10.0



log(x)



naturallogarithmofx(basee)



log(Math.E)is1.0

log(Math.E*Math.E)is

2.0



max(x,y)



largervalueofxandy



max(2.3,12.7)is12.7

max(-2.3,-12.7)is-2.3



min(x,y)



smallervalueofxandy



min(2.3,12.7)is2.3



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 6. Methods: A Deeper Look

Tải bản đầy đủ ngay(0 tr)

×