




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 【正版授權(quán)】 ISO/IEC 30105-2:2024 EN Information technology - IT Enabled Services-Business Process Outsourcing (ITES-BPO) lifecycle processes - Part 2: Process assessment model (PAM)
- 【正版授權(quán)】 ISO 13315-2:2025 EN Environmental management for concrete and concrete structures - Part 2: System boundary and inventory data
- 2025年度公共設(shè)施裝修工期延誤賠償及質(zhì)量保證協(xié)議
- 2025年度電子商務(wù)交易安全保障合同
- 2025高考作文預(yù)測(cè):正確“出圈”才能出彩
- 個(gè)人職業(yè)能力提升計(jì)劃
- 未來(lái)年的市場(chǎng)拓展計(jì)劃
- 提升職業(yè)道德與素養(yǎng)的工作計(jì)劃
- 班級(jí)網(wǎng)絡(luò)學(xué)習(xí)平臺(tái)的搭建與維護(hù)計(jì)劃
- 2025年休閑專(zhuān)用車(chē)及其零附件項(xiàng)目建議書(shū)
- 小學(xué)期末班級(jí)頒獎(jiǎng)典禮動(dòng)態(tài)PPT模板
- 液堿生產(chǎn)工序及生產(chǎn)流程敘述
- 心理抗壓能力測(cè)試?yán)}
- 三年級(jí)學(xué)生《成長(zhǎng)記錄》模板
- 好書(shū)推薦——《三毛流浪記》
- 方菱F2100B中文系統(tǒng)說(shuō)明書(shū)
- 人教版動(dòng)手動(dòng)腦學(xué)物理答案 八下
- 九宮格數(shù)獨(dú)題目(打印版)
- 內(nèi)燃機(jī)基本知識(shí)
- 抹灰工程施工合同-
- 2019.2青島版五四制五年級(jí)下冊(cè)數(shù)學(xué)教學(xué)計(jì)劃(附教學(xué)進(jìn)度表)
評(píng)論
0/150
提交評(píng)論