Object Oriented Language

Generationanddevelopmentdirection

Theobject-orientedlanguagedrawsontheartificialintelligencelanguageLISPinthe1950s,andintroducestheconceptofdynamicbindingandtheideaof​​aninteractivedevelopmentenvironment;since20ThediscreteeventsimulationlanguageSIMULA67inthe1960sintroducedtheessentialsandinheritanceofclassesandwasformedinSmalltalkinthe1970s.

Therearetwodirectionsinthedevelopmentofobject-orientedlanguages:oneispureobject-orientedlanguages,suchasSmalltalk,EIFFEL,etc.;theotherishybridobject-orientedlanguages,thatis,inprocedurallanguages​​andotherlanguagesAddclasses,inheritanceandothercomponents,suchasC++,Objective-C,etc.

Mainfeatures

Object-orientedlanguages​​describetheobjectivesystemmorenaturally,whichisconvenientforsoftwareexpansionandreuse.Therearefourmaincharacteristics:

(1)Recognizability,thebasiccomponentsinthesystemcanberecognizedasagroupofrecognizablediscreteobjects;

(2)Classification,systemAllobjectswiththesamedatastructureandbehaviorcanbegroupedintoonecategory;

(3)Polymorphism,theobjecthasauniquestatictypeandmultiplepossibledynamictypes;

(4)Inheritance,sharingdataandoperationsamongdifferentclassesofbasichierarchicalrelationships.

Amongthem,thefirstthreearethefoundation,andinheritanceisthecharacteristic.Thefour(andsometimesdynamicbinding)areusedincombinationtoreflecttheexpressiveabilityofobject-orientedlanguages.

Speciallanguage

Typical

Itisgenerallybelievedthatthemoretypicalobject-orientedlanguages​​are:

simula67,whichsupportssingleinheritanceandcertainMeaningpolymorphismandpartialdynamicbinding;

Smalltalksupportssingleinheritance,polymorphismanddynamicbinding;

EIFFEL,supportsmultipleinheritance,polymorphismanddynamicbinding;

C++,supportsmultipleinheritance,polymorphismandpartialdynamicbinding.

Javasupportssingleinheritance,polymorphismandpartialdynamicbinding.

Althoughthemeaningsoftheconceptsinvolvedinthefivelanguages​​arebasicallythesame,thetermsusedaredifferent.

C#,alsosupportssingleinheritance,hasmanysimilaritieswithJavaandC++,etc.

Class-based

Class-basedobject-orientedlanguages​​areobject-orientedMainstreamintheworld.Itincludes:

Simula,thefirstobject-orientedlanguage

Smalltalk,thefirstlanguagetosupportdynamictyping

C++,mostofwhichisbasedonclassesThecharacteristicsofisinheritedfromSimula.etc.andsoon.

Thecounterpartofclass-basedlanguageisobject-basedobject-orientedlanguage.Theconceptof"object-based"hereisdifferentfromtheconceptofcallingVisualBasicobject-based."Object-based"herereferstoalanguagethatonlycentersonobjectsandhasnoconceptofclasses,similartolanguages​​suchasPython.

Classesandobjects

Lookatthedefinitionofaclassfirst:

classcellis

varcontents:Integer:=0;

methodget():Integeris

returnself.contents;

end;

methodset(n:Integer)is

self.contents:=n;

end;

end;

AclassisusedtodescribeThecommonstructureofallobjectsbelongingtothisclass.Theobjectrepresentedbythiscellclasshasanintegerattributecalledcontents,whichisinitializedto0.Italsodescribestwomethodsofmanipulatingcontents.Getandset.Thecontentofthesetwomethodsareveryintuitive.TheSelfvariablerepresentstheobjectitself.

Thedynamicsemanticsofanobjectcanbeunderstoodasfollows:

Anobjectisinternallyrepresentedasapointertoasetofproperties.Anyoperationonthisobjectwillgothroughthepropertiesandmethodsofthispointeroperationobject.Whenanobjectisassignedorpassedasaparameter,allthatispassedisapointer,sothatthesamesetofpropertiescanbeshared.

(Note,somelanguages,suchasC++,clearlydistinguishthepointertotheattributegroupandtheattributegroupitself,whilesomeotherlanguages​​hidethisdifference)

TheobjectcanbenewInstantiatefromaclass.Tobeprecise,newCallocatesasetofattributesandreturnsapointertothissetofattributes.Thissetofattributesisgivenaninitialvalue,andincludesthecodeofthemethoddefinedbyclassC.

Let’sconsiderthetypebelow.ForanobjectgeneratedbynewC,recorditstypeasInstanceTypeOf(c).Anexampleis:

varmyCell:InstanceTypeOf(cell):=newcell;

Here,byintroducingInstanceTypeOf(cell),westarttodistinguishbetweenclassandtype.Youcanalsothinkofthecellitselfasatype,butthenyouwillfindthatdoingsowillcauseconfusion.

MethodAnalysis(MethodLookup)

Methodanalysisgivesamethodcallom(...),oneisTheprocesscalledmethodanalysisimplementedbyeachlanguageisresponsibleforfindingthecodeofthecorrectmethod.(Note:Didyouthinkofvtable?).

Intuitively,themethodcodecanbeembeddedineachindividualobject,andformanyobject-orientedlanguages,thesimilarsyntaxforpropertiesandmethodsdoesgivepeoplethisimpression.

However,consideringthespacesaving,fewlanguages​​implementthis.Themorecommonmethodisthatthelanguagegeneratesmanymethodsuites,andthesemethodsuitescanbesharedbyobjectsofthesameclass.Themethodresolutionprocesswillfollowthepointertothemethodsuiteintheobjecttofindthemethod.

Inconsiderationofinheritance,methodanalysiswillbemorecomplicated.Themethodsuitemaybecomposedofatree,andtheanalysisofamethodmayneedtofindaseriesofmethodsuites.Ifthereismultipleinheritance,themethodsuitemayevenformadirectedgraph,oraring.

Methodresolutionmayoccuratcompiletimeoratruntime.

Insomelanguages,thedetailsofwhetherthemethodisembeddedintheobjectorexistinthemethodsuiteareirrelevanttotheprogrammer.Becauseallthelanguagefeaturesthatcandistinguishthesetwomodesaregenerallynotsupportedinclass-basedobject-orientedlanguages.

Forexample,methodscannotbetakenfromobjectsandusedasfunctionslikeattributes.Methodscannotbeupdatedinobjectslikeattributes.(Thatis,themethodofanobjectisupdated,whilethemethodofotherobjectsofthesameclassremainsthesame.)

SubclassingandInheritance(SubclassingandInheritance)

Subclassesandinheritedsubclasses,likegeneralclasses,arealsousedtodescribethestructureofobjects.However,itachievesthisgoalincrementallybyinheritingthestructureofotherclasses.

Thepropertiesoftheparentclasswillbeimplicitlycopiedtothesubclass,andthesubclasscanalsoaddnewproperties.Insomelanguages,subclassescanevenoverridethepropertiesoftheparentclass(bychangingthetypeoftheproperty)

Methodsintheparentclasscanbecopiedtothesubclass,orcanbeoverriddenbythesubclass.

p>

Anexampleofsubclasscodeisasfollows:

subclassreCellofcellis

varbackup:Integer:=0;

overrideset(n:Integer)is

self.backup:=self.contents;

super.set(n);

end;

methodrestore()is

self.contents:=self.backup;

end;

end;

TherearesubclassesThemethodofparsingdiffersdependingonwhetherthelanguageisstaticallytypedordynamicallytyped.

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

Fordynamicallytypedlanguages,(thatis,therelationshipbetweenparentandchildclassesisdeterminedatruntime),themethodsuitecannotbemerged.Therefore,whenthemethodisanalyzed,itisnecessarytosearchalongthisdynamicallygeneratedtreeordirectedgraphuntilasuitablemethodisfound.Andifthelanguagesupportsmultipleinheritance,thissearchismorecomplicated.

Parentclassesandsubclasses

Fromtheaboveexamples,itseemsthatsubclassesareonlyusedtoborrowfromtheparentclassaSomedefinitionstoavoidduplication.However,whenconsideringsubsumption,thingsarealittledifferent.WhatisSubsumption?Pleaselookatthefollowingexample:

varmyCell:InstanceTypeOf(cell):=newcell;

varmyReCell:InstanceTypeOf(reCell):=newreCell;

proceduref(x:InstanceTypeOf(cell))is…end;

Lookatthefollowingcode:

myCell:=myReCell;

f(myReCell);

Inthesetwolinesofcode,thefirstonelineassignsonevariablesoftypeInstanceTypeOf(reCell)tooneAvariableofInstanceTypeOf(cell).Inthesecondline,avariableoftypeInstanceTypeOf(reCell)isusedasaparametertoafunctionwhoseparametertypeisInstanceTypeOf(cell).

Thisusageisillegalinlanguages​​likePascal.Inobject-orientedlanguages,itiscompletelycorrectusageaccordingtothefollowingrules.Thisruleisusuallycalledsubtypepolimorphism,thatis,subtypepolymorphism(press:infact,subtypingshouldbethemostdifferentplaceinOOlanguagefromotherlanguages)

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

Strictlyspeaking:

Ifc'isasubclassofc,ando':InstanceTypeOf(c'),theno':InstanceTypeOf(c).

Carefullyanalyzetheaboverule,youcanintroduceasubtyperelationshipthatsatisfiesreflexivityandtransitivitybetweenthetypesofInstanceTypeOf,use

ThentheaboveThisrulecanbesplitintotworules:

1.Foranya:A,ifA

2.InstanceTypeOf(c’)

TheoneruleiscalledSubsumption.Itistheonlyonestandardforjudgingthesubtype(notethatitisasubtype,notasubclass).

Thesecondrulecanbecalledsubclassing-is-subtyping(subclassingissubtype,right?)

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

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

Mostclass-basedobject-orientedlanguages​​donotdistinguishbetweensubclassingandsubtyping.However,asomeofthelatestobject-orientedlanguages​​haveadoptedamethodofseparatingsubtypingfromsubclassing..Inotherwords,AisasubclassofB,butobjectsofclassAcannotbeusedasobjectsofclassB.(Note:It'sabitlikeprivateinheritanceinC++,butthecontentisricherthanit)

Well,thedistinctionbetweensubclassingandsubtypingwillbediscussedlater.

Next,let’slookbackatthisprocedureagain.f.Inthecaseofsubsumption,whatisthedynamicsemanticsofthefollowingcode?

Proceduref(x:InstanceTypeOf(cell))is

x.set(3);

end;

f(myReCell);

WhenmyReCellispassedtofasanobjectofInstanceTypeOf(cell),whichoneversionofthesetmethodiscalledbyx.set(3)Woolencloth?IsitthesetdefinedinthecellortheonedefinedinthereCell?

Atthistime,therearetwooptions,

1.Staticdispatch(determinedaccordingtothetypeatcompiletime)

2.Dynamicdispatch(determinedaccordingtotherealtypeoftheobjectruntime)

(Press,friendswhoarefamiliarwithC++willsmile,thiscouldn’tbeeasier.)

Thereisnothingtosayaboutstaticdispatch.

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,whatdisappointspuristsisthatmostlanguages​​stillprovideasomeofthepropertiesandmethodsthatareforgottenbythesubsumptionarecheckedatruntime.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-orientedlanguages​​todayaretheresultofvariouseffortstoavoidRTTI.

Forexample,insomecomplextypesystems,youcanusetheSelftypeonparametersandreturnvalues​​toavoidRTTI.Thiswillbeintroducedlater.

Covarance,ContravarianceandInvariance(Covarance,ContravarianceandInvariance)

Inthefollowingsections,wewillintroduceOnetypetechniquetoavoidRTTI.Beforethat,let’sfirstintroducetheconceptsof"covariance","anti-covariance"and"alwaysunchanged".

Covariance

First,let’slookattheonepairtype:A*B

ThistypesupportsoneAgetA()operationtoreturntheAelementinthisPair.

GivenoneA’

Why?ItcanbeprovedbytheattributeofSubsumption:

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

Then,because,A'

Inthisway,thetypeA*BisdefinedascovariantforA.

Similarly,itcanalsobeprovedthatA*BisalsocovarianttoB.

Regularapoint,Covarianceisdefinedasfollows:

GivenL(T),here,typeLiscomposedoftypeT.So,

IfT1

anti-covariance

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

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

ItcanbeprovedthatB->AA.

Basedonspace,noderivationwillbemade.

So,theparametertypeofthefunctionisanti-covariant.

ThedefinitionoftheregularpointofContravarianceisasfollows:

GivenL(T),here,thetypeLiscombinedbythetypeT.Then,

IfT1

thesame,itcanbeprovedthatthereturntypeofthefunctioniscovariant.

Itdoesn’tchangeatall.

Thenconsiderthefunctiong:A->A

Here,AappearsbothinthepositionoftheparameterandinthereturnThepositioncanprovethatitisneithercovariantnoranti-covariant.

Forthissituationthatisneithercovariantnoranti-covariant,itiscalledInvariance

ItisworthnotingthatforthefirstfirstThePairtypeinthisexample,ifsetA(A)issupported,thenPairbecomesInvariance.

MethodSpecialization

Inthepreviousdiscussionofsubclasses,thesimplestmethodisoneTheruleofoverride,thatis,theoverridemethodmusthavethesamesignatureastheoverridemethod.

However,fromtheperspectiveoftypesafety,thisisnotnecessary.

Inthisway,aslongasA

classcis

methodm(x:A):Bis…end;

methodm1(x1:A1):B1is…end;

end;

subclassc'ofcis.

Differentiationmethod

TraditionalOneofthemainfeaturesofclass-basedobject-orientedlanguages​​istheinseparableconnectionbetweeninheritance,subclassingandsubtyping.Manyobject-orientedlanguagegrammarsandconceptscomefromthesethree.Forexample,throughsubclassing,youcaninheritsomemethodsoftheparentclass,whileatthesametimeyoucanrewritethemethodsoftheparentclassinthesubclass.Thisrewrittenmethodcanbecalledfromaobjectwhosetypeistheparentclassthroughsubtypingandsubsumption.

However,inheritance,subclassing,andsubtypingdonotalwaysliveinharmony.Ononesomeoccasions,theentanglementbetweenthethreewillhindercodereusethroughinheritanceorgenerics.Therefore,peoplebegantonoticethepossibilityofseparatingthesethree.Itiscommontodistinguishbetweensubclassingandsubtyping.Otheramethodsarestillintheresearchstage.

Objecttype

Inearlyobject-orientedlanguages​​(suchasSimula),thedefinitionofthetypeandtheimplementationofthemethodaremixedinaStarted.Thisapproachviolatestheprincipleofseparatingimplementationandspecificationthatiswidelyrecognizedtoday.Thisseparationprincipleisespeciallyimportantwhendevelopmentiscarriedoutbyateam.

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

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

returnself.contents;

end;

methodset(n:Integer)is

self.contents:=n;

end;

end;

subclassreCellofcellis

varbackup:Integer:=0;

overrideset(n:Integer)is

self.backup:=self.contents;

super.set(n);

end;

methodrestore()is

self.contents:=self.backup;

end;

end;

Youcangivesuchanobjecttypedefinition:

ObjectTypeCellis

varcontents:Integer;

methodget():Integer;

methodset(n:Integer);

end;

ObjectTypeReCellis

varcontents:Integer;

varbackup:Integer;

methodget():Integer

methodset(n:Integer);

methodrestore();

end;

ThedefinitionofthesetwotypesincludesthetypesofattributesandmethodsdefinedbyallcellandreCellclasses,buttheyarenotDoesnotincluderealization.Inthisway,theycanbeusedasinterfacesthathavenothingtodowithimplementationdetailstoachievetheseparationofspecificationandimplementation.Twocompletelyunrelatedclassescandc'canhavethesametypeCell,andusersoftheCelltypedonotneedtocarewhetheritusesclasscorclassc'.

Notethatyoucanalsoaddadditionalinheritance-likesyntaxtoavoidrewritingthemethodsignatureinCellinReCell.Butthat'sjustasmallsection.

Separation

Intheabovediscussion,therelationshipbetweensubtypesisbasedontherelationshipbetweensubclasses.Butifyouwanttomakethetypeindependentoftheclass,youalsoneedtodefineasubtypethatisindependentofthesubclass.

Whendefiningthesubtype,youarefacedwithseveralchoices:Isthesubtypedeterminedbythecompositionstructureofthetype?Orisitdeterminedbythename?

Thesubtypedeterminedbythecompositionstructureofthetypeislikethis:Ifthetypeahasalltheattributesandmethodsthatthetypetwoneedstohave,thenthetypeoneisthesubtypeoftypetwo.

Thesubtypedeterminedbythetypenameislikethis:onlywhenthetypeahasalltheattributesandmethodsrequiredfortypetwo,Andonlywhenthetype1isclearlydeclaredasasubtypeoftype2,thisrelationshipisrecognized.

Andifthechoiceisone,thenthoseattributesandmethodsarenecessaryforsubtype?Whichonesaredispensable?

Thesubtypedeterminedbythecompositionstructurecanbetype-matchedinthedistributedenvironmentandtheobjectpersistencesystem.Thedisadvantageisthatifthetwotypeshappentohavethesamestructure,butinfacttheyareirrelevant,itwillcauseerrors.However,thiskindoferrorcanbeavoidedwithsometechniques.

Incontrast,name-basedsubtypesarenoteasytoaccuratelydefine,andstructure-basedsubtypesarenotsupported.

YoucandefineasimpleThestructure-basedsubtyperelationship:

ForthetwotypesOandO',

O'

Forexample:ReCell

Forthesakeofsimplicity,thisdefinitiondoesnottakeintoaccountthemethodSpecialization.

Inaddition,whenthetypedefinitionhasrecursion(similartothedefinitionofalinkedlist),thedefinitionofsubtypeneedstobeextracareful.

Becausewedon’tcareabouttheorderofmembers,thissubtypedefinitionautomaticallysupportsmultiplesubtypes.

Forexample:

ObjectTypeReIntegeris

varcontents:Integer;

varbackup:Integer;

methodrestore();

end;

Then,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,subclassingandsubtypinghavebeenpartiallyseparated.Subclassingisstillsubtyping,butsubtypingnolongerrequiressubclassing.

Thispropertyiscalled"subclassing-implies-subtyping"insteadof"subclass-is-subtyping".

Generic

TypeParameters

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

Usedtogetherwithsubtyping,genericscanbeusedtosolveasomeofthedifficultiesofthetypesystemcausedbyanti-covarianceinmethodssuchasmethodspecialization.Considerthisaexample:

TherearetwotypesofPersonandVegetarian,andatthesametime,therearetwotypesofVegitableandFood.Moreover,Vegitable

ObjectTypePersonis

methodeat(food:Food);

end;

ObjectTypeVegetarianis

methodeat(food:Vegitable);

end;

Here,fromcommonsense,IknowoneAVegitarianisaaindividual.Therefore,IhopetherecanbeaVegetarian

.Unfortunately,becausetheparametersareanti-covariant,ifyoumistakenlythinkthatVegetarianisaVegetarianobject,itcanbeusedasaPerson.Soonevegetariancaneatmeatbymistake.

Usinggenerictechnology,introducingTypeOperator(thatis,derivingfromonetypetoanotheronetype,conceptuallysimilartothetypefunction).

ObjectOperatorPersonEating[F

methodeat(food:F);

end;

ObjectOperatorVegetarianEating[F

methodeat(food:F);

end;

ThetechniqueusedhereiscalledBoundedTypeParameterization.(Trelli/Owl,Sather,Eiffel,PolyTOIL,RaptideandGenericJavaallsupportBoundedTypeParameterization.Otherlanguages,suchasC++,onlysupportsimplegenericswithouttypeconstraints)

Fisone

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

So,thereare:

ForanyF

FortheoriginalVegetariantype,thereare:

Vegetarian=VegetarianEating[Vegetable]

Thisrelationshipcorrectlyexpresses"Avegetarianistheconceptof"apersonwhoeatsvegetables".

InadditiontoBoundedTypeParameterization,thereareasimilarmethodsthatcanalsosolvethisvegetarian’sproblem.Thismethodiscalled:BoundedAbstractType.Pleaseseethisdefinition:

ObjectTypePersonis

TypeF

varlunch:F;

methodeat(food:F);

end;

ObjectTypeVegetarianis

TypeF

varlunch:F;

methodeat(food:F);

end;

Here,FisaPersonwhoknowshecaneatcertainKindofFood,butIdon’tknowwhichkindofone.TheattributeofthislunchprovidestheFoodthatthePersoneats.

WhencreatingthePersonobject,youcanfirstselectaFoodsubtype,forexample,F=Dessert.Then,UseonevariableofDesserttypetoassigntotheattributelunch.Finally,implementoneeat(food:Dessert)method.

Inthisway,whenaVegetarianistreatedasaaPerson,thisVegetariancansafelyeathisownlunch,evenifhedoesnotknowwhetherheiseatingmeatorvegetables.

ThelimitationofthismethodisthatPersonandVegancanonlyeattheirownlunch.Can'tletthemeatlunchtheybought.

p>
Related Articles
TOP