




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
附錄A外文翻譯—原文部分Excerptfrom《ThinkinginJava(FouthEdition)》:IntroductiontoObjects“Wecutnatureup,organizeitintoconcepts,andascribesignificancesaswedo,largelybecausewearepartiestoanagreementthatholdsthroughoutourspeechcommunityandiscodifiedinthepatternsofourlanguage…wecannottalkatallexceptbysubscribingtotheorganizationandclassificationofdatawhichtheagreementdecrees.”BenjaminLeeWhorf(1897-1941)Thegenesisofthecomputerrevolutionwasinamachine.Thegenesisofourprogramminglanguagesthustendstolooklikethatmachine.Butcomputersarenotsomuchmachinesastheyaremindamplificationtools(“bicyclesforthemind,”asSteveJobsisfondofsaying)andadifferentkindofexpressivemedium.Asaresult,thetoolsarebeginningtolooklesslikemachinesandmorelikepartsofourminds,andalsolikeotherformsofexpressionsuchaswriting,painting,sculpture,animation,andfilmmaking.Object-orientedprogramming(OOP)ispartofthismovementtowardusingthecomputerasanexpressivemedium.ThischapterwillintroduceyoutothebasicconceptsofOOP,includinganoverviewofdevelopmentmethods.Thischapter,andthisbook,assumesthatyouhavesomeprogrammingexperience,althoughnotnecessarilyinC.Ifyouthinkyouneedmorepreparationinprogrammingbeforetacklingthisbook,youshouldworkthroughtheThinkinginCmultimediaseminar,downloadablefromwww.MindV.Thischapterisbackgroundandsupplementarymaterial.Manypeopledonotfeelcomfortablewadingintoobject-orientedprogrammingwithoutunderstandingthebigpicturefirst.Thus,therearemanyconceptsthatareintroducedheretogiveyouasolidoverviewofOOP.However,otherpeoplemaynotgetthebigpictureconceptsuntilthey’veseensomeofthemechanicsfirst;thesepeoplemaybecomeboggeddownandlostwithoutsomecodetogettheirhandson.Ifyou’repartofthislattergroupandareeagertogettothespecificsofthelanguage,feelfreetojumppastthischapter—skippingitatthispointwillnotpreventyoufromwritingprogramsorlearningthelanguage.However,youwillwanttocomebackhereeventuallytofillinyourknowledgesoyoucanunderstandwhyobjectsareimportantandhowtodesignwiththem.TheprogressofabstractionAllprogramminglanguagesprovideabstractions.Itcanbearguedthatthecomplexityoftheproblemsyou’reabletosolveisdirectlyrelatedtothekindandqualityofabstraction.By“kind”Imean,“Whatisitthatyouareabstracting?”Assemblylanguageisasmallabstractionoftheunderlyingmachine.Manyso-called“imperative”languagesthatfollowed(suchasFORTRAN,BASIC,andC)wereabstractionsofassemblylanguage.Theselanguagesarebigimprovementsoverassemblylanguage,buttheirprimaryabstractionstillrequiresyoutothinkintermsofthestructureofthecomputerratherthanthestructureoftheproblemyouaretryingtosolve.Theprogrammermustestablishtheassociationbetweenthemachinemodel(inthe“solutionspace,”whichistheplacewhereyou’reimplementingthatsolution,suchasacomputer)andthemodeloftheproblemthatisactuallybeingsolved(inthe“problemspace,”whichistheplacewheretheproblemexists,suchasabusiness).Theeffortrequiredtoperformthismapping,andthefactthatitisextrinsictotheprogramminglanguage,producesprogramsthataredifficulttowriteandexpensivetomaintain,andasasideeffectcreatedtheentire“programmingmethods”industry.Thealternativetomodelingthemachineistomodeltheproblemyou’retryingtosolve.EarlylanguagessuchasLISPandAPLchoseparticularviewsoftheworld(“Allproblemsareultimatelylists”or“Allproblemsarealgorithmic,”respectively).Prologcastsallproblemsintochainsofdecisions.Languageshavebeencreatedforconstraint-basedprogrammingandforprogrammingexclusivelybymanipulatinggraphicalsymbols.(Thelatterprovedtobetoorestrictive.)Eachoftheseapproachesmaybeagoodsolutiontotheparticularclassofproblemthey’redesignedtosolve,butwhenyoustepoutsideofthatdomaintheybecomeawkward.Theobject-orientedapproachgoesastepfurtherbyprovidingtoolsfortheprogrammertorepresentelementsintheproblemspace.Thisrepresentationisgeneralenoughthattheprogrammerisnotconstrainedtoanyparticulartypeofproblem.Werefertotheelementsintheproblemspaceandtheirrepresentationsinthesolutionspaceas“objects.”(Youwillalsoneedotherobjectsthatdon’thaveproblem-spaceanalogs.)Theideaisthattheprogramisallowedtoadaptitselftothelingooftheproblembyaddingnewtypesofobjects,sowhenyoureadthecodedescribingthesolution,you’rereadingwordsthatalsoexpresstheproblem.Thisisamoreflexibleandpowerfullanguageabstractionthanwhatwe’vehadbefore.1Thus,OOPallowsyoutodescribetheproblemintermsoftheproblem,ratherthanintermsofthecomputerwherethesolutionwillrun.There’sstillaconnectionbacktothecomputer:Eachobjectlooksquiteabitlikealittlecomputer—ithasastate,andithasoperationsthatyoucanaskittoperform.However,thisdoesn’tseemlikesuchabadanalogytoobjectsintherealworld—theyallhavecharacteristicsandbehaviors.AlanKaysummarizedfivebasiccharacteristicsofSmalltalk,thefirstsuccessfulobject-orientedlanguageandoneofthelanguagesuponwhichJavaisbased.Thesecharacteristicsrepresentapureapproachtoobject-orientedprogramming:1.Everythingisanobject.Thinkofanobjectasafancyvariable;itstoresdata,butyoucan“makerequests”tothatobject,askingittoperformoperationsonitself.Intheory,youcantakeanyconceptualcomponentintheproblemyou’retryingtosolve(dogs,buildings,services,etc.)andrepresentitasanobjectinyourprogram.2.Aprogramisabunchofobjectstellingeachotherwhattodobysendingmessages.Tomakearequestofanobject,you“sendamessage”tothatobject.Moreconcretely,youcanthinkofamessageasarequesttocallamethodthatbelongstoaparticularobject.3.Eachobjecthasitsownmemorymadeupofotherobjects.Putanotherway,youcreateanewkindofobjectbymakingapackagecontainingexistingobjects.Thus,youcanbuildcomplexityintoaprogramwhilehidingitbehindthesimplicityofobjects.4.Everyobjecthasatype.Usingtheparlance,eachobjectisaninstanceofaclass,inwhich“class”issynonymouswith“type.”Themostimportantdistinguishingcharacteristicofaclassis“Whatmessagescanyousendtoit?”5.Allobjectsofaparticulartypecanreceivethesamemessages.Thisisactuallyaloadedstatement,asyouwillseelater.Becauseanobjectoftype“circle”isalsoanobjectoftype“shape,”acircleisguaranteedtoacceptshapemessages.Thismeansyoucanwritecodethattalkstoshapesandautomaticallyhandleanythingthatfitsthedescriptionofashape.ThissubstitutabilityisoneofthepowerfulconceptsinOOP.Boochoffersanevenmoresuccinctdescriptionofanobject:Anobjecthasstate,behaviorandidentity.Thismeansthatanobjectcanhaveinternaldata(whichgivesitstate),methods(toproducebehavior),andeachobjectcanbeuniquelydistinguishedfromeveryotherobject—toputthisinaconcretesense,eachobjecthasauniqueaddressinmemory.AnobjecthasaninterfaceAristotlewasprobablythefirsttobeginacarefulstudyoftheconceptoftype;hespokeof“theclassoffishesandtheclassofbirds.”Theideathatallobjects,whilebeingunique,arealsopartofaclassofobjectsthathavecharacteristicsandbehaviorsincommonwasuseddirectlyinthefirstobject-orientedlanguage,Simula-67,withitsfundamentalkeywordclassthatintroducesanewtypeintoaprogram.Simula,asitsnameimplies,wascreatedfordevelopingsimulationssuchastheclassic“banktellerproblem.”Inthis,youhavenumeroustellers,customers,accounts,transactions,andunitsofmoney—alotof“objects.”O(jiān)bjectsthatareidenticalexceptfortheirstateduringaprogram’sexecutionaregroupedtogetherinto“classesofobjects,”andthat’swherethekeywordclasscamefrom.Creatingabstractdatatypes(classes)isafundamentalconceptinobject-orientedprogramming.Abstractdatatypesworkalmostexactlylikebuilt-intypes:Youcancreatevariablesofatype(calledobjectsorinstancesinobject-orientedparlance)andmanipulatethosevariables(calledsendingmessagesorrequests;yousendamessageandtheobjectfiguresoutwhattodowithit).Themembers(elements)ofeachclasssharesomecommonality:Everyaccounthasabalance,everytellercanacceptadeposit,etc.Atthesametime,eachmemberhasitsownstate:Eachaccounthasadifferentbalance,eachtellerhasaname.Thus,thetellers,customers,accounts,transactions,etc.,caneachberepresentedwithauniqueentityinthecomputerprogram.Thisentityistheobject,andeachobjectbelongstoaparticularclassthatdefinesitscharacteristicsandbehaviors.So,althoughwhatwereallydoinobject-orientedprogrammingiscreatenewdatatypes,virtuallyallobject-orientedprogramminglanguagesusethe“class”keyword.Whenyouseetheword“type”think“class”andviceversa.3Sinceaclassdescribesasetofobjectsthathaveidenticalcharacteristics(dataelements)andbehaviors(functionality),aclassisreallyadatatypebecauseafloatingpointnumber,forexample,alsohasasetofcharacteristicsandbehaviors.Thedifferenceisthataprogrammerdefinesaclasstofitaproblemratherthanbeingforcedtouseanexistingdatatypethatwasdesignedtorepresentaunitofstorageinamachine.Youextendtheprogramminglanguagebyaddingnewdatatypesspecifictoyourneeds.Theprogrammingsystemwelcomesthenewclassesandgivesthemallthecareandtypecheckingthatitgivestobuilt-intypes.Theobject-orientedapproachisnotlimitedtobuildingsimulations.Whetherornotyouagreethatanyprogramisasimulationofthesystemyou’redesigning,theuseofOOPtechniquescaneasilyreducealargesetofproblemstoasimplesolution.Onceaclassisestablished,youcanmakeasmanyobjectsofthatclassasyoulike,andthenmanipulatethoseobjectsasiftheyaretheelementsthatexistintheproblemyouaretryingtosolve.Indeed,oneofthechallengesofobject-orientedprogrammingistocreateaone-to-onemappingbetweentheelementsintheproblemspaceandobjectsinthesolutionspace.Buthowdoyougetanobjecttodousefulworkforyou?Thereneedstobeawaytomakearequestoftheobjectsothatitwilldosomething,suchascompleteatransaction,drawsomethingonthescreen,orturnonaswitch.Andeachobjectcansatisfyonlycertainrequests.Therequestsyoucanmakeofanobjectaredefinedbyitsinterface,andthetypeiswhatdeterminestheinterface.Asimpleexamplemightbearepresentationofalightbulb:Lightlt=newLight();lt.on();Theinterfacedeterminestherequeststhatyoucanmakeforaparticularobject.However,theremustbecodesomewheretosatisfythatrequest.This,alongwiththehiddendata,comprisestheimplementation.Fromaproceduralprogrammingstandpoint,it’snotthatcomplicated.Atypehasamethodassociatedwitheachpossiblerequest,andwhenyoumakeaparticularrequesttoanobject,thatmethodiscalled.Thisprocessisusuallysummarizedbysayingthatyou“sendamessage”(makearequest)toanobject,andtheobjectfiguresoutwhattodowiththatmessage(itexecutescode).Here,thenameofthetype/classisLight,thenameofthisparticularLightobjectislt,andtherequeststhatyoucanmakeofaLightobjectaretoturniton,turnitoff,makeitbrighter,ormakeitdimmer.YoucreateaLightobjectbydefininga“reference”(lt)forthatobjectandcallingnewtorequestanewobjectofthattype.Tosendamessagetotheobject,youstatethenameoftheobjectandconnectittothemessagerequestwithaperiod(dot).Fromthestandpointoftheuserofapredefinedclass,that’sprettymuchallthereistoprogrammingwithobjects.TheprecedingdiagramfollowstheformatoftheUnifiedModelingLanguage(UML).Eachclassisrepresentedbyabox,withthetypenameinthetopportionofthebox,anydatamembersthatyoucaretodescribeinthemiddleportionofthebox,andthemethods(thefunctionsthatbelongtothisobject,whichreceiveanymessagesyousendtothatobject)inthebottomportionofthebox.附錄B外文翻譯—譯文部分摘自《Java編程思想(第四版)》:對象入門面向?qū)ο缶幊蹋∣OP)具有多方面的吸引力。對管理人員,它實現(xiàn)了更快和更廉價的開發(fā)與維護過程。對分析與設(shè)計人員,建模處理變得更加簡單,能生成清晰、易于維護的設(shè)計方案。對程序員,對象模型顯得如此高雅和淺顯。此外,面向?qū)ο蠊ぞ咭约皫斓木薮笸κ咕幊坛蔀橐豁椄谷擞鋹偟娜蝿?wù)。每個人都可從中獲益,至少表面如此。如果說它有缺點,那就是掌握它需付出的代價。思考對象的時候,需要采用形象思維,而不是程序化的思維。與程序化設(shè)計相比,對象的設(shè)計過程更具挑戰(zhàn)性——特別是在嘗試創(chuàng)建可重復(fù)使用(可再生)的對象時。過去,那些初涉面向?qū)ο缶幊填I(lǐng)域的人都必須進行一項令人痛苦的選擇:選擇一種諸如Smalltalk的語言,“出師”前必須掌握一個巨型的庫。選擇幾乎根本沒有庫的C++,然后深入學習這種語言,直至能自行編寫對象庫。事實上,很難很好地設(shè)計出對象——從而很難設(shè)計好任何東西。因此,只有數(shù)量相當少的“專家”能設(shè)計出最好的對象,然后讓其他人享用。對于成功的OOP語言,它們不僅集成了這種語言的語法以及一個編譯程序(編譯器),而且還有一個成功的開發(fā)環(huán)境,其中包含設(shè)計優(yōu)良、易于使用的庫。所以,大多數(shù)程序員的首要任務(wù)就是用現(xiàn)有的對象解決自己的應(yīng)用問題。本章的目標就是向大家揭示出面向?qū)ο缶幊痰母拍睿⒆C明它有多么簡單。本章將向大家解釋Java的多項設(shè)計思想,并從概念上解釋面向?qū)ο蟮某绦蛟O(shè)計。但要注意在閱讀完本章后,并不能立即編寫出全功能的Java程序。所有詳細的說明和示例會在本書的其他章節(jié)慢慢道來。抽象的進步所有編程語言的最終目的都是提供一種“抽象”方法。一種較有爭議的說法是:解決問題的復(fù)雜程度直接取決于抽象的種類及質(zhì)量。這兒的“種類”是指準備對什么進行“抽象”?匯編語言是對基礎(chǔ)機器的少量抽象。后來的許多“命令式”語言(如FORTRAN,BASIC和C)是對匯編語言的一種抽象。與匯編語言相比,這些語言已有了長足的進步,但它們的抽象原理依然要求我們著重考慮計算機的結(jié)構(gòu),而非考慮問題本身的結(jié)構(gòu)。在機器模型(位于“方案空間”)與實際解決的問題模型(位于“問題空間”)之間,程序員必須建立起一種聯(lián)系。這個過程要求人們付出較大的精力,而且由于它脫離了編程語言本身的范圍,造成程序代碼很難編寫,而且要花較大的代價進行維護。由此造成的副作用便是一門完善的“編程方法”學科。為機器建模的另一個方法是為要解決的問題制作模型。對一些早期語言來說,如LISP和APL,它們的做法是“從不同的角度觀察世界”——“所有問題都歸納為列表”或“所有問題都歸納為算法”。PROLOG則將所有問題都歸納為決策鏈。對于這些語言,我們認為它們一部分是面向基于“強制”的編程,另一部分則是專為處理圖形符號設(shè)計的。每種方法都有自己特殊的用途,適合解決某一類的問題。但只要超出了它們力所能及的范圍,就會顯得非常笨拙。面向?qū)ο蟮某绦蛟O(shè)計在此基礎(chǔ)上則跨出了一大步,程序員可利用一些工具表達問題空間內(nèi)的元素。由于這種表達非常普遍,所以不必受限于特定類型的問題。我們將問題空間中的元素以及它們在方案空間的表示物稱作“對象”(Object)。當然,還有一些在問題空間沒有對應(yīng)體的其他對象。通過添加新的對象類型,程序可進行靈活的調(diào)整,以便與特定的問題配合。所以在閱讀方案的描述代碼時,會讀到對問題進行表達的話語。與我們以前見過的相比,這無疑是一種更加靈活、更加強大的語言抽象方法??傊琌OP允許我們根據(jù)問題來描述問題,而不是根據(jù)方案。然而,仍有一個聯(lián)系途徑回到計算機。每個對象都類似一臺小計算機;它們有自己的狀態(tài),而且可要求它們進行特定的操作。與現(xiàn)實世界的“對象”或者“物體”相比,編程“對象”與它們也存在共通的地方:它們都有自己的特征和行為。AlanKay總結(jié)了Smalltalk的五大基本特征。這是第一種成功的面向?qū)ο蟪绦蛟O(shè)計語言,也是Java的基礎(chǔ)語言。通過這些特征,我們可理解“純粹”的面向?qū)ο蟪绦蛟O(shè)計方法是什么樣的:1、所有東西都是對象。可將對象想象成一種新型變量;它保存著數(shù)據(jù),但可要求它對自身進行操作。理論上講,可從要解決的問題身上提出所有概念性的組件,然后在程序中將其表達為一個對象。2、程序是一大堆對象的組合;通過消息傳遞,各對象知道自己該做些什么。為了向?qū)ο蟀l(fā)出請求,需向那個對象“
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 開展主題班會的準備工作計劃
- 提升團隊創(chuàng)新能力的計劃
- 班級危機處理與應(yīng)急預(yù)案計劃
- 西餐廳創(chuàng)新創(chuàng)業(yè)計劃書
- 2025年Υ射線無損探測儀項目合作計劃書
- 2025年液體制劑機械項目合作計劃書
- 2025年勞務(wù)派遣合同和勞動合同模板區(qū)別
- 2025年自營批發(fā)服務(wù)項目建議書
- 工廠員工轉(zhuǎn)正評語
- 資產(chǎn)委托保管協(xié)議
- 2025年廣東省深圳市高考語文一模試卷
- 2025年福建省高職單招職業(yè)適應(yīng)性測試題庫及答案解析
- 統(tǒng)編版(2025)七年級下冊道德與法治第一課《青春正當時》教案(3課時)
- 自媒體運營實戰(zhàn)教程(抖音版) 課件 第7章 短視頻運營-自媒體中級
- 2025時事政治必考題庫含參考答案
- 保潔管理安全培訓課件
- 小學生藥品安全課件視頻
- 隧洞運輸車輛安全課件
- 工程機械租賃服務(wù)方案及保障措施
- 新產(chǎn)程觀察和護理課件
- 《高低壓配電室施工工藝標準》
評論
0/150
提交評論