




已阅读5页,还剩33页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
0附件:外文原文Firstliterature:EverythingisanObjectAlthoughitisbasedonC+,Javaismoreofa“pure”object-orientedlanguage.BothC+andJavaarehybridlanguages,butinJavathedesignersfeltthatthehybridizationwasnotasimportantasitwasinC+.Ahybridlanguageallowsmultipleprogrammingstyles;thereasonC+ishybridistosupportbackwardcompatibilitywiththeClanguage.BecauseC+isasupersetoftheClanguage,itincludesmanyofthatlanguagesundesirablefeatures,whichcanmakesomeaspectsofC+overlycomplicated.TheJavalanguageassumesthatyouwanttodoonlyobject-orientedprogramming.Thismeansthatbeforeyoucanbeginyoumustshiftyourmindsetintoanobject-orientedworld(unlessitsalreadythere).ThebenefitofthisinitialeffortistheabilitytoprograminalanguagethatissimplertolearnandtousethanmanyotherOOPlanguages.InthischapterwellseethebasiccomponentsofaJavaprogramandwelllearnthateverythinginJavaisanobject,evenaJavaprogram.YoumanipulateobjectwithreferencesEachprogramminglanguagehasitsownmeansofmanipulatingdata.Sometimestheprogrammermustbeconstantlyawareofwhattypeofmanipulationisgoingon.Areyoumanipulatingtheobjectdirectly,orareyoudealingwithsomekindofindirectrepresentation(apointerinCorC+)thatmustbetreatedwithaspecialsyntax?AllthisissimplifiedinJava.Youtreateverythingasanobject,usingasingleconsistentsyntax.Althoughyoutreateverythingasanobject,theidentifieryoumanipulateisactuallya“reference”toanobject.Youmightimaginethissceneasatelevision(theobject)withyourremotecontrol(thereference).Aslongasyoureholdingthisreference,youhaveaobjectconnectedtoit.Soifyouwanttoholdawordorsentence,youcreateaStringreference:Strings;Buthereyouvecreatedonlythereference,notanobject.Ifyoudecidedtosendamessagetosatthispoint,youllgetanerror(atruntime)becausesisntactuallyattachedtoanything(theresnotelevision).Asaferpractice,then,isalwaystoinitializea1referencewhenyoucreateit: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.Itsusefultovisualizesomeaspectsofhowthingsarelaidoutwhiletheprogramisrunninginparticularhowmemoryisarranged.Therearesixdifferentplacestostoredata:1.Registers.Thisisthefasteststoragebecauseitexistsinaplacedifferentfromthatofotherstorage:insidetheprocessor.However,thenumberofregistersisseverelylimited,soregistersareallocatedbythecompileraccordingtoitsneeds.Youdonthavedirectcontrol,nordoyouseeanyevidenceinyourprogramsthatregistersevenexist.2.Thestack.Thislivesinthegeneralrandom-accessmemory(RAM)area,buthasdirectsupportfromtheprocessorviaitsstackpointer.Thestackpointerismoveddowntocreatenewmemoryandmoveduptoreleasethatmemory.Thisisanextremelyfastandefficientwaytoallocatestorage,secondonlytoregisters.TheJavacompilermustknow,whileitiscreatingtheprogram,theexactsizeandlifetimeofallthedatathatisstoredonthestack,becauseitmustgeneratethecodetomovethestackpointerupanddown.Thisconstraintplaceslimitsontheflexibilityofyourprograms,sowhilesomeJavastorageexistsonthestackinparticular,objectreferencesJavaobjectsthemselvesarenotplacedonthestack.23.Theheap.Thisisageneral-purposepoolofmemory(alsointheRAMarea)whereallJavaobjectslive.Thenicethingabouttheheapisthat,unlikethestack,thecompilerdoesntneedtoknowhowmuchstorageitneedstoallocatefromtheheaporhowlongthatstoragemuststayontheheap.Thus,theresagreatdealofflexibilityinusingstorageontheheap.Wheneveryouneedtocreateanobject,yousimplywritethecodetocreateitbyusingnew,andthestorageisallocatedontheheapwhenthatcodeisexecuted.Ofcoursetheresapriceyoupayforthisflexibility.Ittakesmoretimetoallocateheapstoragethanitdoestoallocatestackstorage(ifyouevencouldcreateobjectsonthestackinJava,asyoucaninC+).4.Staticstorage.“Static”isusedhereinthesenseof“inafixedlocation”(althoughitsalsoinRAM).Staticstoragecontainsdatathatisavailablefortheentiretimeaprogramisrunning.Youcanusethestatickeywordtospecifythataparticularelementofanobjectisstatic,butJavaobjectsthemselvesareneverplacedinstaticstorage.5.Constantstorage.Constantvaluesareoftenplaceddirectlyintheprogramcode,whichissafesincetheycanneverchange.Sometimesconstantsarecordonedoffbythemselvessothattheycanbeoptionallyplacedinread-onlymemory(ROM),inembeddedsystems.6.Non-RAMstorage.Ifdatalivescompletelyoutsideaprogram,itcanexistwhiletheprogramisnotrunning,outsidethecontroloftheprogram.Thetwoprimaryexamplesofthisarestreamedobjects,inwhichobjectsareturnedintostreamsofbytes,generallytobesenttoanothermachine,andpersistentobjects,inwhichtheobjectsareplacedondisksotheywillholdtheirstateevenwhentheprogramisterminated.Thetrickwiththesetypesofstorageisturningtheobjectsintosomethingthatcanexistontheothermedium,andyetcanberesurrectedintoaregularRAM-basedobjectwhennecessary.Javaprovidessupportforlightweightpersistence,andfutureversionsofJavamightprovidemorecompletesolutionsforpersistence.Specialcase:primitivetypes3Onegroupoftypes,whichyoullusequiteofteninyourprogramming,getsspecialtreatment.Youcanthinkoftheseas“primitive”veryefficient,becausenewplacesobjectsontheheap.ForthesetypesJavafallsbackontheapproachtakenbyCandC+.Thatis,insteadofcreatingthevariablebyusingnew,an“automatic”variableiscreatedthatisnotareference.Thevariableholdsthevalue,anditsplacedonthestack,soitsmuchmoreefficient.Javadeterminesthesizeofeachprimitivetype.Thesesizesdontchangefromonemachinearchitecturetoanotherastheydoinmostlanguages.ThissizeinvarianceisonereasonJavaprogramsareportable.Allnumerictypesaresigned,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.4BigIntegersupportsarbitrary-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.Youneverneedtodestroyanobject5Inmostprogramminglanguages,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,thextraspaces,tabs,andcarriagereturnsdonotaffecttheresultingprogram.Notethatyoucannotdothefollowing,eventhoughitislegalinCandC+:intx=12;intx=96;/IllegalThecompilerwillannouncethatthevariablexhasalreadybeendefined.ThustheCandC+abilityto“hide”avariableinalargerscopeisnotallowed,becausetheJavadesigners6thoughtthatitledtoconfusingprograms.ScopeofobjectsJavaobjectsdonothavethesamelifetimesasprimitives.WhenyoucreateaJavaobjectusingnew,ithangsaroundpasttheendofthescope.Thusifyouuse:Strings=newString(astring);/Endofscopethereferencesvanishesattheendofthescope.However,theStringobjectthatswaspointingtoisstilloccupyingmemory.Inthisbitofcode,thereisnowaytoaccesstheobject,becausetheonlyreferencetoitisoutofscope.Inlaterchaptersyoullseehowthereferencetotheobjectcanbepassedaroundandduplicatedduringthecourseofaprogram.Itturnsoutthatbecauseobjectscreatedwithnewstayaroundforaslongasyouwantthem,awholeslewofC+programmingproblemssimplyvanishinJava.ThehardestproblemsseemtooccurinC+becauseyoudontgetanyhelpfromthelanguageinmakingsurethattheobjectsareavailablewhentheyreneeded.Andmoreimportant,inC+youmustmakesurethatyoudestroytheobjectswhenyouredonewiththem.Secondliterature:TheJavaI/OSystemCreatingagoodinput/output(I/O)systemisoneofthemoredifficulttasksforthelanguagedesigner.Thisisevidencedbythenumberofdifferentapproaches.Thechallengeseemstobeincoveringalleventualities.NotonlyaretheredifferentsourcesandsinksofI/Othatyouwanttocommunicatewith(files,theconsole,networkconnections,etc.),butyouneedtotalktotheminawidevarietyofways(sequential,random-access,buffered,binary,character,bylines,bywords,etc.).7TheJavalibrarydesignersattackedthisproblembycreatinglotsofclasses.Infact,therearesomanyclassesforJavasI/Osystemthatitcanbeintimidatingatfirst(ironically,theJavaI/Odesignactuallypreventsanexplosionofclasses).TherewasalsoasignificantchangeintheI/OlibraryafterJava1.0,whentheoriginalbyte-orientedlibrarywassupplementedwithchar-oriented,Unicode-basedI/Oclasses.InJDK1.4,thenioclasses(for“newI/O,”anamewellstillbeusingyearsfromnow)wereaddedforimprovedperformanceandfunctionality.Asaresult,thereareafairnumberofclassestolearnbeforeyouunderstandenoughofJavasI/Opicturethatyoucanuseitproperly.Inaddition,itsratherimportanttounderstandtheevolutionhistoryoftheI/Olibrary,evenifyourfirstreactionis“dontbothermewithhistory,justshowmehowtouseit!”Theproblemisthatwithoutthehistoricalperspective,youwillrapidlybecomeconfusedwithsomeoftheclassesandwhenyoushouldandshouldntusethem.ThischapterwillgiveyouanintroductiontothevarietyofI/OclassesinthestandardJavalibraryandhowtousethem.TheFileclassBeforegettingintotheclassesthatactuallyreadandwritedatatostreams,welllookatautilityprovidedwiththelibrarytoassistyouinhandlingfiledirectoryissues.TheFileclasshasadeceivingname;youmightthinkitreferstoafile,butitdoesnt.Itcanrepresenteitherthenameofaparticularfileorthenamesofasetoffilesinadirectory.Ifitsasetoffiles,youcanaskforthatsetusingthelist()method,whichreturnsanarrayofString.Itmakessensetoreturnanarrayratherthanoneoftheflexiblecontainerclasses,becausethenumberofelementsisfixed,andifyouwantadifferentdirectorylisting,youjustcreateadifferentFileobject.Infact,“FilePath”wouldhavebeenabetternamefortheclass.Thissectionshowsanexampleoftheuseofthisclass,includingtheassociatedFilenameFilterinterface.AdirectorylisterSupposeyoudliketoseeadirectorylisting.TheFileobjectcanbelistedintwoways.If8youcalllist()withnoarguments,youllgetthefulllistthattheFileobjectcontains.However,ifyouwantarestrictedlistforexample,ifyouwantallofthefileswithanextensionof.javathenyouusea“directoryfilter,”whichisaclassthattellshowtoselecttheFileobjectsfordisplay.Heresthecodefortheexample.Notethattheresulthasbeeneffortlesslysorted(alphabetically)usingthejava.utils.Arrays.sort()methodandtheAlphabeticComparatorTheDirFilterclass“implements”theinterfaceFilenameFilter.ItsusefultoseehowsimpletheFilenameFilterinterfaceis:publicinterfaceFilenameFilterbooleanaccept(Filedir,Stringname);Itsaysallthatthistypeofobjectdoesisprovideamethodcalledaccept().Thewholereasonbehindthecreationofthisclassistoprovidetheaccept()methodtothelist()methodsothatlist()can“callback”accept()todeterminewhichfilenamesshouldbeincludedinthelist.Thus,Thirdliterature:Java2MicroEditionandtheWorldofJava1IntroductionThecomputerrevolutionofthe1970sincreasedthedemandforsophisticatedcomputersoftwaretotakeadvantageoftheever-increasingcapacityofcomputerstoprocessdata.TheCprogramminglanguagebecamethelinchpinthatenabledprogrammerstobuildsoftwarethatwasjustasrobustasthecomputeritranon.Asthe1980sapproached,programmerswerewitnessinganotherspurtintheevolutionofprogramminglanguage.ComputertechnologyadvancedbeyondthecapabilitiesoftheCprogramminglanguage.Theproblemwasntnew.Itoccurredpreviouslyandcausedthedemiseofgenerationsofprogramminglanguages.Theproblemwasthatprogramswerebecomingtoocomplicatedtodesign,write,andmanagetokeepupwiththecapabilitiesofcomp9uters.ItwasaroundthistimethatadesignconceptbasedonSimula67andSmalltalk(fromthelate1960s)movedprogrammingtothenextevolutionarystep.Thiswastheperiodwhenobject-orientedprogramming(OOP),andwithitanewprogramminglanguagecalledC+,tookprogrammersbystorm.In1979,BjarneStroustrupofBellLaboratoriesinNewJerseyenhancedtheCprogramminglanguagetoincludeobject-orientedfeatures.HecalledthelanguageC+.(The+istheincrementaloperatorintheCprogramminglanguage.)C+istrulyanenhancementoftheCprogramminglanguage,anditbeganasapreprocessorlanguagethatwastranslatedintoCsyntaxbeforetheprogramwasprocessedbythecompiler.Stroustrupbuiltontheconceptofaclass(takenfromSimula67andSmalltalk),fromwhichinstancesofobjectsarecreated.Aclasscontainsdatamembersandmemberfunctionsthatdefineanobjectsdataandfunctionality.Healsointroducedtheconceptofinheritance,whichenabledaclasstoinheritsomeoralldatamembersandmemberfunctionsfromoneormoreotherclassesallofwhichcomplementstheconceptsofobject-orientedprogramming.By1988,ANSIofficialsstandardizedStroustrupsC+specification.2EnterJavaJustasC+wasbecomingthelanguageofchoiceforbuildingindustrial-strengthapplications,anothergrowthspurtintheevolutionofprogramminglanguagewasbudding,fertilizedbythelatestdisruptivetechnologytheWorldWideWeb.TheInternethadbeenawell-keptsecretfordecadesbeforetheNationalScienceFoundation(whooversawtheInternet)removedbarriersthatpreventedcommercialization.Until1991whenitwasopenedtocommerce,theInternetwasthealmostexclusivedomainofgovernmentagenciesandtheacademiccommunity.Oncethebarriertocommercializationwaslifted,theWorldWideWeb10oneofseveralservicesofferedontheInternetbecameavirtualcommunitycenterwherevisitorscouldgetfreeinformationaboutpracticallyanythingandbrowsethroughthousandsofvirtualstores.BrowserspowertheWorldWideWeb.AbrowsertranslatesASCIItextfileswritteninHTMLintoaninteractivedisplaythatcanbeinterpretedonanymachine.AslongasthebrowseriscompatiblewiththecorrectversionofHTMLandHTTPimplementation,anycomputerrunningthebrowsercanusethesameHTMLdocumentwithouthavingtomodifyitforaparticulartypeofcomputer,whichwassomethingunheardofatthetime.ProgramswritteninCorC+aremachinedependentandcannotrunonadifferentmachineunlesstheprogramisrecompiled.ThesuccessoftheInternetgaverenewedfocustodevelopingamachine-independentprogramminglanguage.AndthesameyeartheInternetwascommercialized,fivetechnologistsatSunMicrosystemssetouttodojustthat.JamesGosling,PatrickNaughton,ChrisWarth,EdFrank,andMikeSheridanspent18monthsdevelopingtheprogramminglanguagetheycalledOak,whichwasrenamedJavawhenthisnewlanguagemadeitsdebutin1995.Javawentthroughnumerousiterationsbetween1991and1995,duringwhichtimemanyothertechnologistsatSunmadesubstantialcontributionstothelanguage.TheseincludedBillJoy,ArthurvanHoff,JonathanPayne,FrankYelin,andTimLindholm.AlthoughJavaiscloselyassociatedwiththeInternet,itwasdevelopedasalanguageforprogrammingsoftwarethatcouldbeembeddedintoelectronicdevicesregardlessofthetypeofCPUsedbythedevice.ThisisknownastheEmbeddedJavaplatformandisincontinuoususetodayforclosedsystems.TheJavateamfromSunsucceededincreatingaportableprogramminglanguage,somethingthathadeludedprogrammerssincecomputerswerefirstprogrammed.Theirsuccess,however,wasfarbeyondtheirwildestdreams.ThesameconceptusedtomakeJavaprogramsportabletoelectronicdevicesalsocouldbeusedtomakeJavaprogramsrunoncomputersrunningMicrosoftWindows,UNIX,andMacintosh.Timingwasperfect.TheInternet/intr11anethadwhettedcorporateAmericasappetiteforcost-effective,portableprogramsthatcouldreplacemission-criticalapplicationswithinthecorporation.AndJavahadprovenitselfasaprogramminglanguageusedtosuccessfullydevelopmachine-independentapplications.3JavaVirtualMachineWritingJavaprogramsissimilartowritingC+programsinthattheprogrammerwritessourcecodethatcontainsinstructionsintoaneditor,orinanintegrateddevelopmentenvironment,andthenthesourcecodei
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 六一采购活动方案
- 六一骑车比赛活动方案
- 六年级丢沙包活动方案
- 医师卫生职称考试试题及答案
- 夜班准入考试试题及答案
- 安全生产a证试题及答案
- 业务党校考试试题及答案
- 药店考试试题及答案失眠
- 六盘水景区开展活动方案
- 兰州游玩六一活动方案
- 广西《淡水水产养殖尾水排放标准》编制说明
- 认知能力评估体系-全面剖析
- 围棋行业跨境出海战略研究报告
- 附件-珠海市职业卫生分类及分级管理办法
- 第三单元名著导读《骆驼祥子》教学设计 2023-2024学年统编版语文七年级上册
- 针灸理疗科绩效工资二次考核分配方案
- 2025年中考复习地理简答题模板
- 新人教版九年级数学第一轮总复习教案1
- 2024年1月国家开放大学汉语言文学本科《中国当代文学专题》期末纸质考试试题及答案
- 2023年四川省资阳市中考物理试题【含答案、解析】
- 物业电工笔试试题及答案
评论
0/150
提交评论