encapsulation, inheritance & polymorphism. oop properties encapsulation the process of creating...
TRANSCRIPT
Computer Science
Encapsulation, Inheritance & Polymorphism
OOP PropertiesEncapsulation
Theprocessofcreatingprogramssothatinformationwithinaclassisnotaccessiblefromanoutsideclass.
Theattributesandbehavioursofthatclasscannotbechangedfromoutsideoftheclass
Inheritance Theabilitytocreatenewclassesthatarebasedonexistingones
Polymorphism Theabilitytocreatemethodsthatperformageneralfunction,whichautomaticallyadaptsitselftoworkwithobjectsofdifferentclasses
EncapsulationEncapsulationmeanshidingthedetailsofanobjectfromtheotherpartsofaprogram.
Theobjectcanbeusedonlythroughitsaccess methods,whicharecarefullywrittentokeeptheobjectconsistentandsecure.
Example:TheinnerworkingofaTVareencapsulatedbythescreenandplasticframe.TheremotecontroloruserinterfaceallowsyoutoaccesstheTV.
InJava,theuserinterfaceiscontrolledbytheaccess modifiers
Access Control ModifiersPrivateAccessModifier
Amemberintheclasscanonlybythemethodsofthatclass.
PublicAccessModifier Allowsamemberintheclasstobeaccessedbycodeoutsideofthatclass
Encapsulation at WorkClass CheckingAccount { private String accountNumber; private String accountHolder; private int balance; private int useCount = 0; public CheckingAccount( String accNumber, String holder, int start ) { . . . . } private void incrementUse() { .. . . } public int getBalance() { . . . . } public void processDeposit( int amount ) { . . . . } public void processCheck( int amount ) { . . . . } }
Only accessed in CheckingAccount Class
Accessed Outside of the Class
InheritanceInheritanceenablesyoutodefineanewclassbaseduponanexistingclass.
Thenewclassissimilartotheexistingclass,buthasadditionalmembervariablesandmethods.
Thismakesprogrammingeasierbecauseyoucanbuilduponanexistingclassinsteadofstartingoutfromscratch.
Parents and ChildrenTheclassthatdefinesthenewclassisknownas
Theparentclass Thesuperclass Thebaseclass
Aclassthatisbasedontheparentclassisknownas Thechild class Thesubclass Thederivedclass.
Thechildclassesinheritsthecharacteristicsoftheparentclass
InJavathereisoneparentformultiplechilds.
Inheritance between classes not objectsRememberclassesarelikeblueprintsYoucanhavemanyobjectsforthesameclassWhatthismeans
ParentandChildclassescanhaveseveralobjectseachExample:
Parentclass``Automobile``hasoneobject Joe`sCar
ChildClass``Ford``hastwoobjects Mary`sFord,Bob`sFord
Note: A class may be the parent for a child class and may be a child of another class.class childClass extends parentClass {...}
Using Inheritanceclass Video { String title; // name of the item int length; // number of minutes boolean avail; // availability} class Movie extends Video { String director; // name of the director String rating; // G, PG, R, or Xpublic Movie( String ttl, int lngth, String dir, String rtng ) { // constructor super( ttl, lngth ); // uses the super class's constructor director = dir; rating = rtng; // initialize what's new to Movie } }
member
title inheritedfromVideo
length inheritedfromVideo
avail inheritedfromVideo
show() inheritedfromVideo
director definedinMovie
rating definedinMovie
Note: use reserved super() class to ensure inheritance of parent class –always place first in constructor –anywhere in method
Polymorphism & the abstract classRecallthatpolymorphismisabilitytocreatemethodsthatperformageneralfunction,whichcanthenadapttoworkwithotherobjectindifferentclasses
Theabstract classisaspecialclassthatisneverinstantiated.Itspurposeistobeaparenttoseveralrelatedclasses.Thechildrenclassesinheritfromtheabstractparentclass. abstractclassClassName
Abstract MethodsAbstractMethodscanbeincludedintheabstractclassThepurposeoftheabstract method istoensurethatalltypesobjectscanusethemethodsoftheparentclass.
Example Classcards–haspropertiesofgreetingcards VarioustypesofCards–Birthday,Mother’sDay ThegreetingforabirthdaycardwillbedifferentfromthegreetingoftheMother’sdaycard
UsingtheAbstractmethodensuresthecorrectgreetingisonthecorrectobject
Anabstract methodhasnobody.(Ithasnostatements.) Itdeclaresanaccessmodifier,returntype,andmethodsignaturefollowedbyasemicolon.
Example of the Abstractabstract class Card { String recipient; // name of who gets the card public abstract void
greeting(); // abstract greeting() method }
Polymorphism without the AbstractPolymorphismmeans"havingmanyforms.“Forexample:asinglevariablemightbeusedwithseveralobjectsofrelatedclassesatdifferenttimesinaprogram.
Whenthevariableisusedtoinvokeamethod,exactlywhichmethodisrundependsontheobjectthatthevariablecurrentlyrefersto.
Examplepublic class CardTester { public static void main ( String[] args ) { Card card = new Holiday( "Amy" ); card.greeting(); //Invoke a Holiday greeting() card = new Valentine( "Bob", 3 ); card.greeting(); //Invoke a Valentine greeting() card = new Birthday( "Cindy", 17 ); card.greeting(); //Invoke a Birthday greeting() } }