Java編程入門-英語教材_第1頁
Java編程入門-英語教材_第2頁
Java編程入門-英語教材_第3頁
Java編程入門-英語教材_第4頁
Java編程入門-英語教材_第5頁
已閱讀5頁,還剩44頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

Lecture3–Programming2ObjectOrientedProgrammingInWeek2wecoveredMethodsarguments,parametersreturnvoidactivationstack/objectheapaccessingmembersviadotoperator(.)ThisWeekConstructsif,switchfor,whileClassdevelopmentConstructorsGet/SetmethodsAccessspecificationNextcoupleofweeks...InheritanceDynamicbindingAbstractclasses/methodsPolymorphismLectureTest!!!NewfunctionalityOurprogramcurrentlyprocessesaSquare,thenaRectangleandthenaCircle.Let’smodifyitsothattheusercanindicatewhichshapeheorshewantstoworkwith.Thenewprogramwillasktheusertoenter1-foraSquare2-foraRectangle3-foraCircleIfStatementLikePython,JavahasanifstatementTheifstatementallowsachoicebetweendifferentexecutionpathsItchecksabooleanconditionalexpression(true/false)IftheexpressionistrueTheifpathisfollowedIftheexpressionisfalseTheelsepath(ifitexists)isfollowedUnlikePythonthereisnoelifkeywordWecanuseelseifhoweverThemodifiedmainmethodSystem.out.print("Enter1forSquare,2forRectangle,3for Circle:");intchoice=scan.nextInt();if(choice==1) processSquare(scan);elseif(choice==2) processRectangle(scan);elseif(choice==3) processCircle(scan);else System.out.println("Wrongnumber");NotesWhenweruntheaboveprogramonlyoneshapewillbeprocessed–not3Theshapeprocessedwillbedeterminedbytheuser–byentering1,2or3Iftheuserenterssomethingotherthan1,2or3theprogramwillgiveanerrormessageMorethanonestatementIftheprogramisrequiredtoexecutemorethanonestatementonanyparticularpath,theyneedtobeenclosedinbraces{}if(choice==1){ System.out.println(“Youhavechosen1”); processSquare(); }IfthebracesareomittedonlythefirststatementwillbelongtotheifprocessSquarewillbecallednomatterwhatvaluechoicehasAnothermethod-ifTestAgaintoavoidclutteringupthemainmethodwe’llputthenewcodeintoamethodcalledifTestThismethodwillbevoid(itwon’treturnavalue)andwilltakeoneparameter(ofclassScanner)ThecodeforthismethodisshownonthenextslideThecodeforthemodifiedmainmethodwillbeshownontheslideafterthatifTestcodevoidifTest(Scannerscan){ System.out.print("Enter1forSquare,2for Rectangle,3 forCircle:"); intchoice=scan.nextInt(); if(choice==1) processSquare(scan); elseif(choice==2) processRectangle(scan); elseif(choice==3) processCircle(scan); else System.out.println("Wrongnumberentered");}LoopsLet’sconsiderasituationwherewewanttoallowtheusertoprocess5shapesandwewanthimorhertocontrolwhichshapestheyareLikePython,Javaprovidestwodifferentloopingstructures(thereareothersbutwewon’tcoverthem)forloop -definiteloopwhileloop -indefiniteloopWhileloopSimilartothewhileloopinPythonStartswiththekeywordwhileGovernedbyaconditionalexpression(true/false)IftheexpressionevaluatestotrueTheloopiteratesTheexpressionisevaluatedagainTheloopwillcontinuetoiterateuntiltheexpressionevaluatestofalseBecarefulofinfiniteloops–usuallyabadthingCodedemonstratingwhileloopvoidwhileTest(Scannerscan){ inti=0; while(i<5){ ifTest(scan); i++; }}NotethattheloopconsistsofthreemajorelementsAstatementthatinitialisesthecountervariable(i)Anexpressionthattestswhetheriislessthan5Astatementtoadd1toi–otherwiseinfiniteloop(why?)AforloopbringstheseelementstogetherintooneplaceForloopfor(inti=0;i<5;i++){ ifTest(scan);}TheforloopismadeupofthefollowingpartsThekeywordforAgroupofthreeexpressionsenclosedinbracketsThefirstexpressionistheinitialiserItiscalledonlyonce–whentheforloopisenteredWecandeclareanewvariableatthesametimeFurthermore,wecangiveitavalueSowecreateanintvariablecalledi,andinitialiseitto0ThesecondexpressionisaconditionalexpressionTheforloopwilliterateonlyifthisexpressionistrueThethirdexpressionupdatestheforloopcounter(i)1isaddedtoiaftereachiterationMethodtotesttheforloopvoidforTest(Scannerscan){ for(inti=0;i<5;i++){ ifTest(scan); }}NotethatthefirstexpressiondeclaresiandintialisesitatthesametimeSwitchstatementNotcoveredinProgramming1(sopayattention)AdecisionconstructliketheifstatementItevaluatesanint(orbyte,char,short,String)expressionItthenexaminesalistofcasesThecasethatmatches(hasthesamevalue)astheexpressionischosenandthecodeassociatedwithitisexecuted.ThecodeonthenextslideshowsthecodeinifTestbeingrewrittenasaswitchstatementMethodtotestswitchstatementvoidswitchTest(Scannerscan){ System.out.print(“1forSquare,2forRectangle,3forCircle:"); intchoice=scan.nextInt(); switch(choice){ case1: processSquare(scan); break; case2: processRectangle(scan); break; case3: processCircle(scan); break; default: System.out.println("Wrongnumberentered"); }}NotesoncodefrompreviousslideNotetheuseofthekeywordsswitchandcaseTheexpressionfollowingswitchisenclosedinbracesItshouldevaluatetoanintvalue.AdoubleorfloatexpressionwillcauseanerrorThekeywordbreakisusedthreetimes.Itcausesexecutiontoleave(breakoutof)theswitchstatementIfthebreakisnottherethenexecutionwillfallthroughtothenextcaseForexample,ifthebreakwasomittedafterprocessSquareandtheuserentered1,thenprocessSquarewouldbecalledandthenprocessRectangle–whichisprobablynotwhatyouwantThefinalalternativeisdefault.Itischosenwheneverchoicedoesnotequal1,2or3ModifiedcodeformethodforTestvoidforTest(Scannerscan){ for(inti=0;i<5;i++){ //ifTest(scan); switchTest(scan); }}WehavecommentedoutifTestandinvokedswitchTest.Theresultshouldbeexactlythesame.SummaryWe’vediscussedtheuseofvariouscontrolstructuresif,switch,while,forWewillnowmoveontoanimportanttopicThecreationofindividualclassesWewilldothisbyidentifyingappropriateobjectsintheShapesclassandwritingclassestomodelthemShapesclassConsidertheShapesclassWecreatedseveralmethodsthatdealtwithvariousshapesCircles,Squares,RectanglesThisclasscanbeinstantiatedanditsmethodsinvokedButwemightfindmoreuseforclassesthatdealwithcircles,squareandrectanglesindividuallyTheseareeasiertoworkwithandtoreuseASquareclassWemightdecidethatwewanttomakeanobjecttomodelaSquareRememberanobjectmodelsbothdatafunctionalityLet’sfirstconsiderthedataassociatedwithaSquareWeneedonepieceofdataThelengthofthesideofthesquareInstanceVariablesThedataisincludedintheclassasinstancevariables(fields).Thesearesimilarinmanywaystothevariablesthatwe’vealreadyencounteredWe’llmakethesideofasquare(we’llcallit‘side’)adouble(althoughwecouldmakeitafloattooifwewanted)OurSquareclasssofarpublicclassSquare{ doubleside;}AboveisthecodeforaclasscalledSquare.Thekeywordpublicmeansthatit’savailableforotherclassestouseThekeywordclassdesignatesthatit’saclassTheidentifierSquareischosenbytheprogrammerandshouldbemeaningfulAlloftheinstancevariablesandmethodsthatbelongtotheclassareenclosedinsidebraces{}TheclasssofarconsistsonlyofasingleinstancevariableandthusisnotveryusefulasyetMethodsNowweneedtothinkaboutthefunctionalityoftheclassWhatsortofthingsarewegoingtowanttodowiththedata?InourSquareclasstherearetwoobviouscandidatesformethodsdoublecalculateAreaOfSquare(double)doublecalculatePerimeterOfSquare(double)Eachofthemtakeasingleparameteroftypedoubleandreturnavalueoftypedouble.OurSquareclasssofarpublicclassSquare{ doubleside; doublecalculateAreaOfSquare(doubleside){ returnside*side; } doublecalculatePerimeterOfSquare(doubleside){ return4*side; }}TheclassSquareWeaddedtwomethodstoourSquareclasscalculateAreaOfSquarecalculatePerimeterOfSquareWe’llmakeacoupleofchangestothese.Firstly,we’llmakethenamesabitshorter.TheybelongtotheSquareclassnowsowedon’tneedtoreflectthatinthename.We’llmaketheirnamescalcAreacalcPerimeterSecondly,wehavesaidthatthepurposeofthemethodsistomanipulatethedataintheinstancevariables.Therefore,thereisnoneedtopass‘side’asanargument.OurSquareclasssofarpublicclassSquare{ doubleside; doublecalcArea(){ returnside*side; } doublecalcPerimeter(){ return4*side; }}ClassdiagramsClassesareoftensummarisedinclassdiagramsForourpurposesaclassdiagramisaboxwiththreesectionsThetopsectionhasthenameoftheclassThemiddlesectioncontainstheinstancevariablesThebottomsectioncontainsthemethodsClassdiagramsusuallycontainmanysuchboxesandrepresenttherelationshipsbetweenthem.However,wewillstartwithasingleclass.ClassDiagramSquaredoubleside;doublecalcArea()doublecalcPerimeter()CreatingSquareobjectsNowthatwehavedefinedaSquareclasshowdoweuseitinourprogram.Theoriginalcodewas

System.out.println(“Enterthesideofasquare:”);doubleside=scan.nextDouble();doubleareaOfSquare=s.calculateAreaOfSquare(side); System.out.println(“Areais“+areaOfSquare);WewillrewritethiscodeinthenextcoupleofslidestouseournewSquareclassCreatingaSquareobjectWe’vepreviouslyusedthenewoperatortocreatevariousobjects.WewillnowuseittocreateanewSquareobject Squaresq=newSquare()Wecannowusesqtointeractwiththenewlycreatedobject.GivingtheinstancevariableavalueWewillnowgivetheinstancevariablesideavalue.Thevaluewillbewhateverisenteredbytheuser.Wecandothisthroughtheuseofthedotoperator(.) sq.side=side;Wecanthenusethemethodtocalculatethearea area=sq.calculateArea();DatahidingRememberwhenwemadeuseoftheAPIspecificationsinordertousetheJFrameclass?Rememberthatallthatwaslistedweremethods.Wedidnotseeanyinstancevariableslistedforthisclass.ThiswillbetrueofthevastmajorityofclassesintheAPI.Thisisadeliberatedecisiononthepartoftheclassdeveloperstohidethedataandmakeaccesstoitavailableonlythroughitsmethods.AccessSpecificationJavaprovidesthreeaccessspecifierswhichdeterminehowaparticularmembercanbeaccessed.Thesearepublic -availabletoanyotherclassprivate -onlyavailabletomethodsinitsown classprotected -availabletosubclasses(moreonthis whenwecoverinheritance)Ifyoudon’tgiveamemberanaccessspecifierthenthedefault(sometimescalledpackage)isused.Thememberwillbeavailabletoallclassesinthesamepackagebutnoothers.Whatshouldbeprivate?We’vealreadyalludedtothisItisusualtomakeallinstancevariablesprivateThemethodsthatyouwanttomakeavailabletootherclassesshouldbepublicTheremaybesomemethodswhoseonlyjobistobecalledbyothermethodsintheclass.Theseshouldbeprivateaswell.OurSquareclasssofarpublicclassSquare{ privatedoubleside; publicdoublecalcArea(){ returnside*side; } publicdoublecalcPerimeter(){ return4*side; }}calcAreaandcalcPerimetercanbeusedbyotherclasses.Theinstancevariable,side,canonlybeaccessedbymethodsbelongingtoSquareWhymakethedataprivate?Makingthedataprivategivestheclassdevelopersomecontroloverhowtheobjectsareused.Let’ssaythatweasclassdevelopersdecidethatthesideofaSquareshouldneverbenegative.Itshouldonlyeverbe0orpositive.Byallowing sq.side=lengthWecannotpreventsidefromreceivinganegativenumber.AccessingprivateinstancevariableNowthatwehavemadesideprivatethestatementaboveisnolongerlegalandwillresultinanerror.ButnowwehavenowayatallofgivingsideavalueandsoourclassnolongerhasanyuseTherearetwoverycommonsortsofmethodthatallowustoovercomethisproblem.Thesearecalledgetmethods(orgetters)setmethods(orsetters)GetmethodThecommonformofnamingagetmethodisbyusingtheprefix‘get’andthenthenameoftheinstancevariablestartingwithanuppercaseletterThusagetmethodforsidewouldbecalledgetSideAgetmethodhasnoparameterandhasareturntypewhichisthesameasitsinstancevariableInthiscasedoubleIt’susedtoreturnthecurrentvalueoftheinstancevariabledoublegetSide(){ returnside;}SetmethodThecommonformofnamingasetmethodisbyusingtheprefix‘set’andthenthenameoftheinstancevariablestartingwithanuppercaseletterThusasetmethodforsidewouldbecalledsetSideAsetmethodhasnoreturntype(void)andhasasingleparameterwhichisthesametypeasitsinstancevariableInthiscasedoubleIt’susedtosetthecurrentvalueoftheinstancevariablevoidsetSide(doublelen){ side=len;}ModifyingthesetmethodNowthatwecanonlysetthevalueofsidethroughitssetmethod,wecanwritecodetoensurethatonlypositivenumbers(andzero)canbeused.Ifthevalueoftheparameterisnegativethesetterwillsetthevalueofsideto0.Otherwiseitwillsetittothevalueoftheparameter voidsetSide(doublelen){ if(len<0) side=0;

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論