版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 廣東門衛(wèi)合同范本
- 手寫的協(xié)議書模板
- 小肥骨折協(xié)議書
- 資產分配協(xié)議書
- 針灸治病協(xié)議書
- 自我成長協(xié)議書
- 質保服務協(xié)議書
- 資金結算協(xié)議書
- 銷售設備合同范本
- 兼職還款合同范本
- 2025下半年貴州遵義市市直事業(yè)單位選調56人備考筆試試題及答案解析
- 2025中原農業(yè)保險股份有限公司招聘67人備考題庫附答案
- 河南省信陽市高中聯(lián)盟2025-2026學年高三上學期12月聯(lián)考語文試卷(含答案)
- 2025年陜西公務員《行政職業(yè)能力測驗》試題及答案
- 2025年無人機操控員執(zhí)照理論考試題庫及答案(2月份更新)
- 高考作文寫作訓練:“傳承古韻創(chuàng)新前行”作文閱卷細則及高分作文
- 技術賦能 融合實踐 推動區(qū)域教育高質量發(fā)展
- 泛酸鈣在口腔科疾病中的應用研究
- 診所危險化學物品應急預案
- 潔凈區(qū)管理及無菌操作知識培訓課件
- 港股通綜合業(yè)務介紹
評論
0/150
提交評論