alsodeclareandprovideimplementationsfortheinstancemethodsthatallowtheridertochangegears,brake,andchangethepedalingcadence,asshowninthenextfigure.
Thebicycleclass.
Afteryou'vecreatedthebicycleclass,youcancreateanynumberofbicycleobjectsfromthatclass.Whenyoucreateaninstanceofaclass,thesystemallocatesenoughmemoryfortheobjectandallitsinstancevariables.Eachinstancegetsitsowncopyofalltheinstancevariablesdefinedintheclass,asthenextfigureshows.
MyBikeandYourBikearetwodifferentinstancesoftheBikeclass.EachinstancehasitsowncopyoftheinstancevariablesdefinedintheBikeclassbuthasdifferentvaluesforthesevariables.
Inadditiontoinstancevariables,classescandefineclassvariables.Aclasswariablecontainsinformationthatissharedbyallinstancesoftheclass.Forexample,supposethatallbicycleshadthesamenumberofgears.Inthiscase,defininganinstancevariabletoholdthenumberofgearsisinefficient;eachinstancewouldhaveitsowncopyofthevariable,butthevaluewouldbethesameforeveryinstance.Insuchsituations,youcandefineaclassvariablethatcontainsthenumberofgears(seethefollowingfigure);allinstancessharethisvariable.Ifoneobjectchangesthevariable,itchangesforallotherobjectsofthattype.
YourBike,aninstanceofBike,hasaccesstothenumberOfGearsvariableintheBikeclass;however,theYourBikeinstancedoesnothaveacopyofthisclassvariable.
AclasscanalsodeclareclassmethodsYoucaninvokeaclassmethoddirectlyfromtheclass,whereasyoumustinvokeinstancemethodsonaparticularinstance.
TheUnderstandingInstanceandClassMemberssectiondiscussesinstancevariablesandmethodsandclassvariablesandmethodsindetail.
Objectsprovidethebenefitofmodularityandinformation-hiding.Classesprovidethebenefitofreusability.Bicyclemanufacturersusethesameblueprintoverandoveragaintobuildlotsofbicycles.Softwareprogrammersusethesameclass,andthusthesamecode,overandoveragaintocreatemanyobjects.
ObjectsversusClasses
You'veprobablynoticedthattheillustrationsofobjectsandclasseslookverysimilar.Andindeed,thedifferencebetweenclassesandobjectsisoftenthesourceofsomeconfusion.Intherealworld,it'sobviousthatclassesarenotthemselvestheobjectstheydescribe;thatis,ablueprintofabicycleisnotabicycle.However,it'salittlemoredifficulttodifferentiateclassesandobjectsinsoftware.Thisispartiallybecausesoftwareobjectsaremerelyelectronicmodelsofreal-worldobjectsorabstractconceptsinthefirstplace.Butit'salsobecausethetermobjectissometimesusedtorefertobothclassesandinstances.
Inillustrationssuchasthetoppartoftheprecedingfigure,theclassisnotshadedbecauseitrepresentsablueprintofanobjectratherthantheobjectitself.Incomparison,anobjectisshaded,indicatingthattheobjectexistsandthatyoucanuseit.
WhatIsInheritance?
Generallyspeaking,objectsaredefinedintermsofclasses.Youknowalotaboutanobjectbyknowingitsclass.Evenifyoudon'tknowwhatapenny-farthingis,ifItoldyouitwasabicycle,youwouldknowthatithadtwowheels,handlebars,andpedals.
Object-orientedsystemstakethisastepfurtherandallowclassestobedefinedintermsofotherclasses.Forexample,mountainbikes,roadbikes,andtandemsarealltypesofbicycles.Inobject-orientedterminology,mountainbikes,roadbikes,andtandemsareallsubclassesofthebicycleclass.Similarly,thebicycleclassisthesupclassesofmountainbikes,roadbikes,andtandems.Thisrelationshipisshowninthefollowingfigure.
Thehierarchyofbicycleclasses.
Eachsubclassinheritsstate(intheformofvariabledeclarations)fromthesuperclass.Mountainbikes,roadbikes,andtandemssharesomestates:cadence,speed,andthelike.Also,eachsubclassinheritsmethodsfromthesuperclass.Mountainbikes,roadbikes,andtandemssharesomebehaviors-brakingandchangingpedalingspeed,forexample.
However,subclassesarenotlimitedtothestatesandbehaviorsprovidedtothembytheirsuperclass.Subclassescanaddvariablesandmethodstotheonestheyinheritfromthesuperclass.Tandembicycleshavetwoseatsandtwosetsofhandlebars;somemountainbikeshaveanadditionalchainring,givingthemalowergearratio.
Subclassescanalsooverrideinheritedmethodsandprovidespecializedimplementationsforthosemethods.Forexample,ifyouhadamountainbikewithanadditionalchainring,youcouldoverridethe"changegears"methodsothattheridercouldshiftintothoselowergears.
Youarenotlimitedtojustonelayerofinheritance.Theinheritancetree,orclasshierardry,canbeasdeepasneeded.Methodsandvariablesareinheriteddownthroughthelevels.Ingeneral,thefartherdowninthehierarchyaclassappears,themorespecializeditsbehavior.
Note:Classhierarchiesshouldreflectwhattheclassesare,nothowthey'reimplemented.Whenimplementingatricycleclass,itmightbeconvenienttomakeitasubclassofthebicycleclass-afterall,bothtricyclesandbicycleshaveacurrentspeedandcadence.However,becauseatricycleisnotabicycle,it'sunwisetopubliclytiethetwoclassestogether.Itcouldconfuseusers,makethetricycleclasshavemethods(forexample,tochangegears)thatitdoesn'tneed,andmakeupdatingorimprovingthetricycleclassdifficult.
TheObjectclassisatthetopofclasshierarchy,andeachclassisitsdescendant(directlyorindirectly).AvariableoftypeObjectcanholdareferencetoanyobject,suchasaninstanceofaclassoranarray.ObjectprovidesbehaviorsthataresharedbyallobjectsrunningintheJavaVirtualMachine.Forexample,allclassesinheritObject'stoStringmethod,whichreturnsastringrepresentationoftheobject.TheManagingInheritancesectioncoverstheObjectclassindetail.
Inheritanceoffersthefollowingbenefits:
Subclassesprovidespecializedbehaviorsfromthebasisofcommonelementsprovidedbythesuperclass.Throughtheuseofinheritance,programmerscanreusethecodeinthesuperclassmanytimes.
Programmerscanimplementsuperclassescalledabstractclassesthatdefinecommonbehaviors.Theabstractsuperclassdefinesandmaypartiallyimplementthebehavior,butmuchoftheclassisundefinedandunimplemented.Otherprogrammersfillinthedetailswithspecializedsubclasses.
WhatIsanInterface?
Ingeneral,aninterfaceisadeviceorasystemthatunrelatedentitiesusetointeract.Accordingtothisdefinition,aremotecontrolisaninterfacebetweenyouandatelevisionset,theEnglishlanguageisaninterfacebetweentwopeople,andtheprotocolofbehaviorenforcedinthemilitary
上一篇:
ASP_net电子购物商城系统+论文(功能结构图、业务流程图、数据流程图、数据字典)(论文和程序)
下一篇:
试析影响公路路面平整度的因素及应采取的施工措施