Chapter 4 Polymorphm CSC 113 King Saud University College Computer and Information Sciences Department Computer Science
Objectives After you have read and studied th chapter, you should be able to Write programs that are easily extensible and modifiable by applying polymorphm in program design. Define reusable es based on inheritance and abstract es and abstract s. Differentiate abstract es and Java interfaces. Define s, using protected modifier. Parse strings, using a Tokenizer.
Introduction to Polymorphm There are three main programming mechanms that constitute -oriented programming OOP Encapsulation Inheritance Polymorphm Polymorphm ability to associate many meanings to one It does th through a special mechanm known as late binding or dynamic binding A polymorphic one that has same for different es same family, but has different implementations, or behavior, for various es.
Introduction to Polymorphm Polymorphm When a program invokes a through a super variable, correct sub version called, based on type reference stored in super variable The same and signature can cause different actions to occur, deping on type on which invoked Facilitates adding es to a system with minimal modifications to system s code
Example Demonstrating Polymorphic Behavior A polymorphic ex dplay A that has multiple meanings Created when a sub overrides a super Base dplay Doubler Tripler dplay dplay Squarer dplay
Example Demonstrating Polymorphic Behavior Base protected int i 100;... dplay System.out.println i ; Doubler exts Base... dplay System.out.println i*2 ; Tripler exts Base... dplay System.out.printlni*3 ; Squarer exts Tripler... dplay System.out.println i*i ;
Example Demonstrating Polymorphic Behavior Case Static binding Some main program output Base B Base; B. dplay; 100 Doubler D Doubler; D. dplay; 200 Tripler T Tripler; T. dplay; 300 Squarer S Squarer; S. dplay; 10000 Static binding occurs when a defined with same but with different headers and implementations. The actual code for attached, or bound, at compile time. Static binding used to support overloaded s in Java.
Example Demonstrating Polymorphic Behavior Case Dynamic binding A super reference can be aimed at a sub Th possible because a sub a super as well When invoking a from that reference, type actual referenced, not type reference, determines which called Some main program Base B Base; B. dplay; Base D; D Doubler; D. dplay; output 100 200 Late binding or dynamic binding The appropriate version a polymorphic decided at execution time Base T; T Tripler; T. dplay; 300 Base S; S Squarer; S. dplay; 10000
Example Inheritance Hierarchy Class Student Polymorphm case #NUM_OF_TESTS int 3 # string #test [] int Student Student Studentin studentname string setscorein s1 int, in s2 int, in s3 int setnamein Name string gettestscore int getcoursegrade string settestscorein testnumber int, in testname string getname string computecoursegrade GraduateStudent UnderGraduateStudent computecoursegrade computecoursegrade
Example Inheritance Hierarchy Class Student Polymorphm case Creating roster Array We mentioned in array definition that an array must contain elements same data type. For example, we can t store integers and real numbers in same array. To follow th rule, it seems necessary for us to declare two separate arrays, one for graduate and anor for undergraduate students. Th rule, however, does not apply when array elements are s using polymorphm. We only need to declare a single array. We can create roster array combining s from Student, UndergraduateStudent, and GraduateStudent es. Student roster Student[40];... roster[0] GraduateStudent; roster[1] UndergraduateStudent; roster[2] UndergraduateStudent;...
State roster Array The roster array with elements referring to instances GraduateStudent or UndergraduateStudent es.
Sample Polymorphic Message To compute course grade using roster array, we execute for int i 0; i < numberofstudents; i roster[i].computecoursegrade; If roster[i] refers to a GraduateStudent, n computecoursegrade GraduateStudent executed. If roster[i] refers to an UndergraduateStudent, n computecoursegrade UndergraduateStudent executed.
The instance Operator The instance operator can help us learn an. The following code counts number undergraduate students. int undergradcount 0; for int i 0; i < numberofstudents; i if roster[i] instance UndergraduateStudent undergradcount;
Case Study Implementation Student in Java Student Student GraduateStudent GraduateStudent exts exts Student Student protected protected final final static static int int NUM_OF_TESTS NUM_OF_TESTS 3; 3; protected protected ; ; /** /** protected protected int[] int[] test; test; * * students. students. Pass Pass if if total total > > 80; 80; orwe, orwe, No No Pass. Pass. protected protected coursegrade; coursegrade; */ */ Student Student th th No No Name; Name; computecoursegrade computecoursegrade Student Student studentname studentname int int total total 0; 0; studentname; studentname; for for int int i i 0; 0; i i < < NUM_OF_TESTS; NUM_OF_TESTS; i i test test int[num_of_tests]; int[num_of_tests]; total total test[i]; test[i]; coursegrade coursegrade ****; ****; if if total total > > 80 80 coursegrade coursegrade Pass; Pass; setscoreint setscoreint s1, s1, int int s2, s2, int int s3 s3 else else coursegrade coursegrade No No Pass; Pass; test[0] test[0] s1; s1; test[1] test[1] s2; s2; test[2] test[2] s3; s3; computecoursegrade computecoursegrade coursegrade; coursegrade; getcoursegrade getcoursegrade UnderGraduateStudent UnderGraduateStudent exts exts Student Student coursegrade; coursegrade; getname getname ; ; computecoursegrade computecoursegrade int int int gettestscoreint gettestscoreint testnumber testnumber int total total 0; 0; for test[testnumber-1]; test[testnumber-1]; for int int i i 0; 0; i i < < NUM_OF_TESTS; NUM_OF_TESTS; i i total setname setname Name Name total test[i]; test[i]; if Name; Name; if total total > > 70 70 coursegrade settestscoreint settestscoreint testnumber, testnumber, int int testscore coursegrade Pass; Pass; testscore test[testnumber-1]testscore; test[testnumber-1]testscore; else else coursegrade coursegrade No No Pass; Pass;
Implementation StudentTest in Java Case Study StudentTest StudentTest static static main[] main[] args args Student Student roster[] roster[] Student[2]; Student[2]; roster[0] roster[0] GraduateStudent; GraduateStudent; roster[1] roster[1] UnderGraduateStudent; UnderGraduateStudent; roster[0].setscore roster[0].setscore 20, 20, 30, 30, 50; 50; roster[1].setscore roster[1].setscore 10, 10, 17, 17, 13; 13; for for int int i0; i0; i<roster.length; i<roster.length; i i System.out.printlnThe System.out.printlnThe roster[i].getclass.getname; roster[i].getclass.getname; roster[i].computecoursegrade; roster[i].computecoursegrade; System.out.println System.out.println Pass Pass or or Not Not roster[i].getcoursegrade; roster[i].getcoursegrade; ------ execution------------------ The GraduateStudent Pass or Not Pass The UnderGraduateStudent Pass or Not No Pass If roster[i] refers to a GraduateStudent, n computecoursegrade GraduateStudent executed. If roster[i] refers to a UnderGraduateStudent, n computecoursegrade UnderGraduateStudent executed. We call message computecoursegrade polymorphic
Implementation StudentTest2 in Java Case Study Question Count number under graduate students StudentTest2 StudentTest2 static static main[] main[] args args Student Student roster[] roster[] Student[2]; Student[2]; roster[0] roster[0] GraduateStudent; GraduateStudent; roster[1] roster[1] UnderGraduateStudent; UnderGraduateStudent; roster[0].setscore roster[0].setscore 20, 20, 30, 30, 50; 50; roster[1].setscore roster[1].setscore 10, 10, 17, 17, 13; 13; int int nb0; nb0; count count number number Under Under Graduate Graduate Students Students for for int int i0; i0; i<roster.length; i<roster.length; i i if if roster[i] roster[i] instance instance UnderGraduateStudent UnderGraduateStudent nb; nb; System.out.println The System.out.println The number number Under Under Graduate Graduate Students Students nb; nb; ------ execution------------------ The number Under Graduate Students 1 Rule To Determine an, we use instance operator.
Example Inheritance Hierarchy Class dplay dplays area and perimeter Of a shape area perimeter dplay Rectangle -width -length Rectanglein wid, in leng getwidth getlength area perimeter Square -side Squarein sid getside area perimeter
Test inheritance Super-Class Test Test static static main[] main[] args args shp shp ; ; shp shp an an from from Rectangle Rectangle rect rect Rectangle4.0, Rectangle4.0, 5.0; 5.0; rect rect an an from from Rectangle Rectangle Square Square sqr sqr Square6.0; Square6.0; sqr sqr an an from from Square Square shp.dplay; shp.dplay; --- --- uses uses dplay dplay from from rect.dplay; rect.dplay; --- --- rect rect inherits inherits dplay dplay from from Super Super sqr.dplay; sqr.dplay; --- --- sqr sqr inherits inherits dplay dplay from from Super Super ---- ---- execution execution -------- -------- The The The The area area The The perimeter perimeter The The Rectangle Rectangle The The area area 2 2 The The perimeter perimeter 13.0 13.0 The The Square Square The The area area 36.0 36.0 The perimeter 24.0
Case Study 3 Implementation inheritance in Java area area ; ; perimeter perimeter ;; ;; dplay dplay System.out.printlnThe System.out.printlnThe th.getclass.getname; th.getclass.getname; --- --- getclass getclass a a inherits inherits from from super super Object. Object. --- --- getname getname a a from from.. System.out.printlnThe System.out.printlnThe area area area; area; System.out.printlnThe System.out.printlnThe perimeter perimeter perimeter\n\n; perimeter\n\n; Rectangle Rectangle exts exts width; width; length; length; Rectangle Rectangle length, length, width width th.length th.length length; length; th.width th.width width; width; getlength getlength length; length; getwidth getwidth width; width; area area th.getlength*th.getwidth; th.getlength*th.getwidth; perimeter perimeter 2*th.getLengthth.getWidth; 2*th.getLengthth.getWidth; Square Square exts exts side; side; Square Square side side th.side th.side side; side; getside getside side; side; area area th.getside*th.getside; th.getside*th.getside; perimeter perimeter 4*th.getSide; 4*th.getSide;
Introduction to Abstract Classes In following example, we want to add to a dplay that prints area and perimeter a shape. # color string Rectangle -width -length Rectanglein wid, in leng getwidth getlength area perimeter Square -side Squarein sid getside area perimeter
Introduction to Abstract Classes Abstract Method The following added to dplay System.out.println th.area; System.out.println th.perimeter;
Introduction to Abstract Classes Abstract Method There are several problems with th The area and perimeter s are invoked in dplay There are area and perimeter s in each subes There no area and perimeter s in, nor re any way to define it reasonably without knowing wher shape Rectangle or Square.
Abstract Class Introduction to Abstract Classes In order to postpone definition a, Java allows an abstract to be declared An abstract has a heading, but no body The body defined in subes The that contains an abstract called an abstract
Introduction to Abstract Classes Abstract Method An abstract like a placeholder for a that will be fully defined in a descent It has a complete heading, to which has been added modifier abstract It cannot be It has no body, and s with a semicolon in place its body abstract area; abstract perimeter;
Introduction to Abstract Classes # color string dplay dplays area and perimeter a shape area perimeter dplay Rectangle -width -length Rectanglein wid, in leng getwidth getlength area perimeter Square -side Squarein sid getside area perimeter
Introduction to Abstract Classes A that has at least one abstract called an abstract An abstract must have modifier abstract included in its heading abstract protected color;... abstract area; abstract perimeter; dplay System.out.println th.area; System.out.println th.perimeter;...
Introduction to Abstract Classes An abstract can have any number abstract and/or fully defined s If a derived an abstract adds to or does not define all abstract s, n it abstract also, and must add abstract to its modifier A that has no abstract s called a concrete
Pitfall You Cannot Create Instances an Abstract Class An abstract can only be used to derive more specialized es While it may be useful to dcuss shape in general, in reality a shape must be a rectangle form or a square form An abstract cannot be used to create an abstract However, a sub will include an invocation abstract in form super
Dynamic Binding and Abstract Classes Controlling wher a sub can override a super Field modifier final Prevents a from being overridden by a sub Field modifier abstract Requires sub to override Early binding or static binding The appropriate version a decided at compilation time Used by s that are final or static
hierarchy UML diagram.
Example Inheritance Hierarchy Class -fname string -lname string -ssn string setfirstnamein fna string setlastnamein lname string setsnnin snn string getfirstname string getlastname string getsnn string earnings to Salaried -weeklysalary earnings to string...... Commssion -grosssales -commsionrate earnings to string...... Hourly -wage -hours earnings to string...... BasePlusCommssion -basesalary earnings to......
Case Study Implementation in Java abstract abstract firstname; firstname; lastname; lastname; socialsecuritynumber; socialsecuritynumber; three-argument three-argument ssn ssn firstname firstname first; first; lastname lastname last; last; socialsecuritynumber socialsecuritynumber ssn; ssn; three-argument three-argument set set first first setfirstname setfirstname first first firstname firstname first; first; setfirstname setfirstname first first getfirstname getfirstname firstname; firstname; getfirstname getfirstname set set last last setlastname setlastname last last lastname lastname last; last; Dr. S. HAMMAMI setlastname setlastname last last getlastname getlastname lastname; lastname; getlastname getlastname set set social social security security number number setsocialsecuritynumber setsocialsecuritynumber ssn ssn socialsecuritynumber socialsecuritynumber ssn; ssn; should should validate validate setsocialsecuritynumber setsocialsecuritynumber social social security security number number getsocialsecuritynumber getsocialsecuritynumber socialsecuritynumber; socialsecuritynumber; getsocialsecuritynumber getsocialsecuritynumber representation representation to to The The getfirstname getfirstname getlastname getlastname \nthe \nthe Social Social Security Security Number Number getsocialsecuritynumber getsocialsecuritynumber ; ; to to abstract abstract overridden overridden by by subes subes abstract abstract earnings; earnings; no no implementation implementation here here abstract abstract
Implementation Salaried in Java Case Study Salaried Salaried exts exts calculate calculate earnings; earnings; override override abstract abstract earnings earnings in weeklysalary; in weeklysalary; four-argument four-argument earnings earnings Salaried Salaried getweeklysalary; getweeklysalary; ssn, ssn, earnings earnings super super ssn ssn code code reuse representation representation Salaried Salaried reuse super super ssn ssn ; ; pass pass to to setweeklysalary setweeklysalary ; ; validate validate and and store store th th override override to to super super four-argument four-argument Salaried Salaried to to ***** ***** super.to super.to code code reuse reuse good good example set set example setweeklysalary setweeklysalary super.to super.to \nearnings \nearnings getweeklysalary; getweeklysalary; weeklysalary weeklysalary < <?? ; to to ; th th mean mean that, that, if if <0 <0 n n put put it it 0 0 else else put put it it Salaried Salaried setweeklysalary setweeklysalary getweeklysalary getweeklysalary weeklysalary; weeklysalary; getweeklysalary getweeklysalary
Implementation Hourly in Java Case Study Hourly Hourly exts exts wage; wage; wage wage per per hour hour hours; hours; hours hours worked worked for for week week five-argument five-argument Hourly Hourly ssn, ssn, hourlywage, hourlywage, hoursworked hoursworked super super ssn ssn code code reuse reuse super super ssn ssn ; ; setwage setwage hourlywage hourlywage ; ; validate validate and and store store hourly hourly wage wage sethours sethours hoursworked hoursworked ; ; validate validate and and store store hours hours worked worked five-argument five-argument Hourly Hourly setwage setwage hourlywage hourlywage wage wage hourlywage hourlywage < <?? hourlywage; hourlywage; setwage setwage getwage getwage wage; wage; getwage getwage sethours sethours hoursworked hoursworked hours hours hoursworked hoursworked > > && && hoursworked hoursworked < < 168.0 168.0?? hoursworked hoursworked ; ; sethours sethours gethours gethours hours; hours; gethours gethours calculate calculate earnings; earnings; override override abstract abstract earnings earnings in in earnings earnings if if gethours gethours < < 40 40 no no overtime overtime getwage getwage * * gethours; gethours; else else 40 40 * * getwage getwage gethours gethours - - 40 40 * * getwage getwage * * 1.5; 1.5; earnings earnings representation representation Hourly Hourly to to /* /* here here overriding overriding to to super super */ */ /*code /*code reuse reuse using using super. super. */ */ super.to super.to \nhourly \nhourly wage wage getwage getwage \nhours \nhours worked worked gethours gethours \nsalary \nsalary earnings earnings ; ; to to Hourly Hourly
Implementation Comsion in Java Case Study Commsion Commsion exts exts grosssales; grosssales; gross gross weekly weekly sales sales commsionrate; commsionrate; commsion commsion percentage percentage five-argument five-argument Commsion Commsion ssn, ssn, sales, sales, rate rate super super ssn ssn ; ; setgrosssales setgrosssales sales sales ; ; setcommsionrate setcommsionrate rate rate ; ; five-argument five-argument Commsion Commsion set set commsion commsion rate rate setcommsionrate setcommsionrate rate rate commsionrate commsionrate rate rate > > && && rate rate < < 1.0 1.0?? rate rate ; ; setcommsionrate setcommsionrate commsion commsion rate rate getcommsionrate getcommsionrate commsionrate; commsionrate; getcommsionrate getcommsionrate set set gross gross sales sales amount amount setgrosssales setgrosssales sales sales grosssales grosssales sales sales < <?? sales; sales; setgrosssales setgrosssales gross gross sales sales amount amount getgrosssales getgrosssales grosssales; grosssales; getgrosssales getgrosssales calculate calculate earnings; earnings; override override abstract abstract earnings earnings in in earnings earnings getcommsionrate getcommsionrate * * getgrosssales; getgrosssales; earnings earnings representation representation Commsion Commsion to to super.to super.to \ngross \ngross sales sales getgrosssales getgrosssales \ncommsion \ncommsion rate rate getcommsionrate getcommsionrate \nearnings \nearnings earnings earnings ; ; to to Commsion Commsion
Implementation BasePlusComsion in Java Case Study BasePlusCommsion BasePlusCommsion exts exts Commsion Commsion basesalary; basesalary; base base per per week week six-argument six-argument BasePlusCommsion BasePlusCommsion ssn, ssn, sales, sales, rate, rate, super super ssn, ssn, sales, sales, rate rate ; ; setbasesalary setbasesalary ; ; validate validate and and store store base base six-argument six-argument BasePlusCommsion BasePlusCommsion set set base base setbasesalary setbasesalary basesalary basesalary < <?? ; ; nonnegative nonnegative setbasesalary setbasesalary calculate calculate earnings; earnings; override override earnings earnings in in Commsion Commsion earnings earnings getbasesalary getbasesalary super.earnings; super.earnings; code code reuse reuse form form Commsion Commsion earnings earnings representation representation BasePlusCommsion BasePlusCommsion to to \nbase-salaried \nbase-salaried super.to super.to \nbase \nbase getbasesalary getbasesalary \nearnings \nearnings earnings earnings ; ; to to BasePlusCommsion BasePlusCommsion base base getbasesalary getbasesalary basesalary; basesalary; getbasesalary getbasesalary
Implementation PayrollSystemTest in Java PayrollSystemTest PayrollSystemTest static static main main args[] args[] create create sub sub s s Salaried Salaried SA SA Salaried Salaried Ali, Ali, Samer, Samer, 111-11-1111, 111-11-1111, 800 800 ; ; Hourly Hourly HE HE Hourly Hourly Ramzi, Ramzi, Ibrahim, Ibrahim, 222-22-2222, 222-22-2222, 16.75, 16.75, 40 40 ; ; Commsion Commsion CE CE Commsion Commsion Med, Med, Ahmed, Ahmed, 333-33-3333, 333-33-3333, 10000, 10000,.06.06 ; ; BasePlusCommsion BasePlusCommsion BP BP BasePlusCommsion Beji, BasePlusCommsion Beji, Lotfi, Lotfi, 444-44-4444, 444-44-4444, 5000, 5000,.04,.04, 300 300 ; ; System.out.println System.out.println s s processed processed individually\n individually\n ; ; /* /* salaried salaried same same as as salaried.to salaried.to */ */ System.out.println System.out.println SA.to SA.to \nearned \nearned SA.earnings\n\n SA.earnings\n\n ; ; System.out.println System.out.println HE HE \n \n earned earned HE.earnings\n\n HE.earnings\n\n ; ; System.out.printlnCE System.out.printlnCE \n \n earned earned CE.earnings\n\n CE.earnings\n\n ; ; System.out.printlnBP System.out.printlnBP \n \n earned earned BP.earnings\n\n BP.earnings\n\n ; ; create create four-element four-element array array employees[] employees[] [ [ 4 4 ]; ]; employees[ employees[ 0 0 ] ] SA; SA; employees[ employees[ 1 1 ] ] HE; HE; employees[ employees[ 2 2 ] ] CE; CE; employees[ employees[ 3 3 ] ] BP; BP; System.out.println System.out.println s s processed processed polymorphically\n polymorphically\n ; ; generically generically process process each each element element in in array array employees employees for for current current employees employees System.out.println System.out.println current current ; ; invokes invokes to to here here polymorphysim polymorphysim call call to to at at executiontime. executiontime. called called dynamic dynamic binding binding or or late late binding binding Note Note only only s s super super can can be be called called via via super super variable variable get get type type each each in in employees employees array array for for int int j j 0; 0; j j < < employees.length; employees.length; j j System.out.printf System.out.printf %d %d a a %s\n, %s\n, j, j, employees[ employees[ j j ].getclass.getname ].getclass.getname ; ; dplay dplay whos whos employee[j] employee[j] Dr. S. HAMMAMI main main PayrollSystemTest PayrollSystemTest