资源描述:
《chapter 5 defining methods》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Chapter5DefiningMethodsIntheprecedingchapters,weputJavatoworkinsolvinginterestingproblems.Thedemoprogramsgrewtoahealthysize,however.TheCountWords2.javaprogram,asanexample,tookabout40linesofcodeandhadsixlevelsofindentationatthedeepestspot.Copingwiththisincreaseincom
2、plexityisthetopicofthischapter.We'lllearnhowtodefinecustommethodstosubdividecomplexprogrammingtasksintosmallertasksthatareeasytounderstandandeasytomanage.Amethodisafunction.Theterm"function"hasaheritageincomputersciencedatingbackseveraldecades;howeverthetermisnotus
3、edinJava.IfyouhaveprogrammingexperiencewithalanguagelikeCorPascal,andyouarejustlearningJava,youmaybemorecomfortablewiththeterm"function".Ifyouthink"function"whenyouread"method",itmayhelpeaseyouintotheworldofJava.Makeitapersonalgoal,however,toweanyourselfoftheterm"f
4、unction".Onceyoubegintothinkintermsofmethodsconstructors,classmethods,andinstancemethodsyouarewellunderwaytobecomingaJavaprogrammer.Allthemethodspresentedinthischapterareexamplesofclassmethods,asopposedtoinstancemethods.Thedistinctionbetweenthetwowaselaboratedinthe
5、precedingchapter,butwillre-surfaceinthischapteraswell.WewilllearntodefinedinstancemethodsinChapterxwhenwelearntodefineclasses.WhyMethods?Anyprogrammingproblemthatcanbesolvedusingmethods,canbesolvedwithoutmethods.So,what'sthebigdeal?Aremethodsjustanotherofthosetools
6、,likethebreakstatementortheselectionoperator,thatexistforourconveniencebutaren'treallynecessary?Notatall.MethodsareanessentialJavaprogrammingtool.Itwouldnotbepossibletosolve"large"programmingproblemswithoutmethods.Thetaskwouldgrowincomplexityuntilitwasimpossiblefor
7、ameremortaltounderstandhowallthepartsworkedtogether.JavaPrimer5-1ÓScottMacKenzieThereareatleastthreereasonswhyweusemethods:(i)toallowustocopewithcomplexproblems,(ii)tohidelow-leveldetailsthatotherwiseobscureandconfuse,and(iii)toreuseportionsofcode.Let'sexamineeacho
8、fthesepointsinturn.ComplexityAprogramsgainincomplexity,theygenerallygaininsize,and,soonerorlater,theybecomeunruly.Whenconfrontinghundredsoflineso