




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
chapter2programminglanguage2.1ComputerProgramAcomputerprogramisasetofinstructionsthatdirectsacomputertoperformsomeprocessingfunctionorcombinationoffunctions.Fortheinstructionstobecarriedout,acomputermustexecuteaprogram,thatis,thecomputerreadstheprogram,andthenfollowsthestepsencodedintheprograminapreciseorderuntilcompletion.Aprogramcanbeexecutedmanydifferenttimes,witheachexecutionyieldingapotentiallydifferentresultdependingupontheoptionsanddatathattheusergivesthecomputer.Programsfallintotwomajorclasses:applicationprogramsandoperatingsystems.Withthetexteditor,theprogrammercreatesatextfile,whichisanorderedlistofinstructions,alsocalledtheprogramsourcefile.Theindividualinstructionsthatmakeuptheprogramsourcefilearecalledsourcecode.Atthispoint,aspecialapplicationsprogramtranslatesthesourcecodeintomachinelanguage,orobjectcode—aformatthattheoperatingsystemwillrecognizeasaproperprogramandbeabletoexecute.Threetypesofapplicationsprogramstranslatefromsourcecodetoobjectcode:compilers,interpreters,andassemblers.Thethreeoperatedifferentlyandondifferenttypesofprogramminglanguages,buttheyservethesamepurposeoftranslatingfromaprogramminglanguageintomachinelanguage.Acompilertranslatestextfileswritteninahigh-levelprogramminglanguage—suchasFORTRAN,C,orPascal—fromthesourcecodetotheobjectcodeallatonce.ThisdiffersfromtheapproachtakenbyinterpretedlanguagessuchasBASIC,inwhichaprogramistranslatedintoobjectcodestatementbystatementaseachinstructionisexecuted.Theadvantageofinterpretedlanguagesisthattheycanbeginexecutingtheprogramimmediatelyinsteadofhavingtowaitforallofthesourcecodetobecompiled.Changescanalsobemadetotheprogramfairlyquicklywithouthavingtowaitforittobecompiledagain.Thedisadvantageofinterpretedlanguagesisthattheyareslowtoexecute,sincetheentireprogrammustbetranslatedoneinstructionatatime,eachtimetheprogramisrun.Ontheotherhand,compiledlanguagesarecompiledonlyonceandthuscanbeexecutedbythecomputermuchmorequicklythaninterpretedlanguages.Forthisreason,compiledlanguagesaremorecommonandarealmostalwaysusedinprofessionalandscientificapplications.
Anothertypeoftranslatoristheassembler,whichisusedforprogramsorpartsofprogramswritteninassemblylanguage.Assemblylanguageisanotherprogramminglanguage,butitismuchmoresimilartomachinelanguagethanothertypesofhigh-levellanguages.Inassemblylanguage,asinglestatementcanusuallybetranslatedintoasingleinstructionofmachinelanguage.Today,assemblylanguageisrarelyusedtowriteanentireprogram,butisinsteadmostoftenusedwhentheprogrammerneedstodirectlycontrolsomeaspectofthecomputer’sfunction.
Programsareoftenwrittenasasetofsmallerpieces,8witheachpiecerepresentingsomeaspectoftheoverallapplicationprogram.Aftereachpiecehasbeencompiledseparately,aprogramcalledalinkercombinesallofthetranslatedpiecesintoasingleexecutableprogram.Programsseldomworkcorrectlythefirsttime,soaprogramcalledadebuggerisoftenusedtohelpfindproblemscalledbugs.Debuggingprogramsusuallydetectaneventintheexecutingprogramandpointtheprogrammerbacktotheoriginoftheeventintheprogramcode.Recentprogrammingsystems,suchasJava,useacombinationofapproachestocreateandexecuteprograms.AcompilertakesaJavasourceprogramandtranslatesitintoanintermediateform.SuchintermediateprogramsarethentransferredovertheInternetintocomputerswhereaninterpreterprogramthenexecutestheintermediateformasanapplicationprogram.Ⅱ.ProgramElementsMostprogramsarebuiltfromjustafewkindsofstepsthatarerepeatedmanytimesindifferentcontextsandindifferentcombinationsthroughouttheprogram.Themostcommonstepperformssomecomputation,andthenproceedstothenextstepintheprogram,intheorderspecifiedbytheprogrammer.Programsoftenneedtorepeatashortseriesofstepsmanytimes,forinstanceinlookingthroughalistofgamescoresandfindingthehighestscore.Suchrepetitivesequencesofcodearecalledloops.Oneofthecapabilitiesthatmakecomputerssousefulistheirabilitytomakeconditionaldecisionsandperformdifferentinstructionsbasedonthevaluesofdatabeingprocessed.If-then-elsestatementsimplementthisfunctionbytestingsomepieceofdataandthenselectingoneoftwosequencesofinstructionsonthebasisoftheresult.Oneoftheinstructionsinthesealternativesmaybeagotostatementthatdirectsthecomputertoselectitsnextinstructionfromadifferentpartoftheprogram.Forexample,aprogrammightcomparetwonumbersandbranchtoadifferentpartoftheprogramdependingontheresultofthecomparison:ifxisgreatthanythengotoinstruction#10elsecontinueProgramsoftenuseaspecificsequenceofstepsmorethanonce.Suchasequenceofstepscanbegroupedtogetherintoasubroutine,whichcanthenbecalled,oraccessed,asneededindifferentpartsofthemainprogram.Eachtimeasubroutineiscalled,thecomputerrememberswhereitwasintheprogramwhenthecallwasmade,sothatitcanreturnthereuponcompletionofthesubroutine.Eachtimeasubroutineiscalled,thecomputerrememberswhereitwasintheprogramwhenthecallwasmade,sothatitcanreturnthereuponcompletionofthesubroutine.Precedingeachcall,aprogramcanspecifythatdifferentdatabeusedbythesubroutine,allowingaverygeneralpieceofcodetobewrittenonceandusedinmultipleways.ProgramFunctionMostprogramsuseseveralvarietiesofsubroutines.Themostcommonofthesearefunctions,procedures,libraryroutines,systemroutines,anddevicedrivers.Functionsareshortsubroutinesthatcomputesomevalue,suchascomputationsofangles,whichthecomputercannotcomputewithasinglebasicinstruction.Proceduresperformamorecomplexfunction,suchassortingasetofnames.Libraryroutinesaresubroutinesthatarewrittenforusebymanydifferentprograms.Systemroutinesaresimilartolibraryroutinesbutareactuallyfoundintheoperatingsystem.Theyprovidesomeservicefortheapplicationprograms,suchasprintingalineoftext.Devicedriversaresystemroutinesthatareaddedtoanoperatingsystemtoallowthecomputertocommunicatewithanewdevice,suchasascanner,modem,orprinter.Devicedriversoftenhavefeaturesthatcanbeexecuteddirectlyasapplicationsprograms.Thisallowstheusertodirectlycontrolthedevice,whichisusefulif,forinstance,acolorprinterneedstoberealignedtoattainthebestprintingqualityafterchanginganinkcartridge.Ⅲ.ProgramFunctionModerncomputersusuallystoreprogramsonsomeformofmagneticstoragemediathatcanbeaccessedrandomlybythecomputer,suchastheharddrivediskpermanentlylocatedinthecomputer,oraportablefloppydisk.Additionalinformationonsuchdisks,calleddirectories,indicatesthenamesofthevariousprogramsonthedisk,whentheywerewrittentothedisk,andwheretheprogrambeginsonthediskmedia.Whenauserdirectsthecomputertoexecuteaparticularapplicationprogram,theoperatingsystemlooksthroughthesedirectories,locatestheprogram,andreadsacopyintoRAM.TheoperatingsystemthendirectstheCPU(centralprocessingunit)tostartexecutingtheinstructionsatthebeginningoftheprogram.InstructionsatthebeginningoftheprogrampreparethecomputertoprocessinformationbylocatingfreememorylocationsinRAMtoholdworkingdata,retrievingcopiesofthestandardoptionsanddefaultstheuserhasindicatedfromadisk,anddrawinginitialdisplaysonthemonitor.Theoperatingsystemconvertsanydatasoenteredintoastandardinternalform.Theapplicationthenusesthisinformationtodecidewhattodonext—forexample,performsomedesiredprocessingfunctionsuchasreformattingapageoftext,orobtainsomeadditionalinformationfromanotherfileonadisk.Ineithercase,callstoothersystemroutinesareusedtoactuallycarryoutthedisplayoftheresultsortheaccessingofthefilefromthedisk.Whentheapplicationreachescompletionorispromptedtoquit,itmakesfurthersystemcallstomakesurethatalldatathatneedstobesavedhasbeenwrittenbacktodisk.Itthenmakesafinalsystemcalltotheoperatingsystemindicatingthatitisfinished.TheoperatingsystemthenfreesuptheRAMandanydevicesthattheapplicationwasusingandawaitsacommandfromtheusertostartanotherprogram.Ⅳ.HistoryPeoplehavebeenstoringsequencesofinstructionsintheformofaprogramforseveralcenturies.Musicboxesofthe18thcenturyandplayerpianosofthelate19thandearly20thcenturiesplayedmusicalprogramsstoredasseriesofmetalpins,orholesinpaper,witheachline(ofpinsorholes)representingwhenanotewastobeplayed,andthepinorholeindicatingwhatnotewastobeplayedatthattime.Moreelaboratecontrolofphysicaldevicesbecamecommonintheearly1800swithFrenchinventorJosephMarieJacquard’sinventionofthepunch-cardcontrolledweavingloom.Intheprocessofweavingaparticularpattern,variouspartsoftheloomhadtobemechanicallypositioned.Toautomatethisprocess,Jacquardusedasinglepapercardtorepresenteachpositioningoftheloom,withholesinthecardtoindicatewhichloomactionsshouldbedone.Anentiretapestrycouldbeencodedontoadeckofsuchcards,withthesamedeckyieldingthesametapestrydesigneachtimeitwasused.Programsofover24,000cardsweredevelopedandused.Theworld’sfirstprogrammablemachinewasdesigned—althoughneverfullybuilt—bytheEnglishmathematicianandinventor,CharlesBabbage.Thismachine,calledtheAnalyticalEngine,usedpunchcardssimilartothoseusedintheJacquardloomtoselectthespecificarithmeticoperationtoapplyateachstep.Theworld’sfirstprogrammablemachinewasdesigned—althoughneverfullybuilt—bytheEnglishmathematicianandinventor,CharlesBabbage.Thismachine,calledtheAnalyticalEngine,usedpunchcardssimilartothoseusedintheJacquardloomtoselectthespecificarithmeticoperationtoapplyateachstep.ThefirstcarddeckprogramsfortheAnalyticalEngineweredevelopedbyBritishmathematicianAugustaAdaByron,daughterofthepoetLordByron.Forthisreasonsheisrecognizedastheworld’sfirstprogrammer.VonNeumann’sideawastousethecomputer’smemorytostoretheprogramaswellasthedata.Inthisway,programscanbeviewedasdataandcanbeprocessedlikedatabyotherprograms.Thisideagreatlysimplifiestheroleofprogramstorageandexecutionincomputers.Thefieldofcomputersciencehasgrownrapidlysincethe1950sduetotheincreaseintheiruse.Computerprogramshaveundergonemanychangesduringthistimeinresponsetouserneedandadvancesintechnology.Newerideasincomputingsuchasparallelcomputing,distributedcomputing,andartificialintelligence,haveradicallyalteredthetraditionalconceptsthatoncedeterminedprogramformandfunction.Ⅴ.TheFuture
Computerscientistsworkinginthefieldofparallelcomputing,inwhichmultipleCPUscooperateonthesameproblematthesametime,haveintroducedanumberofnewprogrammodels.Inparallelcomputingpartsofaproblemareworkedonsimultaneouslybydifferentprocessors,andthisspeedsupthesolutionoftheproblem.Manychallengesfacescientistsandengineerswhodesignprogramsforparallelprocessingcomputers,becauseoftheextremecomplexityofthesystemsandthedifficultyinvolvedinmakingthemoperateaseffectivelyaspossible.AnothertypeofparallelcomputingcalleddistributedcomputingusesCPUsfrommanyinterconnectedcomputerstosolveproblems.OftenthecomputersusedtoprocessinformationinadistributedcomputingapplicationareconnectedovertheInternet.Internetapplicationsarebecomingaparticularlyusefulformofdistributedcomputing,especiallywithprogramminglanguagessuchasJava.Insuchapplications,auserlogsontoaWebsiteanddownloadsaJavaprogramontotheircomputer.WhentheJavaprogramisrun,itcommunicateswithotherprogramsatitshomeWebsite,andmayalsocommunicatewithotherprogramsrunningondifferentcomputersorWebsites.Researchintoartificialintelligence(AI)hasledtoseveralothernewstylesofprogramming.Logicprograms,forexample,donotconsistofindividualinstructionsforthecomputertofollowblindly,butinsteadconsistofsetsofrules:ifxhappensthendoy.Aspecialprogramcalledaninferenceengineusestheserulesto“reason”itswaytoaconclusionwhenpresentedwithanewproblem.Applicationsoflogicprogramsincludeautomaticmonitoringofcomplexsystems,andprovingmathematicaltheorems.Aradicallydifferentapproachtocomputinginwhichthereisnoprogramintheconventionalsenseiscalledaneuralnetwork.Aneuralnetworkisagroupofhighlyinterconnectedsimpleprocessingelements,designedtomimicthebrain.Insteadofhavingaprogramdirecttheinformationprocessinginthewaythatatraditionalcomputerdoes,aneuralnetworkprocessesinformationdependinguponthewaythatitsprocessingelementsareconnected.Programminganeuralnetworkisaccomplishedbypresentingitwithknownpatternsofinputandoutputdataandadjustingtherelativeimportanceoftheinterconnectionsbetweentheprocessingelementsuntilthedesiredpatternmatchingisaccomplished.18Neuralnetworksareusuallysimulatedontraditionalcomputers,butunliketraditionalcomputerprograms,neuralnetworksareabletolearnfromtheirexperience.2.2IntroductionofprogramminglanguagesAprogramminglanguageisanartificiallanguagedesignedtocommunicateinstructionstoamachine,particularlyacomputer.Programminglanguagescanbeusedtocreateprogramsthatcontrolthebehaviorofamachineand/ortoexpressalgorithmsprecisely.Similartonaturallanguages,suchasEnglish,programminglanguageshaveavocabulary,grammar,andsyntax.However,naturallanguagesarenotsuitedforprogrammingcomputersbecausetheyareambiguous,meaningthattheirvocabularyandgrammaticalstructuremaybeinterpretedinmultipleways.Thelanguagesusedtoprogramcomputersmusthavesimplelogicalstructures,andtherulesfortheirgrammar,spelling,andpunctuationmustbeprecise.Ⅰ.DefinitionsAprogramminglanguageisanotationforwritingprograms,whicharespecificationsofacomputationoralgorithm.Some,butnotall,authorsrestricttheterm"programminglanguage"tothoselanguagesthatcanexpressallpossiblealgorithms.Traitsoftenconsideredimportantforwhatconstitutesaprogramminglanguageinclude:Functionandtarget:Acomputerprogramminglanguageisalanguageusedtowritecomputerprograms,whichinvolveacomputerperformingsomekindofcomputationoralgorithmandpossiblycontrolexternaldevicessuchasprinters,diskdrives,robots,andsoon.ForexamplePostScriptprogramsarefrequentlycreatedbyanotherprogramtocontrolacomputerprinterordisplay.Moregenerally,aprogramminglanguagemaydescribecomputationonsome,possiblyabstract,machine.Itisgenerallyacceptedthatacompletespecificationforaprogramminglanguageincludesadescription,possiblyidealized,ofamachineorprocessorforthatlanguage.Inmostpracticalcontexts,aprogramminglanguageinvolvesacomputer;consequently,programminglanguagesareusuallydefinedandstudiedthisway.Programminglanguagesdifferfromnaturallanguagesinthatnaturallanguagesareonlyusedforinteractionbetweenpeople,whileprogramminglanguagesalsoallowhumanstocommunicateinstructionstomachines.Abstractions:Programminglanguagesusuallycontainabstractionsfordefiningandmanipulatingdatastructuresorcontrollingtheflowofexecution.Thepracticalnecessitythataprogramminglanguagesupportadequateabstractionsisexpressedbytheabstractionprinciple;thisprincipleissometimesformulatedasrecommendationtotheprogrammertomakeproperuseofsuchabstractions.Expressivepower:Thetheoryofcomputationclassifieslanguagesbythecomputationstheyarecapableofexpressing.AllTuringcompletelanguagescanimplementthesamesetofalgorithms.ANSI/ISOSQLandCharityareexamplesoflanguagesthatarenotTuringcomplete,yetoftencalledprogramminglanguages.Themostcommonlyusedprogramminglanguagesarehighlyportableandcanbeusedtoeffectivelysolvediversetypesofcomputingproblems.LanguageslikeC,PASCAL,andBASICfallintothiscategory.Programminglanguagesmaybedividedintothreegeneraltypes:Low-levelprogramminglanguagesHigh-levellanguagesAssemblyLanguagesⅡ.LanguageTypes1.Low-levelprogramminglanguages,ormachinelanguages,arethemostbasictypeofprogramminglanguagesandcanbeunderstooddirectlybyacomputer.Machinelanguageisthe“naturallanguage”ofaparticularcomputer.Itisdefinedbythehardwaredesignofthecomputer.Inmachinelanguages,instructionsarewrittenassequencesof1sand0s,calledbits,thatacomputercanunderstanddirectly.Aninstructioninmachinelanguagegenerallytellsthecomputerfourthings:Wheretofindoneortwonumbersorsimplepiecesofdatainthemaincomputermemory(RandomAccessMemory,orRAM),Asimpleoperationtoperform,suchasaddingthetwonumberstogether,Whereinthemainmemorytoputtheresultofthissimpleoperation,Wheretofindthenextinstructiontoperform.Whileallexecutableprogramsareeventuallyreadbythecomputerinmachinelanguage,theyarenotallprogrammedinmachinelanguage.Itisextremelydifficulttoprogramdirectlyinmachinelanguagebecausetheinstructionsaresequencesof1sand0s.Atypicalinstructioninamachinelanguagemightread1001011001011andmeansaddingthecontentsofstorageregisterAtothecontentsofstorageregisterB.2."High-levellanguage"referstothehigherlevelofabstractionfrommachinelanguage.Ratherthandealingwithregisters,memoryaddressesandcallstacks,high-levellanguagesdealwithvariables,arrays,objects,complexarithmeticorbooleanexpressions,subroutinesandfunctions,loops,threads,locks,andotherabstractcomputerscienceconcepts,withafocusonusabilityoveroptimalprogramefficiency.Unlikelow-levelassemblylanguages,high-levellanguageshavefew,ifany,languageelementsthattranslatedirectlyintoamachine'snativecodes.Otherfeatures,suchasstringhandlingroutines,object-orientedlanguagefeatures,andfileinput/output,mayalsobepresent.High-levellanguagesarerelativelysophisticatedsetsofstatementsutilizingwordsandsyntaxfromhumanlanguage21.Theyaremoresimilartonormalhumanlanguagesthanassemblyormachinelanguagesandarethereforeeasiertouseforwritingcomplicatedprograms.Theseprogramminglanguagesallowlargerandmorecomplicatedprogramstobedevelopedfaster.However,high-levellanguagesmustbetranslatedintomachinelanguagebyanotherprogramcalledacompilerbeforeacomputercanunderstandthem.Forthisreason,programswritteninahigh-levellanguagemaytakelongertoexecuteanduseupmorememorythanprogramswritteninanassemblylanguage.3.Assemblylanguageisalow-levelprogramminglanguageforcomputers,microprocessors,microcontrollers,andotherprogrammabledevicesinwhicheachstatementcorrespondstoasinglemachinelanguageinstruction.Anassemblylanguageisspecifictoacertaincomputerarchitecture,incontrasttomosthigh-levelprogramminglanguages,whichgenerallyareportabletomultiplesystems.Assemblylanguageprogramsareconvertedintoexecutablemachinecodebyautilityprogramreferredtoasanassembler,theconversionprocessbeingreferredtoasassemblyorassemblingtheprogram.Assemblylanguageusesmnemonicstorepresentthelow-levelmachineoperationsthatareuniquetothetargetsystem.Dependingontheparticularinstructionbeingassembled,anoperandmaybepartoftheinstruction.Mostassemblersalsounderstandtheuseoflabelsandsymbolstorepresentaddressesandconstants,makingitpossibletosymbolicallyrepresentoperandsinsteadofenteringhardcodeddata.Generallyspeaking,thereisaone–to–onecorrespondencebetweeneachassemblylanguagestatementandanexecutablemachineinstruction.Actually,inanassemblylanguage,eachstatementcorresponds
roughlytoonemachinelanguageinstruction.Anassemblylanguagestatementiscomposedwiththeaidofeasytoremembercommands.ThecommandtoaddthecontentsofthestorageregisterAtothecontentsofstorageregisterBmightbewrittenADDB,Ainatypicalassemblylanguagestatement.Assemblylanguagessharecertainfeatureswithmachinelanguages.Forinstance,itispossibletomanipulatespecificbitsinbothassemblyandmachinelanguages22.Programmersuseassemblylanguageswhenitisimportanttominimizethetimeittakestorunaprogram,becausethetranslationfromassemblylanguagetomachinelanguageisrelativelysimple.Assemblylanguagesarealsousedwhensomepartofthecomputerhastobecontrolleddirectly,suchasindividualdotsonamonitorortheflowofindividualcharacterstoaprinter.Ⅲ.ClassificationofHigh-LevelLanguagesHigh-levellanguagesarecommonlyclassifiedasprocedure-oriented,functional,object-oriented,orlogiclanguages.Inprocedure-orientedlanguages,oneormorerelatedblocksofstatementsthatperformsomecompletefunctionaregroupedtogetherintoaprogrammodule,orprocedure,andgivenanamesuchas“procedureA”.Ifthesamesequenceofoperationsisneededelsewhereintheprogram,asimplestatementcanbeusedtoreferbacktotheprocedure.Inessence,aprocedureisjustamini-program.Alargeprogramcanbeconstructedbygroupingtogetherproceduresthatperformdifferenttasks.Procedurallanguagesallowprogramstobeshorterandeasierforthecomputertoread,buttheyrequiretheprogrammertodesigneachproceduretobegeneralenoughtobeusedindifferentsituations.Functionallanguagestreatprocedureslikemathematicalfunctionsandallowthemtobeprocessedlikeanyotherdatainaprogram.Thisallowsamuchhigherandmorerigorouslevelofprogramconstruction.Functionallanguagesalsoallowvariables—symbolsfordatathatcanbespecifiedandchangedbytheuserastheprogramisrunning—tobegivenvaluesonlyonce.Thissimplifiesprogrammingbyreducingtheneedtobeconcernedwiththeexactorderofstatementexecution,sinceavariabledoesnothavetoberedeclared,orrestated,eachtimeitisusedinaprogramstatement.Manyoftheideasfromfunctionallanguageshavebecomekeypartsofmanymodernprocedurallanguages.Object-orientedlanguagesareoutgrowthsoffunctionallanguages.Anobjectorientedlanguageusesconceptsofclasses,objects,andmethods.Inobject-orientedlanguages,thecodeusedtowritetheprogramandthedataprocessedbytheprogramaregroupedtogetherintounitscalledobjects.Objectsarefurthergroupedintoclasses,whichdefinetheattributesobjectsmusthave.AsimpleexampleofaclassistheclassBook.ObjectswithinthisclassmightbeNovelandShortStory.Objectsalsohavecertainfunctionsassociatedwiththem,calledmethods.Thecomputeraccessesanobjectthroughtheuseofoneoftheobject’smethods.Themethodperformssomeactiontothedataintheobjectandreturnsthisvaluetothecomputer.Thepurposeofobjectorientationistomodel,incode,theobjectsthatmakeuptheapplicationyou’rewritingandtheinteractionsbetweenthem.Asinhumanlanguage,it’simpossibletodescribeanyprocesswithoutreferringtothenounsthatareinvolved.Allprogramminglanguagesprovidesomenouns,butuntilobject-orientedlanguagesarrivedonthescene,theprogrammercouldn’tcreatehis/herownnounsveryeasily.Programmingwaslimitedtotalkingaboutthesetofnounsprovidedbyalanguage:numbers,characters,channels,etc.Ofcourse,programmersbuiltmoreabstractstructuresaroundthislimitedsetofnouns,butthecodethatdescribedthoseabstractionswasmuchmorecomplexthantalkingabouttheminEnglish.Object-orientedlanguagesallowyoutodefinetypesofobjects(calledclasses)thatarederivedfrom,orcomposedof,othertypes.Inadditiontothisdatacomponent,thefunctions(alsocalledmethods)that“belong”tothedataarealsogroupedintheclass.Thishasatleastthreebenefits:Encapsulation.Functionsthatareinternaltoaclasscanbemarkedas“private”.Thismeansthatthey’rehiddenfromanycodeoutsidetheclass,sotheirimplementationcanbechangedwithoutbotheringanycodethatusestheclass.Conversely,themethodsthataremarked“public”formawell-definedinterfacethatshouldnotbechangedwithoutdueconsideration,becauseclientcodereliesonit.Inheritance.Youcanderiveoneclassfromanother,andthenewclassautomaticallycontainsallofthemethodsanddataoftheoriginalclass.Thisisusefulwhensomesubsetofyourobjectsneedsanadditionalcapability,butyoudon’twanttogivethatcapabilitytoalloftheotherobjects.Polymorphism.Pollywho?It’saGreek-derivedtermthatmeans“manyforms”.InOOP,itmeansthatsendingthesamemessage(inmostOOlanguages,thismeanscallingamethodbyname)mayevokedifferentresponsesdependingontype.Polymorphismitselfhasmorethanoneform.Thefirstformiswhenaderivedclassoverridesaninheritedmethodwithitsownimplementation,sothatsendingthesamemessage(callingthesamefunction)ontwodifferentobjectsyieldsadifferentbehaviordependingontheirtypes.Asecondtypeofpolymorphismiscalled“parametricpolymorphism”,whichmeansthataclassprovidesdifferentimplementationsforamethoddependingonthetypesofparameterspassedtoit.Logiclanguagesuselogicastheirmathematicalbase.Alogicprogramconsistsofsetsoffactsandif-thenrules,whichspecifyhowonesetoffactsmaybededucedfromothers,forexample:IfthestatementXistrue,thenthestatementYisfalse.Intheexecutionofsuch
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 区块链技术助力幼儿园教育资源优化
- 医疗AI技术下的药店智能化管理
- 超高速粒子加速器-全面剖析
- 2025年临床研究服务项目合作计划书
- 电网柔性调控算法-全面剖析
- 医疗专业人员的肿瘤防治技能培训计划
- 区块链技术在教育供应链优化中的市场营销策略
- 七年级下册语文知识拓展计划
- 高并发系统调试方法-全面剖析
- 南二外(集团)学府一小数学组学生能力提升计划
- GB/T 9410-2008移动通信天线通用技术规范
- GB/T 3408.1-2008大坝监测仪器应变计第1部分:差动电阻式应变计
- GB/T 20041.23-2009电缆管理用导管系统第23部分:柔性导管系统的特殊要求
- GB/T 10460-2008豌豆
- 区级领导干部医疗保健工作方案
- 焊缝超声波探伤检测报告
- 锅炉专项吊装施工方案
- 碳排放核算方法课件
- 江苏省工程技术研究中心名录
- 巡察工作流程图1
- 发育生物学 第一章 绪论
评论
0/150
提交评论