GenerationAndDevelopmentDirection
Theobject-orientedlanguagedrawsontheartiFicialintelligencelanguageLISPinthe1950s,andintroducestheconceptoFdynamicbindingandtheideaoFaninteractivedevelopmentenvironment;since20ThediscreteeventsimulationlanguageSIMULA67inthe1960sintroducedtheessentialsandinheritanceoFclassesandwasFormedinSmalltalkinthe1970s.
TherearetWodirectionsEnthedevementOFObject-orientedLanguages: OneSpureObject-orientedlangageages, tayAsmallTalk, EiFFel atd..;theotherishybridobject-orientedlanguages,thatis,inprocedurallanguagesandotherlanguagesAddclasses,inheritanceandothercomponents,suchasC++,Objective-C,atd.
MainFeatures
Object-orientedlanguagesdescribetheobjectivesystemmorenaturally,whichisconvenientForsoFtwareeXpansionandreuse.ThereFourmainCaracteristics:
(1) rozpoznávatelnost, thebasiccomponentSenthesystemCanberecognizesagoupoFrecognIzabledIscreteObjectjeds;
(2) klasiFikace, SystemallobjectswiththesameDataStructureandbehaviorcanbegroupedIntooNecategory;
(3) polymorFismus, theobjecthasauniquestaticpeandmultiplepossibledynamicTyps;
(4) Dědičnost, SharingDataandoperationsAmongdiFFerentClassesoFBasierarchical Relationshipships.
Mezi them, theFirstTHreeEarethundation, andInHeritanceistHecharacteristic.TheFour (andsometimesdynamicdinding) jsou využito v rámci.
SpecialLanguage
Typický
Itisgenerallybelievedthatthemoretypicalobject-orientedlanguagesare:
Simula67, který podává nalezenoinHeritanceandCiveMeaningPolymorphisMandPartialDynamicdinding;
SmallTalkSupportssingleInHeritance, PolymorphisManddynamicdinding;
EiFFel, podporaMultipleInHeritance, PolymorphisManddynamicdinding;
C ++, podporaMultipleInHeritance, PolymorphisMandPartialDynamicdinding.
JavasupportssingleInHeritance, PolymorFismAndPartialDynamicdinding.
AlthoughthemeaningsoFtheconceptsinvolvedintheFivelanguagesarebasicallythesame,thetermsusedarediFFerent.
C#, AlsosupportssingleinHeritance, HasmanysiMilarityswithjavaandc ++ atd..
Třída založená
Třída založenáobject-orientedlanguagesareobject-orientedMainstreamintheworld.To zahrnuje:
Simula, theFirstObject-orientedlanguage
Smalltalk, theFirstLanguageTosupportdynamicTyping
C ++, nejmodernější.atd.a tak dále.
TheCounterPartoFClass-LanguageISObject-založená na základě-orientanganguage.TheConceptoF "Object založené" dále issiFFerentFomTheConceceptoFCallingVisualBasICObjects."Object-based"herereFerstoalanguagethatonlycentersonobjectsandhasnoconceptoFclasses,similartolanguagessuchasPython.
Třídy
LookATTheDeFinitionOFaclassFirst:
Classcellis
VarContents: Integer: = 0;
Methodget (): Integeris
návrat.obsah;
konec;
Metodasset (N: INTEGER) je
já.Obsah: = n;
konec;
konec;
AclasssisusedtodescretheTeTeComstranuctureoFallobjectsBelongTothisclass.TheObjectrepresentedBythisCellClasshasanintegeratTributeCalledContents, které senitializovaly to0.ItalsodescriptorestwomethodSoFManipulatingContents.GetAndset.THECONTENTOFTESTOMETODSAREVERYIENTIVNÍ.TheSelFvariablerepresentstheobjectitjá.
ThedynamicsemanticsoFanobjectCanBeunderstoodasFollows:
ANOBjektivisinternallyrepresentAsAPOINTERTOASeToFProperties.AnyoperationOnThisobjectWillGothRoughthepropertiesandSoFThisSispointeroperationObject.KdyanobjectIsISSASSIGNORSSEDASAPARAMETER, AllhispasseDisapointer, SothatthesameSeToFPropertiesCanbesharedaredaredaredared.
(Note,somelanguages,suchasC++,clearlydistinguishthepointertotheattributegroupandtheattributegroupitjá,whilesomeotherlanguageshidethisdiFFerence)
TheObjectcanbeNewinstantiateFomaclass.TOBEPRECISE, NewCallocatesAtesEtoFattributesAndreturnsapointertothisSetoFattributes.ThisseToFattributesGivenininitialValue, a includesthecodeoFTheMetDeFinedBysClassc.
Let'sConsiderTheTypebelow.ForanobjectgeneratedByNewc, recorditStypeasInstanceTypeoF (c).AneXampleis:
Varmycell: InstanceTypeoF (Cell): = newCell;
Zde, BYINTRODUCINGINTSTANCETYPEOF (Cell), WestArtTodistingiishBeenclassandType.YoucanalsothinkoFthecellitjáasatype,butthenyouwillFindthatdoingsowillcauseconFusion.
MethodAnalysis(MethodLookup)
MetodanalysisGivesAMethodcallom (...), OneiSTHEPROCESSCALLEDMeTodanalysiimplementedByeachLanguageIsResponsibleFrindingTheCodeoFTheCorectMethod.(Poznámka: DiDyouthinkoFVtable?).
Intuitivně, theSetHodCodecanbeembedDeDineachIndividualObject a ForFormobject-orientedlangageages, thesimilarsyntaXForProperties amThodsdoesGivePethisiMimpression.
However,consideringthespacesaving,Fewlanguagesimplementthis.TEMORECOMMONMODISTHATHELANGUAGEGENERATERATESMaMetHodSites, ATHESEMESEMETHODSITSCANBESCANSAREDBYObjectSoFTheSAMECLASS.TheEtHODResolutionProcessWillFollowThePoterTotheModSuiteInTheObjectToFindThemethod.
Nesvětlení oFinHeritance, MetodanalysisWillBemoreComplicated.THEETHODSUITEMAYBECOMOSESONSOFATREE, ATHEANALYSSOFAMETODMODMAYNEEDTOFIndaseriesOFMethodsuites.IFtereismultipleInHeritance, theSetHodSuitemayevenFormadiredGraph, Oraring.
MetodresolutionMayoccuratCompiletimeoRuntime.
Intomelangages, thedetailsoFwhetHetHethetHodiseMBedDetheObjecteXistinTheMeTodSiReRereLevanttotheprogrammer.BecauseallthelanguageFeaturesthatCandistingThesetWomodeSaregerallyNotSupportedInclass-založená na základě orientací.
ForeXample, MethodsCannotBetakenFromobjectsandesesAsesFunctionsFunctionsLikeattributes.MetodancannotbeupdatedInInObjectSlikeattributes.(To je, thesEthodoFanobjectesisUpdated, zatímco jethodothotherobjectSoFThesaClassRemainshesamesamesamesamesamesamesamesamesamesamesamesamesamesamesamese.)
SubclassingandInheritance(SubclassingandInheritance)
Podtřídynsidheritedsubclasses, jako jegeneralclasses, arealsousedtodescrethetheretructureoFObjectjects.ItachievesthisgoalincrementalyByByInheritingThestructurecturetructureCtructureCtructuretructuretructureCtructuretructuretructuretructuretructureCtructuretructuretructuretructuretructuretructuretructuretructuretructuretructuretheroFotherClass.
ThePropertiesoFtHeparentClassWillbeimplicityCopiedTotheSubClass a athesubClasscAllsoadDNewProperties.Insomelangageages, podtřídanEveroverrideThePropertiesoFtHeparentClass (ByChangTheTypeoFTheProperty)
MetodassintEparentClasscanbecopiedTothesubClass, orcanbeoverriddendbythesubclass.
p>
ANEXampleOFSubClassCodeisasFollows:
SubclassRecelloFCellis
varbackup: Integer: = 0;
OverrideSet (N: Integer) je
já.backup:=já.obsah;
super.set (n);
konec;
MethodRestore () je
já.contents:=já.záloha;
konec;
konec;
THERERESUBCLASSESTEMODOFPARSINGDIFFERSDEDINGONESHOTHERTHETHETHETHELANGEISSSTATICEDODDORDYNYMICKÁLNĚ.
Instaticallytypedlanguages(suchasC++,Java),thetopologicalstructureoFthemethodsuiteoFtheparentclassandthechildclassisdeterminedatcompiletime,sothemethodsinthemethodsuiteoFtheparentclasscanbemergedGotothemethodsuiteoFthesubclass,thereisnoneedtosearchthetreeorgraphoFthismethodsuitewhenthemethodisanalyzed.(Stiskněte: C ++ VTableIsthisMethod)
FordynamicallytypedLanguages (to je, TherelationshipBetweentarentAntAndChildClassesisDeterMinedAtruntUntime), thethodsuiteCannotbeMerged.Proto, WhentheMethodisanalyzed, itisNentSadyToSearchAlongThisDyMicallygeredTreeorDeorDiredGrapHuntilasuitableMethodiFound.AFthelangageagesUpportsMultipleInHeritance, to searchesMoreComplicated.
ParentClassesAndSubClasses
FromtheaboveeXamples,itseemsthatsubclassesareonlyusedtoborrowFromtheparentclassaSomedeFinitionstoavoidduplication.Avšak když je třeba spotřebovat.WhatIssubssued?
Varmycell: InstanceTypeoF (Cell): = newCell;
Varmyrecell: InstanceTypeoF (Recell): = NewRecell;
procedureF(X:InstanceTypeOF(cell))is…konec;
LookATTHEFOLLOWINGCODE:
MyCell: = MyRecell;
F (myrecell);
InthesetwolinesoFcode,theFirstonelineassignsonevariablesoFtypeInstanceTypeOF(reCell)tooneAvariableoFInstanceTypeOF(cell).Inthesecondline,avariableoFtypeInstanceTypeOF(reCell)isusedasaparametertoaFunctionwhoseparametertypeisInstanceTypeOF(cell).
ThisusageisillegalinlanguageslikePascal.INOBject-orientedlangages, itisCompletelyCorrecTusageAccordingTotheFollowlingRules.ThisRuleisusUsUsusCalledSubTypePolimorphism, to je, podtypepolymorFismus (Press: inFact, podtypy, které bytostDiFFerentplaceSinoolangaguageFromotherLanguages)))
IFc'isasubtypeoFc,ando'AreoneinstancesoFc',theno'isalsooneinstanceoFc.
Přesně řečeno:
IFc'isasubClassOFc, Ando ': InstanceTypeoF (C'), Tako ': InstanceTypeoF (C).
CareFullyanalyzetheaboverule,youcanintroduceasubtyperelationshipthatsatisFiesreFleXivityandtransitivitybetweenthetypesoFInstanceTypeOF,use
THENTHEABOVETHISRULECANBESPLITINTOTOTWORULES:
1.Foranya: A, IFA
2.InstanceTypeoF (C ')
TheoneruleiscalledSubsumption.ItistheonlyonestandardForjudgingthesubtype(notethatitisasubtype,notasubclass).
TheSecondRulecanbecalledSubClassing-Is IS-Subtyping (SubclassingIsSubtype, že?)
OneGenerallyspeaking,inheritanceTheyareallrelatedtosubclassing,sothisrulecanalsobecalled:inheritance-is-subtyping(inheritanceissubtyping)
Allobject-orientedlanguagessupportsubsumption(itcanbesaidthatiFthereisnosubsumption,therewillbenoBecomeobject-oriented).
Mostclass-basedobject-orientedlanguagesdonotdistinguishbetweensubclassingandsubtyping.However,asomeoFthelatestobject-orientedlanguageshaveadoptedamethodoFseparatingsubtypingFromsubclassing..Itherwords, AisasubClassOFB, butObjectsOFClassacannotbeusesAsObSoFClassb.(POZNÁMKA: ItSabitIlikePrivaIvateInHeritanceInc ++, butthecontentisricherthanit)
No, thedistinctionbetweensubclassingandSubtypingwillbediscusdedlater.
Dále pojďme naklouznout.F.InthecaseoFsubsumption,whatisthedynamicsemanticsoFtheFollowingcode?
ProcedureF(X:InstanceTypeOF(cell))is
X.set (3);
konec;
F (myrecell);
WhenmyRecellispassedtoFasanobjectoFInstanceTypeOF(cell),whichoneversionoFthesetmethodiscalledbyX.set(3)Woolencloth?IsitthesetdeFinedinthecellortheonedeFinedinthereCell?
AtThistime, thereretwooptions,
1.Staticdispatch (určující AccordingTotheTeTypeatCompIletime)
2.Dynamicdispatch(determinedaccordingtotherealtypeoFtheobjectruntime)
(Press,FriendswhoareFamiliarwithC++一willsmile,thiscouldn’tbeeasier.)
ThisNothingTosayAboutstaticdisPatch.
Dynamicdispatchhasoneinterestingproperties.Thatis,subsumptiononemustnotaFFectthestateoFtheobject.IFthestateoFthisobjectischangedduringsubsumption,suchasobjectslicinginC++,thedynamicanalysismethodmayFail.
Fortunately,thisattributeisverygoodForbothsemanticsandeFFiciency.
(Press,objectslicinginC++initializesthevptroFthenewobjecttoitsowntypeoFvtablepointer,sothereisnoproblemoFdynamicparsing.ButinFact,objectslicingcannotbecalledsubsumptionatall.
InspeciFiclanguageimplementations,suchasC++,althoughsubsumptiondoesnotchangetheinternalstateoFtheobject,thevalueoFthepointermaychange.ThisisalsoaannoyingButtheC++vtablesolutioncanonlydothis.ThereareonevariantsoFthevtablemethod,whichcanavoidpointerchangesandismoreeFFicient.ThismethodwillbeeXplainedinanotherarticle.)
AbouttypeinFormation
AlthoughsubsumptiondoesnotchangethestateoFtheobject,insomelanguages(suchasJava),Itdoesn'tevenhaveanyruntimeoverhead.However,itlostasomestatictypeinFormation.
ForeXample,thereisonetypeInstanceTypeOF(Object),andtherearenoattributesandmethodsdeFinedintheObjectclass.ThereisanotheroneclassMyObject,whichinheritsFromObject.ThenwhentheobjectoFMyObjectistreatedasInstanceTypeOF(Object)type,yougetauselessemptyobjectwithnothing.
OFcourse,iFyouconsideralesseXtremecase,ForeXample,thereareamethodFdeFinedintheObjectclass,andMyObjecthasamethodFisoverloaded,then,throughdynamicdispatch,thepropertiesandmethodsinMyObjectcanstillbemanipulatedindirectly.ThisisalsoatypicalmethodoFobject-orienteddesignandprogramming.
FromtheperspectiveoFapurist,dynamicdispatchistheonlythingthatshouldbeusedtomanipulateattributesandmethodsthathavebeenForgottenbysubsumption.Itiselegant,saFe,andallthegloryisattributedtodynamicdispatch!!!
However,whatdisappointspuristsisthatmostlanguagesstillprovideasomeoFthepropertiesandmethodsthatareForgottenbythesubsumptionarecheckedatruntime.ThismethodisgenerallycalledRTTI(RunTimeTypeIdentiFication).Suchasdynamic_castinC++,orinstanceoFinJava.
Tobehonest,RTTIisuseFul.ButbecauseoFasometheoreticalandmethodologicalreasons,itisconsideredtodestroythepurityoFobject-oriented.
FirstoFall,itbreakstheabstractionandmakesasomemethodsandpropertiesthatshouldn’tbeusedincorrectly.
Secondly,becauseoFtheuncertaintyoFtheruntimetype,iteFFectivelymakestheprogrammoreFragile.
Thethirdandperhapsthemostimportantonepoint,itmakestheprogramlackoFscalability.Whenaddinganewtype,youmayneedtoreadthecodeoFdynamic_castorinstanceoFcareFullyandchangethemiFnecessarytoensurethattheadditionoFthisnewtypewillnotcauseproblems.
ManypeopleonementionedRTTI,alwaysFocusingonitsruntimeoverhead.However,comparedtothemethodologicalshortcomings,thisruntimeoverheadisreallyinsigniFicant.
IntheFrameworkoFpurist(press,takeabreath,lookintothedistance,doadeeplook),theadditionoFnewsubclassesdoesnotneedtochangetheeXistingcode.
Thisisaverygoodadvantage,especiallywhenyoudon’thaveallthesourcecode.
Ingeneral,althoughRTTI(alsocalledtypecase)seemstobeaninevitableaFeature,itisbecauseoFitsmethodologicalaSomedisadvantages,itmustbeusedverycareFully.ManythingsinthetypesystemoFobject-orientedlanguagestodayaretheresultoFvariouseFFortstoavoidRTTI.
ForeXample,insomecompleXtypesystems,youcanusetheSelFtypeonparametersandreturnvaluestoavoidRTTI.Thillbeintroducedlater.
Kovariance, protichůdná a invariance (kovariance, protichůdná a invariance)
IntheFollowingsections,wewillintroduceOnetypetechniquetoavoidRTTI.BeForethat,let’sFirstintroducetheconceptsoF"covariance","Anti-Covariance"and"alwaysunchanged".
Kovariance
First,let’slookattheonepairtype:A*B
ThistypesupportsoneAgetA()operationtoreturntheAelementinthisPair.
GivenoneA’
Why?ItcanbeprovedbytheattributeoFSubsumption:
AssumingthereareoneobjectsoFtypeA'*Ba'*b,here,a':A',b:B,a'*b
Pak, protože a '
Inthisway,thetypeA*BisdeFinedascovariantForA.
Podobně, itcAnalsObeProvedTthata*bisalscovariantTOBOBOBOB.
Regularapoint,KovarianceisdeFinedasFollows:
GivenL(T),here,typeLiscomposedoFtypeT.Tak,
IFT1
Anti-Covariance
pleaseseeaFunction:AF(Bb);(usingthedeFinitionoFFunctionallanguagePerhapsmoreconcise,thatis,F:B->A)
Pak,givenone,whatkindoFsubtypeisbetweenB'AandB'->AWhatabouttherelationship?
ItcanbeprovedthatB->AA.
Založený na základě, noderivationWillBemade.
Tak,theparametertypeoFtheFunctionisanti-covariant.
ThedeFinitionoFtheregularpointoFContravarianceisasFollows:
Vzhledem k (t), zde, thetypeliscombinedbythetypet.Pak,
IFT1
thesame,itcanbeprovedthatthereturntypeoFtheFunctioniscovariant.
Itdoes notchangeall.
ThenconsidertheFunctiong:A->A
Here,AappearsbothinthepositionoFtheparameterandinthereturnThepositioncanprovethatitisneithercovariantnoranti-covariant.
ForthissituationthisneitherCercovarianTnoranti-Covariant, itiscallEdinvariance
ItisworthnotingthatFortheFirstFirstThePairtypeinthiseXample,iFsetA(A)issupported,thenPairbecomesInvariance.
Metoda
InthepreviousdiscussionoFsubclasses,thesimplestmethodisoneTheruleoFoverride,thatis,theoverridemethodmusthavethesamesignatureastheoverridemethod.
However,FromtheperspectiveoFtypesaFety,thisisnotnecessary.
Inthisway, Aslongasa
klasika
methodm(X:A):Bis…konec;
methodm1(X1:A1):B1is…konec;
konec;
subclassc'oFcis.
DiFFerentiationmethod
TraditionalOneoFthemainFeaturesoFclass-basedobject-orientedlanguagesistheinseparableconnectionbetweeninheritance,subclassingandsubtyping.Manyobject-orientedlanguagegrammarsandconceptscomeFromthesethree.ForeXample,throughsubclassing,youcaninheritsomemethodsoFtheparentclass,whileatthesametimeyoucanrewritethemethodsoFtheparentclassinthesubclass.ThisrewrittenmethodcanbecalledFromaobjectwhosetypeistheparentclassthroughsubtypingandsubsumption.
Dědictví, podtřídy asubtypingdotalwaysLiveInharmony.Ononesomeoccasions,theentanglementbetweenthethreewillhindercodereusethroughinheritanceorgenerics.ThereFore,peoplebegantonoticethepossibilityoFseparatingthesethree.ItiscommontodistingiishbetweensubclassingandSubtyping.Otheramethodsarestillintheresearchstage.
ObjectType
Inearlyobject-orientedlanguages(suchasSimula),thedeFinitionoFthetypeandtheimplementationoFthemethodaremiXedinaStarted.ThisapproachviolatestheprincipleoFseparatingimplementationandspeciFicationthatiswidelyrecognizedtoday.ThisSaparationPrincipleiseSesiálně imrportantwhendevelovelIscarriedOutTyateam.
Morealanguage,distinguishbetweenimplementationandspeciFicationbyintroducingobjecttypesthatdonotdependonimplementation.Modula-3andotherlanguagesthatsupportclassandinterFacesuchasJavausethistechnology.
WhenInstanceTypeOF(cell)wasFirstintroduced,theconceptitrepresentedwasquitelimited.ItseemsthatitonlyrepresentsthetypeoFobjectsgeneratedbynewcell,soitcannotbeusedtorepresentobjectsFromothertypesoFnew.Butlater,whentheintroductionoFsubclassing,methodoverriding,subsumptionanddynamicdispatch,thingsbecamelesssimple.TheInstanceTypeOF(cell)canalreadybeusedtorepresentobjectsderivedFromthesubclassoFcell.TheseobjectscanincludeattributesandmethodsthatarenotdeFinedbythecellclass.
ItseemsunreasonabletoletInstanceTypeOF(cell)dependonaspeciFicclass.InFact,oneobjectoFtypeInstanceTypeOF(cell)doesnotnecessarilyonehaveanythingtodowithclasscell.
TheonlyonebetweenitandthecellclassisthatithasthesignatureoFallthemethodsdeFinedbythecellclass.
BasedonthisConsider,youcanintroducethesyntaXoFtheobjecttype:
ForthedeFinitionoFthecellclassandthereCellclass:
Classcellis
VarContents: Integer: = 0;
Methodget (): Integeris
návrat.obsah;
konec;
Metodasset (N: INTEGER) je
já.Obsah: = n;
konec;
konec;
SubclassRecelloFCellis
varbackup: Integer: = 0;
OverrideSet (N: Integer) je
já.backup:=já.obsah;
super.set (n);
konec;
MethodRestore () je
já.contents:=já.záloha;
konec;
konec;
YoucangivesuchanobjecttypedeFinition:
ObjectTypecellis
VarContents: Integer;
Methodget (): Integer;
Metodasset (N: Integer);
konec;
ObjectTyPereCellis
VarContents: Integer;
Varbackup: Integer;
Methodget (): celé číslo
Metodasset (N: Integer);
MethodRestore ();
konec;
ThedeFinitionoFthesetwotypesincludesthetypesoFattributesandmethodsdeFinedbyallcellandreCellclasses,buttheyarenotDoesnotincluderealization.Inthisway,theycanbeusedasinterFacesthathavenothingtodowithimplementationdetailstoachievetheseparationoFspeciFicationandimplementation.Twocompletelyunrelatedclassescandc'canhavethesametypeCell,andusersoFtheCelltypedonotneedtocarewhetheritusesclasscorclassc'.
Notethatyoucanalsoaddadditionalinheritance-likesyntaXtoavoidrewritingthemethodsignatureinCellinRecell.Butthat'sjustasmallSection.
Oddělení
Intheabovediscsion, TherelationshipBetweensubtypesisBasedTherelationshipBetweensblass.ButiFyouwanttomakethetypeindependentoFtheclass,youalsoneedtodeFineasubtypethatisindependentoFthesubclass.
WhendeFiningthesubtype,youareFacedwithseveralchoices:IsthesubtypedeterminedbythecompositionstructureoFthetype?Orisitdeterminedbythename?
ThesubtypedeterminedbythecompositionstructureoFthetypeislikethis:IFthetypeahasalltheattributesandmethodsthatthetypetwoneedstohave,thenthetypeoneisthesubtypeoFtypetwo.
Thesubtypedeterminedbythetypenameislikethis:onlywhenthetypeahasalltheattributesandmethodsrequiredFortypetwo,Andonlywhenthetype1isclearlydeclaredasasubtypeoFtype2,thisrelationshipisrecognized.
AndiFthechoiceisone,thenthoseattributesandmethodsarenecessaryForsubtype?Whichonesaredispensable?
ThesubtypeteRinedBetheCompositionStructucructucUnBeType-matedinthedIstributeDenvironmentandtheObjectPerSistencesystem.ThedisadvantageisthatiFthetwotypeshappentohavethesamestructure,butinFacttheyareirrelevant,itwillcauseerrors.However,thiskindoFerrorcanbeavoidedwithsometechniques.
Incontrast,name-basedsubtypesarenoteasytoaccuratelydeFine,andstructure-basedsubtypesarenotsupported.
YoucandeFineasimpleThestructure-basedsubtyperelationship:
FOURTHETWOTYPESOANDO ',
Ó'
ForeXample:Recell
ForthesakeoFsimplicity,thisdeFinitiondoesnottakeintoaccountthemethodSpecialization.
Inaddition,whenthetypedeFinitionhasrecursion(similartothedeFinitionoFalinkedlist),thedeFinitionoFsubtypeneedstobeeXtracareFul.
Becausewedon’tcareabouttheorderoFmembers,thissubtypedeFinitionautomaticallysupportsmultiplesubtypes.
ForeXample:
ObjectTypereIntegeris
VarContents: Integer;
Varbackup: Integer;
MethodRestore ();
konec;
Pak,ThereistheFollowingsubtyperelationship:
Recell
Recell
(Press,theeXampledoesnottakeintoaccountdetailssuchastheinterFacecannotcontainthedataField.InFact,iFyousupportthedataFieldOverrideinsteadoFshadowing-theauthor'sstructure-basedsubtypesemanticsdoesimplysuchlogic-then,itdoesnotmatterwhetherthedataFieldisincludedintheinterFace,becausethetroublesomenameconFlictproblemnolongereXists)
FromthisdeFinition,wecanconclude:
IFc'isasubclassoFc,thenObjectTypeOF(c')
NotethattheinversepropositionoFthisdeFinitiondoesnothold,Thatistosay:
EveniFthereisnosubclassrelationshipbetweenc'andc,aslongasthemembersdeFinedbythemconFormtothedeFinitionoFsubtype,ObjectTypeOF(c')
LookbackandlookatThesubclass-is-subtypingoFthepreviousFace:
InstanceTypeOF(c')
Incontrast, podtřídy aSubtypingHavebeenPartiallyseparované.SubclassingisstillsUbtyping, butsubtypingNolongerRequiressubClassing.
Thispropertyiscalled"subclassing-implies-subtyping"insteadoF"subclass-is-subtyping".
Obecný
Typeparametry
OneGeneralmeaningIntheabove,genericsareatechnologythatreusesthesamecodeondiFFerenttypes.AsaatechnologyrelativelyindependentoFotherobject-orientedFeatures,ithasbecomemoreandmorecommoninobject-orientedlanguages.ThereasonwhygenericsarediscussedhereisonebecausethetechnologyoFgenericsisveryinterestinginitjá,andalsobecausegenericsareoneusedtodealwithThemaintoolForbinarymethodproblems.
Usedtogetherwithsubtyping,genericscanbeusedtosolveasomeoFthediFFicultiesoFthetypesystemcausedbyAnti-Covarianceinmethodssuchasmethodspecialization.ConsiderthisaeXample:
TherearetwotypesoFPersonandVegetarian,andatthesametime,therearetwotypesoFVegitableandFood.Navíc zelenina
ObjectTypepersonis
…
methodeat(Food:Food);
konec;
ObjectTyPevegetarianis
…
methodeat(Food:Vegitable);
konec;
Here,Fromcommonsense,IknowoneAVegitarianisaaindividual.ThereFore,IhopetherecanbeaVegetarian
.UnFortunately,becausetheparametersareanti-covariant,iFyoumistakenlythinkthatVegetarianisaVegetarianobject,itcanbeusedasaPerson.Soonevegetariancaneatmeatbymistake.
Usinggenerictechnology,introducingTypeOperator(thatis,derivingFromonetypetoanotheronetype,conceptuallysimilartothetypeFunction).
ObjectOperatorPersoning [f
…
methodeat(Food:F);
konec;
ObjectOperatorVegetarianiating [f
…
methodeat(Food:F);
konec;
TheTechniqueuseusedsherescalledBoundTypeparameterizace.(Trelli/Owl,Sather,EiFFel,PolyTOIL,RaptideandObecnýJavaallsupportBoundedTypeParameterization.Jiné jazyky, takové ASC ++, OnlySupportSimplegenerics withOutTyPeconstraints)
Fisone
b>Atypeparameter,whichcanbeinstantiatedintoaspeciFictype.SimilartothetypedeFinitionoFvariables,aboundisalegaltypesuchasF.ThetypeVegetarianEating[Vegitable]isainstanceoFVegetarianEating,anditisequivalenttothetypeVegan.(Používání astruktury založené na
Tak,thereare:
ForAnyf
Pro původní vegetariánský typ existují:
Vegetarián = vegetariánský stravování [zelenina]
ThisrelationshipcorrectlyeXpresses"一AvegetarianistheconceptoF"apersonwhoeatsvegetables".
InadditiontoBoundedTypeParameterization,thereareasimilarmethodsthatcanalsosolvethisvegetarian’sproblem.ThistoMethodiscalled: BoundedabstractType.PleaseseethisdeFinition:
ObjectTypepersonis
Typ
…
Varlunch: F;
methodeat(Food:F);
konec;
ObjectTyPevegetarianis
Typ
…
Varlunch: F;
methodeat(Food:F);
konec;
Here,FisaPersonwhoknowshecaneatcertainKindoFFood,butIdon’tknowwhichkindoFone.TheattributeoFthislunchprovidestheFoodthatthePersoneats.
WhencreatingthePersonobject,youcanFirstselectaFoodsubtype,ForeXample,F=Dessert.Pak,UseonevariableoFDesserttypetoassigntotheattributelunch.Finally,implementoneeat(Food:Dessert)method.
Inthisway,whenaVegetarianistreatedasaaPerson,thisVegetariancansaFelyeathisownlunch,eveniFhedoesnotknowwhetherheiseatingmeatorvegetables.
ThelimitationoFthismethodisthatPersonandVegancanonlyeattheirownlunch.CelkolthemeatLunchtheyBeght.
p>