Objektivoidekieli

Sukupolven ja kehityssuuntainen

Theobject-orientedlanguagedrawsontheartificialintelligencelanguageLISPinthe1950s,andintroducestheconceptofdynamicbindingandtheideaof​​aninteractivedevelopmentenvironment;since20ThediscreteeventsimulationlanguageSIMULA67inthe1960sintroducedtheessentialsandinheritanceofclassesandwasformedinSmalltalkinthe1970s.

ThereareTwodirectionsInTheDevelopmentOfObject-OrdentedLanguages: OneispureObject-OrientedLanguges, sellainen.;theotherishybridobject-orientedlanguages,thatis,inprocedurallanguages​​andotherlanguagesAddclasses,inheritanceandothercomponents,suchasC++,Objective-C,jne.

Pääpiirteet

Object-orientedlanguages​​describetheobjectivesystemmorenaturally,whichisconvenientforsoftwareexpansionandreuse.ThereAseFourMainCharacteristics:

(1-A tunnistettavuus, TheBasicComponentsInthesystemCanberecogizedAgroupOfRecognizableSScreteObjects;

(2-A luokittelu, SystemAllObjectSwithtHesameAstructureandbehaviorCanbeGroupedInONECategory;

(3-A polymorfismi, TheObjecthasaUniquestaticTyPeandmultiplePossibledynamictypes;

(4-A perintö, sharingdataandoperationsamongdifferentClassesfbasichierarchalRelationship.

FirstThreearethefoundation, andInheritanceistheCharacteristicin joukossa.Four (and ForsometimesDynamicbinding-A ovat käyttäytyneet.

Erityinen

Tyypillinen

Itisgenerallybelievedthatthemoretypicalobject-orientedlanguages​​are:

simula67, joka on tukeva

SmallTalksupportssingleInheritance, polymorfismiadynamicbinding;

Eiffel, tukeeMultipleInheritance, polymorfismiadynamicbinding;

C ++, tukeeSmultipleInheritance, PolymorfismandPartialDynamicbinding.

JavaSupportsSingleInheritance, PolymorfismandPartialDynamicbinding.

Althoughthemeaningsoftheconceptsinvolvedinthefivelanguages​​arebasicallythesame,thetermsusedaredifferent.

C#, AlsosupportsssingleInheritance, HasManysimilartity workin.

Luokkapohjainen

Luokkapohjainenobject-orientedlanguages​​areobject-orientedMainstreamintheworld.Se sisältää:

Simula, TheFirstobject-OrientedLanguage

SmallTalk, The FirstLanguageTosupportDynamicTytyping

C ++, Malsef WhatchisbasedOnClassestHecharacteristicsOfisInhertedFromsimula.jne.ja niin edelleen.

THECOUNTERPARTOFCLASS-PERUSTELULAGUAGEISOBST-PERUSTELUOBJE-ORIENTEDLIGUAGE.TÄMÄN "OBPOT-PERUSTELU" ELÄMÄNSIFROMESTIESTIEKIRJOITTAMISEKSI."Object-based"herereferstoalanguagethatonlycentersonobjectsandhasnoconceptofclasses,similartolanguages​​suchasPython.

Kurssit

LOOKTHEDEFINITionofaclassFirst:

classcellis

Varcontents: kokonaisluku: = 0;

metodget (-A: kokonaisluku

itsenäinen palautus.sisällys;

loppu;

Methodset (n: kokonaisluku-A on

itse.Sisältö: = n;

loppu;

loppu;

AclassisusedtodescribeThecommonstructureofallobjectsbelongingtothisclass.TheobjectricestertedbythiscellclasshasanIntegerattributeCalledContents.ITSODESDESCRIBESTWOMETHODSOFMANIPULINGCONTENTS.GetAndset.ThecontentHesetwomethodsareveryIntivetive.TheSelfvariablerepresentstheobjectititse.

ThedynamicsemanticsofanobjectCanbeundersdedeasfollows:

AnobjectisInternaldeRepresentedasApointertoaseTOfproperties.AnyoperationOnThisObjectwillgothroughthepropertiesandMethodSOfThisPoEnterOperationObject.Kun AllAntSaSispassEdisAPointer, SothatTheSameseTOfPropertiesCanbeshed.

(Note,somelanguages,suchasC++,clearlydistinguishthepointertotheattributegroupandtheattributegroupititse,whilesomeotherlanguages​​hidethisdifference-A

TheObjectCanbenewInstanTiateFromaClass.Toimia.OSetSetofattributesisgivenaninitialValue, ja sisäinen,.

Let’ConsiderTheTypebelow.ForanObjectGeneratedByNewc, RecorditSTyPeaStanceTypeOf (C-A.Anexampleis:

VarmyCell: instaceTypeOf (solu-A: = newcell;

Täällä, BYTRODUCHINGINSTANCEETYPEOF (CELL-A, WESTARTTODISTICHISISEBETWEENCLASSANDTYPE.Youcanalsothinkofthecellititseasatype,butthenyouwillfindthatdoingsowillcauseconfusion.

MethodAnalysis(MethodLookup-A

MethodAnalysGivesamethodCallom (.....(Huomaa: DidyouthinKofvTable?-A.

Intuitiivisesti, teemathodkoodekanbeembeddedIneachindInualobject ja formOnyobject-Orientedlanguages, thesimilarsyntaxforpropertiesandMethodsDoesgivePeoplethisimpression.

However,consideringthespacesaving,fewlanguages​​implementthis.ThemorecommonMethodisthatThelanguageGenerateManymethodsuites ja thesemethodsuitesCanbesharedbyobjectSameclass.ThemethodResolutionProcessWillFollowThePoterToThemethodSuiteInTheObjecttofindthemethod.

Kohdistaminen.ThemethodSuitEMayBecomponedOfaTree ja theanalysisofamethodMaynedTofindaseries OfMethodsuites.IfthereismultipleInheritance, ThemethodSuitEMayevenformadiredgraph, oksaring.

MethodResolutionMayoCCuratCompileTimeAratRuntime.

UnkomeLanguges, thedetailsOfetytheMethodisembedDineTHTheObjecTexistinthemethodSuitEaReirrelastiantTotepRogrammer.BacauseallthelanguagefeatUresthatcandistraishtHesetWomodesareGenerallyNoTSupportedInclass-pohjainen objekti-suuntautuneiden kieltenkäytökset.

Forexample, MethodscannotBetaKeenFromObjectSandUnedasfunctionslikeattributes.METHOMSSCANNOTBEUPDATEDINOBjectSlikeatTributes.(Thatis, ThemethodofanObjectisupdated, WhilethemethodOfotherobjectSameSameclassremainsthesame.-A

SubclassingandInheritance(SubclassingandInheritance-A

Alaluokka jaAnhertedSubClasses, kuten generalclasses, alaryhmät.ItachievesthisGoalincrentarybyinhermitTructureOt ofoterlasses.

THEEPARENTCLASSWILLBEIMPLICYLYCOPIEDTOTHESUBCLASS- jaTHESUBCLASSCANALSOADDNEWPROPERTIES.Insomelanguages,subclassescanevenoverridethepropertiesoftheparentclass(bychangingthetypeoftheproperty-A

MENETELEMINEN.

p>

ANEXAMPESFSUBCLASSCODEISASFOLLOWS:

alaluokka

VarBackup: Kokonaisluku: = 0;

overrideset(n:Integer-Ais

itse.backup:=itse.sisällys;

super.set(n-A;

loppu;

methodrestore(-Ais

itse.contents:=itse.varmuuskopioida;

loppu;

loppu;

TheearesubclassesthemethodOfparsing differsDepingonGeHtheLanguAgeisSstacyPepeDordynamalyped.

Instaticallytypedlanguages​​(suchasC++,Java-A,thetopologicalstructureofthemethodsuiteoftheparentclassandthechildclassisdeterminedatcompiletime,sothemethodsinthemethodsuiteoftheparentclasscanbemergedGotothemethodsuiteofthesubclass,thereisnoneedtosearchthetreeorgraphofthismethodsuitewhenthemethodisanalyzed.(Press:C++vtableisthismethod-A

Fordynamicallytypedlanguages,(thatis,therelationshipbetweenparentandchildclassesisdeterminedatruntime-A,themethodsuitecannotbemerged.Siksi Whistemethodisanalysoidut, ItisneryyTeSearchalongThisDnamy DeneratedTreeOrdechedGraphunTitilasuitableMethodisfound.AndiftHelanguagesupportsmultipleInheritance, thisearchismorEncomplicted.

ParentClassesandsubclasses

Fromtheaboveexamples,itseemsthatsubclassesareonlyusedtoborrowfromtheparentclassaSomedefinitionstoavoidduplication.Kun kuitenkin.Mitä kulutus? PleaselookThefollowingExample:

VarmyCell: instaceTypeOf (solu-A: = newcell;

varmyToistaa uudelleen:InstanceTypeOf(reCell-A:=newreCell;

proceduref(x:InstanceTypeOf(cell-A-AisNiinloppu;

LOUTATHEFOLOWINGCODE:

MyCell: = MyRecell;

f(myToistaa uudelleen-A;

Inthesetwolinesofcode,thefirstonelineassignsonevariablesoftypeInstanceTypeOf(reCell-AtooneAvariableofInstanceTypeOf(cell-A.Inthesecondline,avariableoftypeInstanceTypeOf(reCell-AisusedasaparametertoafunctionwhoseparametertypeisInstanceTypeOf(cell-A.

Thisusageisillegalinlanguages​​likePascal.INOBject-OrientedLanguges, ITISCOMPLEYCORECTUSTAGEACCORDINGTOTHFOLOWINGRULES.Thisruleisusuallycalledsubtypepolimorphism,thatis,subtypepolymorphism(press:infact,subtypingshouldbethemostdifferentplaceinOOlanguagefromotherlanguages-A

Ifc'isasubtypeofc,ando'Areoneinstancesofc',theno'isalsooneinstanceofc.

Tarkkaan ottaen:

Ifc'isasubclassofc,ando':InstanceTypeOf(c'-A,theno':InstanceTypeOf(c-A.

Carefullyanalyzetheaboverule,youcanintroduceasubtyperelationshipthatsatisfiesreflexivityandtransitivitybetweenthetypesofInstanceTypeOf,use

THINTHEABOVETHISRULECANBESPLITINTOTOTWORULES:

1.Foranya: a, ifa

2.InstanceTypeOf(c’-A

TheoneruleiscalledSubsumption.Itistheonlyonestandardforjudgingthesubtype(notethatitisasubtype,notasubclass-A.

Thesecondrulecanbecalledsubclassing-is-subtyping(subclassingissubtype,right?-A

OneGenerallyspeaking,inheritanceTheyareallrelatedtosubclassing,sothisrulecanalsobecalled:inheritance-is-subtyping(inheritanceissubtyping-A

Allobject-orientedlanguages​​supportsubsumption(itcanbesaidthatifthereisnosubsumption,therewillbenoBecomeobject-oriented-A.

Mostclass-basedobject-orientedlanguages​​donotdistinguishbetweensubclassingandsubtyping.However,asomeofthelatestobject-orientedlanguages​​haveadoptedamethodofseparatingsubtypingfromsubclassing..Inotherwords, AisasubClassOfB, ButObjectSofClassacannotbeUseDasObjectSOfClassB.(Note:It'sabitlikeprivateinheritanceinC++,butthecontentisricherthanit-A

No, thedistlanctionBetWeSubClassingAndSubtypingWillbebusedlater.

Seuraavaksi Let’slookbacTThisprocedureagain.f.IntheCaseOfSubsulk, whatisthedynamicanticsOfollowingCode?

Proceduref(x:InstanceTypeOf(cell-A-Ais

x.set(3-A;

loppu;

f(myToistaa uudelleen-A;

WhenmyToistaa uudelleenispassedtofasanobjectofInstanceTypeOf(cell-A,whichoneversionofthesetmethodiscalledbyx.set(3-AWoolencloth?IsitthesetdefinedinthecellortheonedefinedinthereCell?

AtHistime, ThereareTwooptions,

1.Staticdispatch(determinedaccordingtothetypeatcompiletime-A

2.Dynamicdispatch(determinedaccordingtotherealtypeoftheobjectruntime-A

(Press,friendswhoarefamiliarwithC++willsmile,thiscouldn’tbeeasier.-A

Siellä.

Dynamicdispatchhasoneinterestingproperties.Thatis,subsumptiononemustnotaffectthestateoftheobject.IFTHESTATEFTHISOBjectSChangedDuringSUBSUBSURNUS -.

Onneksi tämä.

(Paina, ObjectSlicinginc ++ aluskvaSesthevptroftHenewObjectToTownTypeOfVTablePointer, Sothereisnoproblemofdynamicparsing.Beinfact, objektilicingCannotBecalledSubsuNuNingAll.

Tarkastustenvaikeusmenetelmät, JOSTAC ++, vaikka.ThisisalsoaannoyingButtheC++vtablesolutioncanonlydothis.Thereareonevariantsofthevtablemethod,whichcanavoidpointerchangesandismoreefficient.TämäMethodwillBeexlainedInanoterarticle.-A

Maito

Althoughsubsumptiondoesnotchangethestateoftheobject,insomelanguages​​(suchasJava-A,Itdoesn'tevenhaveanyruntimeoverhead.However,itlostasomestatictypeinformation.

Forexample,thereisonetypeInstanceTypeOf(Object-A,andtherearenoattributesandmethodsdefinedintheObjectclass.ThereisanotheroneclassMyObject,whichinheritsfromObject.ThenwhentheobjectofMyObjectistreatedasInstanceTypeOf(Object-Atype,yougetauselessemptyobjectwithnothing.

Ofcourse,ifyouconsideralessextremecase,forexample,thereareamethodfdefinedintheObjectclass,andMyObjecthasamethodFisoverloaded,then,throughdynamicdispatch,thepropertiesandmethodsinMyObjectcanstillbemanipulatedindirectly.TämäSalsoAtoPicalMethodObObject-OrientedDesignand-ohjelmointi.

FromThePerspektivefapurist, DynamicDispatchisheOnthingThatSouldBeUnedTomanipulaTeattributesandMethodsThaveBeenForGottenBysubsulk -kulutus.Itiselegant, turvallinen, andAllThegloryisAttributedTodynaamicDispatch !!!

However,whatdisappointspuristsisthatmostlanguages​​stillprovideasomeofthepropertiesandmethodsthatareforgottenbythesubsumptionarecheckedatruntime.ThismethodisgenerallycalledRTTI(RunTimeTypeIdentification-A.Sucasdynamic_casinc ++, Orinstanceofinjava.

RTTIISUSEFIED.Butbecauseofasometheoreticalandmethodologicalreasons,itisconsideredtodestroythepurityofobject-oriented.

Firstofall,itbreakstheabstractionandmakesasomemethodsandpropertiesthatshouldn’tbeusedincorrectly.

Toiseksi, koska itfektiveyMakesthepRogrammoRAGRILESILE.

Thethirdandperhapsthemostimportantonepoint,itmakestheprogramlackofscalability.Whenaddinganewtype,youmayneedtoreadthecodeofdynamic_castorinstanceofcarefullyandchangethemifnecessarytoensurethattheadditionofthisnewtypewillnotcauseproblems.

ManypeopleonementionedRTTI,alwaysfocusingonitsruntimeoverhead.Kuitenkin verrattu.

Intheframeworkofpurist(press,takeabreath,lookintothedistance,doadeeplook-A,theadditionofnewsubclassesdoesnotneedtochangetheexistingcode.

Thisisaverygoodadvantage,especiallywhenyoudon’thaveallthesourcecode.

Ingeneral,althoughRTTI(alsocalledtypecase-Aseemstobeaninevitableafeature,itisbecauseofitsmethodologicalaSomedisadvantages,itmustbeusedverycarefully.Manythingsinthetypesystemofobject-orientedlanguages​​todayaretheresultofvariouseffortstoavoidRTTI.

Forexample,insomecomplextypesystems,youcanusetheSelftypeonparametersandreturnvalues​​toavoidRTTI.Tämä.

Covarance,ContravarianceandInvariance(Covarance,ContravarianceandInvariance-A

Inthefollowingsections,wewillintroduceOnetypetechniquetoavoidRTTI.Beforethat, Let’sfirstintroDucetheconceptsfofs of "kovarianssi", "anti-kovarianssin" ja "aina.

Kovarianssi

First,let’slookattheonepairtype:A*B

ThistypesupportsoneAgetA(-AoperationtoreturntheAelementinthisPair.

GivenoneA’

Miksi? ItCanbeprovedByTheatTributeOfSUBSUBSUBSON:

AssumingthereareoneobjectsoftypeA'*Ba'*b,here,a':A',b:B,a'*b

Sitten, koska

IntShisway, thetepea*bisdefinedascovariantfora.

Samoin ItCanalalsObeveveThata*BisalsocovariantTob.

Regularapoint,Kovarianssiisdefinedasfollows:

GivenL(T-A,here,typeLiscomposedoftypeT.Niin,

IFT1

anti-kovarianssin

pleaseseeafunction:Af(Bb-A;(usingthedefinitionoffunctionallanguagePerhapsmoreconcise,thatis,f:B->A-A

Sitten,givenone,whatkindofsubtypeisbetweenB'AandB'->AWhatabouttherelationship?

ItcanbeprovedthatB->AA.

BasefaceSpace, NodervationWillBemade.

Niin,theparametertypeofthefunctionisanti-covariant.

THEEDEFINESTIONEGEGUNERPONTOFCONTRAVARANCEISASFOLLOWS:

GivenL(T-A,here,thetypeLiscombinedbythetypeT.Sitten,

IFT1

thesame, itCanbeprovedTheThereurnTypefthefunctioniscovariant.

Se ei.

Thenconsiderthefunctiong:A->A

Täällä, appearsbothinthepositionftheparameterandinthereturnThePositionCanproVethatitisnephercovariantnoranti-covariant.

ForthissitoationTitisnephercovariantnoranti-covariant, itcalledInvariance

ItisworthnotingthatforthefirstfirstThePairtypeinthisexample,ifsetA(A-Aissupported,thenPairbecomesInvariance.

Menetelmä

Inthepreviousdiscussionofsubclasses,thesimplestmethodisoneTheruleofoverride,thatis,theoverridemethodmusthavethesamesignatureastheoverridemethod.

Kuitenkin.

IntHisway, Aslongasa

klassikot

methodm(x:A-A:BisNiinloppu;

methodm1(x1:A1-A:B1isNiinloppu;

loppu;

alaluokka.

Erottelumenetelmä

TraditionalOneofthemainfeaturesofclass-basedobject-orientedlanguages​​istheinseparableconnectionbetweeninheritance,subclassingandsubtyping.ManyObject-OrientedLanguageGramMarSandconceptscomefromthesethree.Forexample, läpiluokan, yocaninheritsomemethodSoftheparentClass, whileatTheSametimeyouCanrewriteTheMethodSoftheparentClassinTheSubClass.Thisrewrittenmethodcanbecalledfromaobjectwhosetypeistheparentclassthroughsubtypingandsubsumption.

Perintö, alaluokka ja subtypingDonotalwaysLiveInharmony Kuitenkin.Ononesomeoccasions,theentanglementbetweenthethreewillhindercodereusethroughinheritanceorgenerics.Siksi PeopleBegantonoticTePsibilitysParationTheThree.ITisCOMMONTODISTICHONBETWEENSUBClassingAndSubtyping.Otheramethodsarestillintheresearchstage.

Objektityyppi

Inearlyobject-orientedlanguages​​(suchasSimula-A,thedefinitionofthetypeandtheimplementationofthemethodaremixedinaStarted.Tämä päästötehtuuri.ThisSePaationPRincipleisSespecial Päätälöity.

Morealanguage,distinguishbetweenimplementationandspecificationbyintroducingobjecttypesthatdonotdependonimplementation.Modula-3andotherlanguages​​thatsupportclassandinterfacesuchasJavausethistechnology.

WhenInstanceTypeOf(cell-Awasfirstintroduced,theconceptitrepresentedwasquitelimited.ITSEEMTHATITONLYREPRESENTSTHETYPEOFOBSTSGENeratedByNewCell, SoitCannotbeUnedToRePresentObjectSfromothertypesofNew.Butlater, WhentheinTroDuction OFSUBClassing, MetodingIrding, SubnerthAndDynamicDispatch, Asiat.TheInstanceTypeOf(cell-Acanalreadybeusedtorepresentobjectsderivedfromthesubclassofcell.Nämä objectScanincludeAtTributesandMethodsThatarenotDefinedByTheCellClass.

ItseemsunreasonabletoletInstanceTypeOf(cell-Adependonaspecificclass.Infact,oneobjectoftypeInstanceTypeOf(cell-Adoesnotnecessarilyonehaveanythingtodowithclasscell.

Theonlyonebetweenitandthecellclassisthatithasthesignatureofallthemethodsdefinedbythecellclass.

BasedonThisconsider, YouCaninTroDucethesyntaxofTheObjectType:

ForthEdEfinitionFtheCellClassandthereCellClass:

classcellis

Varcontents: kokonaisluku: = 0;

metodget (-A: kokonaisluku

itsenäinen palautus.sisällys;

loppu;

Methodset (n: kokonaisluku-A on

itse.Sisältö: = n;

loppu;

loppu;

alaluokka

VarBackup: Kokonaisluku: = 0;

overrideset(n:Integer-Ais

itse.backup:=itse.sisällys;

super.set(n-A;

loppu;

methodrestore(-Ais

itse.contents:=itse.varmuuskopioida;

loppu;

loppu;

YouCangivesuchanObjecTepedEfinition:

Objektityyppicellis

Varcontentit: kokonaisluku;

methodget(-A:Integer;

methodset(n:Integer-A;

loppu;

Objektiperelli

Varcontentit: kokonaisluku;

VarBackup: kokonaisluku;

methodget(-A:Integer

methodset(n:Integer-A;

methodrestore(-A;

loppu;

ThedefinitionftHesetwotypescludeSTetypesofattributesandMethodsDefinedByAllCellandRecellClasses.IntShisway, he ovat käyttäneet.Kaksiyteisesti.

MoitthattyoucanalsoddadditionalInheritance-likesyntaxtoavoidrewrithemethodSignatureincellInrecell.BUTTHI'SJUSTAMALLSECTION.

Erottaminen

Intheabovediscussion, therelationshipbetweensubtypesisbasedonTherelationshipBetweSubClasses.ButifyouwanTtomakeTeTypeDivedenceFTheclass, YouALsOneEdTodefineasubtypethatisinnecenceFTHESUBCLASS.

WhendefiningTheSubtype, YouRefacedWithSeveralChoices: isTheSubtypeDeterMedByTheCompositionStructureftHeTypEpEpEtyyppiä?

Thesubtypedeterminedbythecompositionstructureofthetypeislikethis:Ifthetypeahasalltheattributesandmethodsthatthetypetwoneedstohave,thenthetypeoneisthesubtypeoftypetwo.

Thesubtypedeterminedbythetypenameislikethis:onlywhenthetypeahasalltheattributesandmethodsrequiredfortypetwo,Andonlywhenthetype1isclearlydeclaredasasubtypeoftype2,thisrelationshipisrecognized.

Andifthechoiceisone,thenthoseattributesandmethodsarenecessaryforsubtype?Whichonesaredispensable?

ThesubplepeTenteredByTheCompositionstructurecanbeType-MatthedistributedInVironmentAdTheObjectPersistSystem.ThedisadvantageSThatiftHetwotypeshAppenthovethesamestructure, butInfactTheyareirrelsific, iTWillCauseRrors.Tämäkinkinkindoferrorcanbeavoeddwithsometechniques.

Epäkunnia, nimipohjainen.

YoucandefineasimpleThestructure-basedsubtyperelationship:

Forthetwotypesoando ',

O '

Exextample: Recell

ForthesAseOfSimplicity, This DefinitionDoesNottaKeAnToAcCountThemethodSpecialisaatio.

Inaddition,whenthetypedefinitionhasrecursion(similartothedefinitionofalinkedlist-A,thedefinitionofsubtypeneedstobeextracareful.

Koska WEDON'TCAREABOUTTHEORDOROFMESTORS, TÄMÄNSUBTEPEDEFINESTAUTOMAATESTUUTUTUTURIMILUSKIRJOITUKSET.

Esimerkiksi:

ObjektityyppireIngeris

Varcontentit: kokonaisluku;

VarBackup: kokonaisluku;

methodrestore(-A;

loppu;

Sitten,Thereisthefollowingsubtyperelationship:

Toistaa uudelleen

Toistaa uudelleen

(Paina, The ExpampleDoESNottaKeAntoAcCountDetailssuchastheinterfaceCannotContaintHeDataField.Infact,ifyousupportthedatafieldOverrideinsteadofshadowing-theauthor'sstructure-basedsubtypesemanticsdoesimplysuchlogic-then,itdoesnotmatterwhetherthedatafieldisincludedintheinterface,becausethetroublesomenameconflictproblemnolongerexists-A

FromThisdefinition, Wecanconclude:

Ifc'isasubclassofc,thenObjectTypeOf(c'-A

MotThatTheInversPropositionfThisdefinitionDoSnothold, SeSisTosay:

Evenifthereisnosubclassrelationshipbetweenc'andc,aslongasthemembersdefinedbythemconformtothedefinitionofsubtype,ObjectTypeOf(c'-A

LookbackandlookatThesubclass-is-subtypingofthepreviousface:

InstanceTypeOf(c'-A

Epäkunnia, alaluokka.Alaluokkalaudalla.

Tämä "alaluokkaan tarkoitettu" alaluokka-on-subtyping "sen sijaan" alaluokka-merkitys ".

Yleinen

Typeparametrit

OneGeneralmeaningIntheabove,genericsareatechnologythatreusesthesamecodeondifferenttypes.Asaatechnologyrelativelyindependentofotherobject-orientedfeatures,ithasbecomemoreandmorecommoninobject-orientedlanguages.Thereasonwhygenericsarediscussedhereisonebecausethetechnologyofgenericsisveryinterestinginititse,andalsobecausegenericsareoneusedtodealwithThemaintoolforbinarymethodproblems.

Usedtogetherwithsubtyping,genericscanbeusedtosolveasomeofthedifficultiesofthetypesystemcausedbyanti-kovarianssininmethodssuchasmethodspecialization.Considerthisaexample:

ThereareTWotypesOfersonandVegetarian, jaThesametime, thereareTwotypesofvegitableandfood.Lisäksi vihannes

Objektityyppipersonis

Niin

methodeat(food:Food-A;

loppu;

Objektityyppi

Niin

methodeat(food:Vegitable-A;

loppu;

Here,fromcommonsense,IknowoneAVegitarianisaaindividual.Siksi ihopetherecanbeavegeTarian

.Valitettavasti becausetheparametersareanti-covariant, ifyoumSenSenlyThinkThatvegetarianisAvegetarianObject, itCanbeUseSaperson.Soonevegetariancaneatmeatbymistake.

Usinggenerictechnology,introducingTypeOperator(thatis,derivingfromonetypetoanotheronetype,conceptuallysimilartothetypefunction-A.

ObjectsOperatorPersoning [F

Niin

methodeat(food:F-A;

loppu;

ObjectsOperatorvegeTarianing [f

Niin

methodeat(food:F-A;

loppu;

TheTechniqueDerEisCalledboundtypeparametrization.(Trelli/Owl, Sather, Eiffel, Polytoil, RaptideandYleinenjavaAllSupportBoundTypeparametrization.Otherlanguages,suchasC++,onlysupportsimplegenericswithouttypeconstraints-A

Fisone

b>Atypeparameter,whichcanbeinstantiatedintoaspecifictype.Similartothetypedefinitionofvariables,aboundisalegaltypesuchasF.ThetypeVegetarianEating[Vegitable]isainstanceofVegetarianEating,anditisequivalenttothetypeVegan.(Usingastructure-basedsubtype-A

Niin,thereare:

Foranyf

Alkuperäiselle kasvissyöjälle on:

Kasvissyöjä = kasvissyöjä [vihannes]

Thisrelationshipcorrectlyexpresses"Avegetarianistheconceptof"apersonwhoeatsvegetables".

InadditiontoBoundedTypeParameterization,thereareasimilarmethodsthatcanalsosolvethisvegetarian’sproblem.TämäMetodisaroitu: boundabtractType.Pleasesesethisdefinition:

Objektityyppipersonis

Kirjasintyyppi

Niin

Varlunch: f;

methodeat(food:F-A;

loppu;

Objektityyppi

Kirjasintyyppi

Niin

Varlunch: f;

methodeat(food:F-A;

loppu;

Here,FisaPersonwhoknowshecaneatcertainKindofFood,butIdon’tknowwhichkindofone.TheatributefThislunchProvidesthefoodThatThePersoneats.

WhencreatingthePersonobject,youcanfirstselectaFoodsubtype,forexample,F=Dessert.Sitten,UseonevariableofDesserttypetoassigntotheattributelunch.Finally,implementoneeat(food:Dessert-Amethod.

Inthisway,whenaVegetarianistreatedasaaPerson,thisVegetariancansafelyeathisownlunch,evenifhedoesnotknowwhetherheiseatingmeatorvegetables.

ThelimithismethodisthetPersonandveGanonlyEeatheirownlunch.CantletTheMeatLunchTheyBought.

p>
Related Articles
TOP