外文翻译 - 一切都是对象_第1页
外文翻译 - 一切都是对象_第2页
外文翻译 - 一切都是对象_第3页
外文翻译 - 一切都是对象_第4页
外文翻译 - 一切都是对象_第5页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

英文原文及翻译英文EverythingisanObjectAlthoughitisbasedonC+,Javaismoreofa“pure”object-orientedlanguage.BothC+andJavaarehybridlanguages,butinJavathedesignersfeltthatthehybridizationwasnotasimportantasitwasinC+.Ahybridlanguageallowsmultipleprogrammingstyles;thereasonC+ishybridistosupportbackwardcompatibilitywiththeClanguage.BecauseC+isasupersetoftheClanguage,itincludesmanyofthatlanguagesundesirablefeatures,whichcanmakesomeaspectsofC+overlycomplicated.TheJavalanguageassumesthatyouwanttodoonlyobject-orientedprogramming.Thismeansthatbeforeyoucanbeginyoumustshiftyourmindsetintoanobject-orientedworld(unlessitsalreadythere).ThebenefitofthisinitialeffortistheabilitytoprograminalanguagethatissimplertolearnandtousethanmanyotherOOPlanguages.InthischapterwellseethebasiccomponentsofaJavaprogramandwelllearnthateverythinginJavaisanobject,evenaJavaprogram.YoumanipulateobjectswithreferencesEachprogramminglanguagehasitsownmeansofmanipulatingdata.Sometimestheprogrammermustbeconstantlyawareofwhattypeofmanipulationisgoingon.Areyoumanipulatingtheobjectdirectly,orareyoudealingwithsomekindofindirectrepresentation(apointerinCorC+)thatmustbetreatedwithaspecialsyntax?AllthisissimplifiedinJava.Youtreateverythingasanobject,usingasingleconsistentsyntax.Althoughyoutreateverythingasanobject,theidentifieryoumanipulateisactuallya“reference”toanobject.10Youmightimaginethissceneasatelevision(theobject)withyourremotecontrol(thereference).Aslongasyoureholdingthisreference,youhaveaconnectiontothetelevision,butwhensomeonesays“changethechannel”or“lowerthevolume,”whatyouremanipulatingisthereference,whichinturnmodifiestheobject.Ifyouwanttomovearoundtheroomandstillcontrolthetelevision,youtaketheremote/referencewithyou,notthetelevision.Also,theremotecontrolcanstandonitsown,withnotelevision.Thatis,justbecauseyouhaveareferencedoesntmeantheresnecessarilyanobjectconnectedtoit.Soifyouwanttoholdawordorsentence,youcreateaStringreference:Strings;Buthereyouvecreatedonlythereference,notanobject.Ifyoudecidedtosendamessagetosatthispoint,youllgetanerror(atruntime)becausesisntactuallyattachedtoanything(theresnotelevision).Asaferpractice,then,isalwaystoinitializeareferencewhenyoucreateit:Strings=asdf;However,thisusesaspecialJavafeature:stringscanbeinitializedwithquotedtext.Normally,youmustuseamoregeneraltypeofinitializationforobjects.YoumustcreatealltheobjectsWhenyoucreateareference,youwanttoconnectitwithanewobject.Youdoso,ingeneral,withthenewkeyword.Thekeywordnewsays,“Makemeanewoneoftheseobjects.”Sointheprecedingexample,youcansay:Strings=newString(asdf);Notonlydoesthismean“MakemeanewString,”butitalsogivesinformationabouthowtomaketheStringbysupplyinganinitialcharacterstring.Ofcourse,Stringisnottheonlytypethatexists.Javacomeswithaplethoraofready-madetypes.Whatsmoreimportantisthatyoucancreateyourowntypes.Infact,thatsthefundamentalactivityinJavaprogramming,anditswhatyoullbelearningaboutintherestofthisbook.WherestoragelivesItsusefultovisualizesomeaspectsofhowthingsarelaidoutwhiletheprogramisrunninginparticularhowmemoryisarranged.Therearesixdifferentplacestostoredata:Registers.Thisisthefasteststoragebecauseitexistsinaplacedifferentfromthatofotherstorage:insidetheprocessor.However,thenumberofregistersisseverelylimited,soregistersareallocatedbythecompileraccordingtoitsneeds.Youdonthavedirectcontrol,nordoyouseeanyevidenceinyourprogramsthatregistersevenexist.Thestack.Thislivesinthegeneralrandom-accessmemory(RAM)area,buthasdirectsupportfromtheprocessorviaitsstackpointer.Thestackpointerismoveddowntocreatenewmemoryandmoveduptoreleasethatmemory.Thisisanextremelyfastandefficientwaytoallocatestorage,secondonlytoregisters.TheJavacompilermustknow,whileitiscreatingtheprogram,theexactsizeandlifetimeofallthedatathatisstoredonthestack,becauseitmustgeneratethecodetomovethestackpointerupanddown.Thisconstraintplaceslimitsontheflexibilityofyourprograms,sowhilesomeJavastorageexistsonthestackinparticular,objectreferencesJavaobjectsthemselvesarenotplacedonthestack.Theheap.Thisisageneral-purposepoolofmemory(alsointheRAMarea)whereallJavaobjectslive.Thenicethingabouttheheapisthat,unlikethestack,thecompilerdoesntneedtoknowhowmuchstorageitneedstoallocatefromtheheaporhowlongthatstoragemuststayontheheap.Thus,theresagreatdealofflexibilityinusingstorageontheheap.Wheneveryouneedtocreateanobject,yousimplywritethecodetocreateitbyusingnew,andthestorageisallocatedontheheapwhenthatcodeisexecuted.Ofcoursetheresapriceyoupayforthisflexibility.Ittakesmoretimetoallocateheapstoragethanitdoestoallocatestackstorage(ifyouevencouldcreateobjectsonthestackinJava,asyoucaninC+).Staticstorage.“Static”isusedhereinthesenseof“inafixedlocation”(althoughitsalsoinRAM).Staticstoragecontainsdatathatisavailablefortheentiretimeaprogramisrunning.Youcanusethestatickeywordtospecifythataparticularelementofanobjectisstatic,butJavaobjectsthemselvesareneverplacedinstaticstorage.Constantstorage.Constantvaluesareoftenplaceddirectlyintheprogramcode,whichissafesincetheycanneverchange.Sometimesconstantsarecordonedoffbythemselvessothattheycanbeoptionallyplacedinread-onlymemory(ROM),inembeddedsystems.Non-RAMstorage.Ifdatalivescompletelyoutsideaprogram,itcanexistwhiletheprogramisnotrunning,outsidethecontroloftheprogram.Thetwoprimaryexamplesofthisarestreamedobjects,inwhichobjectsareturnedintostreamsofbytes,generallytobesenttoanothermachine,andpersistentobjects,inwhichtheobjectsareplacedondisksotheywillholdtheirstateevenwhentheprogramisterminated.Thetrickwiththesetypesofstorageisturningtheobjectsintosomethingthatcanexistontheothermedium,andyetcanberesurrectedintoaregularRAM-basedobjectwhennecessary.Javaprovidessupportforlightweightpersistence,andfutureversionsofJavamightprovidemorecompletesolutionsforpersistence.Specialcase:primitivetypesOnegroupoftypes,whichyoullusequiteofteninyourprogramming,getsspecialtreatment.Youcanthinkoftheseas“primitive”types.Thereasonforthespecialtreatmentisthattocreateanobjectwithnewespeciallyasmall,simplevariableisntveryefficient,becausenewplacesobjectsontheheap.ForthesetypesJavafallsbackontheapproachtakenbyCandC+.Thatis,insteadofcreatingthevariablebyusingnew,an“automatic”variableiscreatedthatisnotareference.Thevariableholdsthevalue,anditsplacedonthestack,soitsmuchmoreefficient.Javadeterminesthesizeofeachprimitivetype.Thesesizesdontchangefromonemachinearchitecturetoanotherastheydoinmostlanguages.ThissizeinvarianceisonereasonJavaprogramsareportable.PrimitivetypeSizeMinimumMaximumWrappertypebooleanBooleanchar16-bitUnicode0Unicode216-1Characterbyte8-bit-128+127Byteshort16-bit-215+2151Shortint32-bit-231+2311Integerlong64-bit-263+2631Longfloat32-bitIEEE754IEEE754Floatdouble64-bitIEEE754IEEE754DoublevoidVoidAllnumerictypesaresigned,sodontlookforunsignedtypes.Thesizeofthebooleantypeisnotexplicitlyspecified;itisonlydefinedtobeabletotaketheliteralvaluestrueorfalse.The“wrapper”classesfortheprimitivedatatypesallowyoutomakeanonprimitiveobjectontheheaptorepresentthatprimitivetype.Forexample:charc=x;CharacterC=newCharacter(c);Oryoucouldalsouse:CharacterC=newCharacter(x);Thereasonsfordoingthiswillbeshowninalaterchapter.High-precisionnumbersJavaincludestwoclassesforperforminghigh-precisionarithmetic:BigIntegerandBigDecimal.Althoughtheseapproximatelyfitintothesamecategoryasthe“wrapper”classes,neitheronehasaprimitiveanalogue.Bothclasseshavemethodsthatprovideanaloguesfortheoperationsthatyouperformonprimitivetypes.Thatis,youcandoanythingwithaBigIntegerorBigDecimalthatyoucanwithanintorfloat,itsjustthatyoumustusemethodcallsinsteadofoperators.Also,sincetheresmoreinvolved,theoperationswillbeslower.Youreexchangingspeedforaccuracy.BigIntegersupportsarbitrary-precisionintegers.Thismeansthatyoucanaccuratelyrepresentintegralvaluesofanysizewithoutlosinganyinformationduringoperations.BigDecimalisforarbitrary-precisionfixed-pointnumbers;youcanusetheseforaccuratemonetarycalculations,forexample.ConsulttheJDKdocumentationfordetailsabouttheconstructorsandmethodsyoucancallforthesetwoclasses.ArraysinJavaVirtuallyallprogramminglanguagessupportarrays.UsingarraysinCandC+isperilousbecausethosearraysareonlyblocksofmemory.Ifaprogramaccessesthearrayoutsideofitsmemoryblockorusesthememorybeforeinitialization(commonprogrammingerrors),therewillbeunpredictableresults.OneoftheprimarygoalsofJavaissafety,somanyoftheproblemsthatplagueprogrammersinCandC+arenotrepeatedinJava.AJavaarrayisguaranteedtobeinitializedandcannotbeaccessedoutsideofitsrange.Therangecheckingcomesatthepriceofhavingasmallamountofmemoryoverheadoneacharrayaswellasverifyingtheindexatruntime,buttheassumptionisthatthesafetyandincreasedproductivityisworththeexpense.Whenyoucreateanarrayofobjects,youarereallycreatinganarrayofreferences,andeachofthosereferencesisautomaticallyinitializedtoaspecialvaluewithitsownkeyword:null.WhenJavaseesnull,itrecognizesthatthereferenceinquestionisntpointingtoanobject.Youmustassignanobjecttoeachreferencebeforeyouuseit,andifyoutrytouseareferencethatsstillnull,theproblemwillbereportedatruntime.Thus,typicalarrayerrorsarepreventedinJava.Youcanalsocreateanarrayofprimitives.Again,thecompilerguaranteesinitializationbecauseitzeroesthememoryforthatarray.Arrayswillbecoveredindetailinlaterchapters.YouneverneedtodestroyanobjectInmostprogramminglanguages,theconceptofthelifetimeofavariableoccupiesasignificantportionoftheprogrammingeffort.Howlongdoesthevariablelast?Ifyouaresupposedtodestroyit,whenshouldyou?Confusionovervariablelifetimescanleadtoalotofbugs,andthissectionshowshowJavagreatlysimplifiestheissuebydoingallthecleanupworkforyou.ScopingMostprocedurallanguageshavetheconceptofscope.Thisdeterminesboththevisibilityandlifetimeofthenamesdefinedwithinthatscope.InC,C+,andJava,scopeisdeterminedbytheplacementofcurlybraces.Soforexample:intx=12;/Onlyxavailableintq=96;/Bothx&qavailable/Onlyxavailable/q“outofscope”Avariabledefinedwithinascopeisavailableonlytotheendofthatscope.Anytextaftera/totheendofalineisacomment.IndentationmakesJavacodeeasiertoread.SinceJavaisafree-formlanguage,theextraspaces,tabs,andcarriagereturnsdonotaffecttheresultingprogram.Notethatyoucannotdothefollowing,eventhoughitislegalinCandC+:intx=12;intx=96;/IllegalThecompilerwillannouncethatthevariablexhasalreadybeendefined.ThustheCandC+abilityto“hide”avariableinalargerscopeisnotallowed,becausetheJavadesignersthoughtthatitledtoconfusingprograms.ScopeofobjectsJavaobjectsdonothavethesamelifetimesasprimitives.WhenyoucreateaJavaobjectusingnew,ithangsaroundpasttheendofthescope.Thusifyouuse:Strings=newString(astring);/EndofscopeThereferencesvanishesattheendofthescope.However,theStringobjectthatswaspointingtoisstilloccupyingmemory.Inthisbitofcode,thereisnowaytoaccesstheobject,becausetheonlyreferencetoitisoutofscope.Inlaterchaptersyoullseehowthereferencetotheobjectcanbepassedaroundandduplicatedduringthecourseofaprogram.Itturnsoutthatbecauseobjectscreatedwithnewstayaroundforaslongasyouwantthem,awholeslewofC+programmingproblemssimplyvanishinJava.ThehardestproblemsseemtooccurinC+becauseyoudontgetanyhelpfromthelanguageinmakingsurethattheobjectsareavailablewhentheyreneeded.Andmoreimportant,inC+youmustmakesurethatyoudestroytheobjectswhenyouredonewiththem.Thatbringsupaninterestingquestion.IfJavaleavestheobjectslyingaround,whatkeepsthemfromfillingupmemoryandhaltingyourprogram?ThisisexactlythekindofproblemthatwouldoccurinC+.Thisiswhereabitofmagichappens.Javahasagarbagecollector,whichlooksatalltheobjectsthatwerecreatedwithnewandfiguresoutwhichonesarenotbeingreferencedanymore.Thenitreleasesthememoryforthoseobjects,sothememorycanbeusedfornewobjects.Thismeansthatyouneverneedtoworryaboutreclaimingmemoryyourself.Yousimplycreateobjects,andwhenyounolongerneedthem,theywillgoawaybythemselves.Thiseliminatesacertainclassofprogrammingproblem:theso-called“memoryleak,”inwhichaprogrammerforgetstoreleasememory.Creatingnewdatatypes:classIfeverythingisanobject,whatdetermineshowaparticularclassofobjectlooksandbehaves?Putanotherway,whatestablishesthetypeofanobject?Youmightexpecttheretobeakeywordcalled“type,”andthatcertainlywouldhavemadesense.Historically,however,mostobject-orientedlanguageshaveusedthekeywordclasstomean“Imabouttotellyouwhatanewtypeofobjectlookslike.”Theclasskeyword(whichissocommonthatitwillnotbebold-facedthroughoutthisbook)isfollowedbythenameofthenewtype.Forexample:classATypeName/*Classbodygoeshere*/Thisintroducesanewtype,althoughtheclassbodyconsistsonlyofacomment(thestarsandslashesandwhatisinside,whichwillbediscussedlaterinthischapter),sothereisnottoomuchthatyoucandowithit.However,youcancreateanobjectofthistypeusingnew:ATypeNamea=newATypeName();Butyoucannottellittodomuchofanything(thatis,youcannotsenditanyinterestingmessages)untilyoudefinesomemethodsforit.FieldsandmethodsWhenyoudefineaclass(andallyoudoinJavaisdefineclasses,makeobjectsofthoseclasses,andsendmessagestothoseobjects),youcanputtwotypesofelementsinyourclass:fields(sometimescalleddatamembers),andmethods(sometimescalledmemberfunctions).Afieldisanobjectofanytypethatyoucancommunicatewithviaitsreference.Itcanalsobeoneoftheprimitivetypes(whichisntareference).Ifitisareferencetoanobject,youmustinitializethatreferencetoconnectittoanactualobject(usingnew,asseenearlier)inaspecialmethodcalledaconstructor(describedfullyinChapter4).Ifitisaprimitivetype,youcaninitializeitdirectlyatthepointofdefinitionintheclass.(Asyoullseelater,referencescanalsobeinitializedatthepointofdefinition.)Eachobjectkeepsitsownstorageforitsfields;thefieldsarenotsharedamongobjects.Hereisanexampleofaclasswithsomefields:classDataOnlyinti;floatf;booleanb;Thisclassdoesntdoanything,butyoucancreateanobject:DataOnlyd=newDataOnly();Youcanassignvaluestothefields,butyoumustfirstknowhowtorefertoamemberofanobject.Thisisaccomplishedbystatingthenameoftheobjectreference,followedbyaperiod(dot),followedbythenameofthememberinsidetheobject:objectReference.memberForexample:d.i=47;d.f=1.1f;/fafternumberindicatesfloatconstantd.b=false;Itisalsopossiblethatyourobjectmightcontainotherobjectsthatcontaindatayoudliketomodify.Forthis,youjustkeep“connectingthedots.”Forexample:myPlane.leftTank.capacity=100;TheDataOnlyclasscannotdomuchofanythingexceptholddata,becauseithasnomethods.Tounderstandhowthosework,youmustfirstunderstandargumentsandreturnvalues,whichwillbedescribedshortly.DefaultvaluesforprimitivemembersWhenaprimitivedatatypeisamemberofaclass,itisguaranteedtogetadefaultvalueifyoudonotinitializeit:PrimitivetypeDefaultbooleanfalsecharu0000(null)byte(byte)0short(short)0int0long0Lfloat0.0fdouble0.0dNotecarefullythatthedefaultvaluesarewhatJavaguaranteeswhenthevariableisusedasamemberofaclass.Thisensuresthatmembervariablesofprimitivetypeswillalwaysbeinitialized(somethingC+doesntdo),reducingasourceofbugs.However,thisinitialvaluemaynotbecorrectorevenlegalfortheprogramyouarewriting.Itsbesttoalwaysexplicitlyinitializeyourvariables.Thisguaranteedoesntapplyto“local”variablesthosethatarenotfieldsofaclass.Thus,ifwithinamethoddefinitionyouhave:intx;Thenxwillgetsomearbitraryvalue(asinCandC+);itwillnotautomaticallybeinitializedtozero.Youareresponsibleforassigninganappropriatevaluebeforeyouusex.Ifyouforget,JavadefinitelyimprovesonC+:yougetacompile-timeerrortellingyouthevariablemightnothavebeeninitialized.(ManyC+compilerswillwarnyouaboutuninitializedvariables,butinJavatheseareerrors.)Methods,arguments,andreturnvaluesInmanylanguages(likeCandC+),thetermfunctionisusedtodescribeanamedsubroutine.ThetermthatismorecommonlyusedinJavaismethod,asin“awaytodosomething.”Ifyouwant,youcancontinuethinkingintermsoffunctions.Itsreallyonlyasyntacticdifference,butthisbookfollowsthecommonJavausageoftheterm“method.”MethodsinJavadeterminethemessagesanobjectcanreceive.Inthissectionyouwilllearnhowsimpleitistodefineamethod.Thefundamentalpartsofamethodarethename,thearguments,thereturntype,andthebody.Hereisthebasicform:returnTypemethodName(/*Argumentlist*/)/*Methodbody*/Thereturntypeisthetypeofthevaluethatpopsoutofthemethodafteryoucallit.Theargumentlistgivesthetypesandnamesfortheinformationyouwanttopassintothemethod.Themethodnameandargumentlisttogetheruniquelyidentifythemethod.MethodsinJavacanbecreatedonlyaspartofaclass.Amethodcanbecalledonlyforanobject,11andthatobjectmustbeabletoperformthatmethodcall.Ifyoutrytocallthewrongmethodforanobject,youllgetanerrormessageatcompiletime.Youcallamethodforanobjectbynamingtheobjectfollowedbyaperiod(dot),followedbythenameofthemethodanditsargumentlist,likethis:objectName.methodName(arg1,arg2,arg3);Forexample,supposeyouhaveamethodf()thattakesnoargumentsandreturnsavalueoftypeint.Then,ifyouhaveanobjectcalledaforwhichf()canbecalled,youcansaythis:intx=a.f();Thetypeofthereturnvaluemustbecompatiblewiththetypeofx.Thisactofcallingamethodiscommonlyreferredtoassendingamessagetoanobject.Intheprecedingexample,themessageisf()andtheobjectisa.Object-orientedprogrammingisoftensummarizedassimply“sendingmessagestoobjects.”TheargumentlistThemethodargumentlistspecifieswhatinformationyoupassintothemethod.Asyoumightguess,thisinformationlikeeverythingelseinJavatakestheformofobjects.So,whatyoumustspecifyintheargumentlistarethetypesoftheobjectstopassinandthenametouseforeachone.AsinanysituationinJavawhereyouseemtobehandingobjectsaround,youareactuallypassingreferences.12Thetypeofthereferencemustbecorrect,however.IftheargumentissupposedtobeaString,youmustpassinaStringorthecompilerwillgiveanerror.ConsideramethodthattakesaStringasitsargument.Hereisthedefinition,whichmustbeplacedwithinaclassdefinitionforittobecompiled:intstorage(Strings)returns.length()*2;ThismethodtellsyouhowmanybytesarerequiredtoholdtheinformationinaparticularString.(EachcharinaStringis16bits,ortwobytes,long,tosupportUnicodecharacters.)TheargumentisoftypeStringandiscalleds.Oncesispassedintothemethod,youcantreatitjustlikeanyotherobject.(Youcansendmessagestoit.)Here,thelength()methodiscalled,whichisoneofthemethodsforStrings;itreturnsthenumberofcharactersinastring.Youcanalsoseetheuseofthereturnkeyword,whichdoestwothings.First,itmeans“leavethemethod,Imdone.”Second,ifthemethodproducesavalue,thatvalueisp

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论