Polymorphism & Abstract
Polymorphism & Abstract
Polymorphism
CSC 113
King Saud University
College of Computer and Information Sciences
Department of Computer Science
Dr. S. HAMMAMI
Dr. S. HAMMAMI
Objectives
• After you have read and studied this chapter, you should be able to
Dr. S. HAMMAMI
Introduction to Polymorphism
• A polymorphic method is one that has the same name for different
classes of the same family, but has different implementations, or
behavior, for the various classes.
Dr. S. HAMMAMI
Introduction to Polymorphism
• Polymorphism
– The same method name and signature can cause different actions to
occur, depending on the type of object on which the method is
invoked
Dr. S. HAMMAMI
Example: Demonstrating Polymorphic Behavior
A polymorphic method (ex: display() )
– A method that has multiple meanings
– Created when a subclass overrides a
method of the superclass
Base
+ display()
Tripler
Doubler
+ display()
+ display()
Squarer
+ display()
Dr. S. HAMMAMI
Example: Demonstrating Polymorphic Behavior
...
public void display() { System.out.println( i );
}}
Dr. S. HAMMAMI
Example: Demonstrating Polymorphic Behavior
Case: Static binding
Some main program output
Static binding occurs when a method is defined with the same name but with
different headers and implementations. The actual code for the method is
attached, or bound, at compile time. Static binding is used to support
overloaded methods in Java.
Dr. S. HAMMAMI
Example: Demonstrating Polymorphic Behavior
Case: Dynamic binding
•A superclass reference can be aimed at a subclass object
–This is possible because a subclass object is a superclass object as well
–When invoking a method from that reference, the type of the actual referenced
object, not the type of the reference, determines which method is called
Base S;
S = new Squarer();
S. display(); 10000
Dr. S. HAMMAMI
Example: Inheritance Hierarchy of Class Student : Polymorphism case
S tu d e n t
# N U M _ O F _ T E S T S : in t = 3
# n a m e : strin g
# te st [] : in t
+ S tu d e n t()
+ S tu d e n t(in s tu d e n tN a m e : strin g )
+ s e tS c o re (in s1 : in t, in s2 : in t, in s3 : in t)
+ s e tN a m e (in n e w N a m e : s trin g )
+ g e tT e stS co re () : in t
+ g e tC o u rse g ra d e () : strin g
+ s e tT e stS c o re (in te stN u m b e r : in t, in te s tN a m e : strin g )
+ g e tN a m e () : strin g
+ c o m p u te C o u rse G ra d e ()
G ra d u a te S tu d e n t U n d e rG ra d u a te S tu d e n t
+ co m p u te C o u rse G ra d e () + co m p u te C o u rse G ra d e ()
Dr. S. HAMMAMI
Example: Inheritance Hierarchy of Class Student : Polymorphism case
Creating the roster Array
• We mentioned in array definition that an array must contain elements of
the same data type. For example, we can’t store integers and real numbers
in the same array.
• To follow this rule, it seems necessary for us to declare two separate
arrays, one for graduate and another for undergraduate students. This rule,
however, does not apply when the array elements are objects using the
polymorphism. We only need to declare a single array.
• We can create the roster array combining objects from the Student,
UndergraduateStudent, and GraduateStudent classes.
Dr. S. HAMMAMI
State of the roster Array
Dr. S. HAMMAMI
Sample Polymorphic Message
Dr. S. HAMMAMI
The instanceof Operator
int undergradCount = 0;
for (int i = 0; i < numberOfStudents; i++) {
if ( roster[i] instanceof UndergraduateStudent ) {
undergradCount++;
}
}
Dr. S. HAMMAMI
Implementation Student in Java
Case Study :
class
classStudent
Student{{ class
classGraduateStudent
GraduateStudentextends extendsStudent
Student
protected
protected final
finalstatic
staticint
intNUM_OF_TESTS
NUM_OF_TESTS==3;3; {{
protected
protected String
String name;
name; /**
/**
protected int[] test; **students.
protected int[] test; students.PassPassififtotal
total>=
>=80;
80;otherwise,
otherwise,NoNoPass.
Pass.
protected String
protected String courseGrade;
courseGrade; */*/
public
public Student( ) { this ("NoName");
Student( ) { this ("No Name");}} public
publicvoid voidcomputeCourseGrade()
computeCourseGrade(){{
public
publicStudent(String
Student(StringstudentName)
studentName){{ int
inttotal
total==0;0;
name
name==studentName; for
studentName; for(int
(inti i==0;0;i i<<NUM_OF_TESTS;
NUM_OF_TESTS;i++) i++){{
test
test = newint[NUM_OF_TESTS];
= new total
int[NUM_OF_TESTS]; total+=+=test[i];
test[i];}}
courseGrade
courseGrade=="****"; ifif(total
"****"; (total>= >=80)
80){{
}} courseGrade
courseGrade=="Pass"; "Pass";
public
publicvoid
voidsetScore(int
setScore(ints1, s1,int
ints2,
s2,int
ints3)
s3){{ }}else
else { courseGrade=="No
{ courseGrade "NoPass";
Pass"; }}
test[0]
test[0]==s1;
s1;test[1]
test[1]==s2;s2;test[2]
test[2]==s3;s3; }}
}} }}
public
publicvoid
voidcomputeCourseGrade()
computeCourseGrade(){{courseGrade="";}
courseGrade="";}
class
classUnderGraduateStudent
UnderGraduateStudentextends
extendsStudent
Student{{
public
publicString
StringgetCourseGrade(
getCourseGrade() ){{
return
returncourseGrade;
courseGrade; }} public
public publicvoidvoidcomputeCourseGrade()
computeCourseGrade(){{
publicString
StringgetName(
getName() ){{return
returnname;
name;}} int
inttotal
total==0;0;
public
publicint
intgetTestScore(int
getTestScore(inttestNumber)
testNumber){{ for
return for(int
(inti i==0;0;i i<<NUM_OF_TESTS;
NUM_OF_TESTS;i++) i++){{
returntest[testNumber-1];
test[testNumber-1]; }} total
total+=+=test[i];
test[i];}}
public
publicvoid
voidsetName(String
setName(StringnewName)
newName){{ ifif(total
name (total>= >=70)
70){{
name==newName;
newName; }} courseGrade
courseGrade=="Pass"; "Pass";
public
publicvoid
voidsetTestScore(int
setTestScore(inttestNumber,
testNumber,int
inttestScore) }}else
{{ test[testNumber-1]=testScore; }
testScore) else { courseGrade=="No
{ courseGrade "NoPass";
Pass"; }}
test[testNumber-1]=testScore; } }}
}} }}
Dr. S. HAMMAMI
Implementation StudentTest in Java
Case Study :
public
publicclass
classStudentTest
StudentTest {{
public
publicstatic
staticvoid
voidmain(String[]
main(String[]args)
args)
{{
Student
Studentroster[]=
roster[]=new
newStudent[2];
Student[2];
roster[0] = new GraduateStudent();
roster[0] = new GraduateStudent();
roster[1]
roster[1]==new
new UnderGraduateStudent();
UnderGraduateStudent();
roster[0].setScore
roster[0].setScore(20,
(20,30,
30,50);
50);
roster[1].setScore (10, 17, 13);
roster[1].setScore (10, 17, 13);
for
for(int
(inti=0;
i=0;i<roster.length;
i<roster.length;i++)
i++)
{{
System.out.println("The
System.out.println("Thename
nameofofthe
theclass
classisis: :""++ roster[i].getClass().getName());
roster[i].getClass().getName());
roster[i].computeCourseGrade();
roster[i].computeCourseGrade();
System.out.println("
System.out.println("Pass
PassororNot
Not : :""++roster[i].getCourseGrade());
roster[i].getCourseGrade());
}}
}}
}}
------ execution------------------
If roster[i] refers to a GraduateStudent, then the
computeCourseGrade method of the GraduateStudent class is
The name of the class is : GraduateStudent executed.
Pass or Not : Pass
The name of the class is : UnderGraduateStudent If roster[i] refers to a UnderGraduateStudent, then the
computeCourseGrade method of the UnderGraduateStudent
Pass or Not : No Pass
class is executed.
public
publicclass
classStudentTest2
StudentTest2 {{
public
publicstatic
staticvoid
voidmain(String[]
main(String[]args)
args)
{{
Student
Studentroster[]=
roster[]=new
newStudent[2];
Student[2];
roster[0] = new GraduateStudent();
roster[0] = new GraduateStudent();
roster[1]
roster[1]==new
new UnderGraduateStudent();
UnderGraduateStudent();
roster[0].setScore
roster[0].setScore(20,(20,30,
30,50);
50);
roster[1].setScore (10, 17, 13);
roster[1].setScore (10, 17, 13);
int
intnb=0;
nb=0; //===
//===count
countthe
thenumber
numberofofUnder
UnderGraduate
GraduateStudents
Students
for (int i=0; i<roster.length; i++)
for (int i=0; i<roster.length; i++)
ifif(roster[I]
(roster[I]instanceof
instanceofUnderGraduateStudent
UnderGraduateStudent) )
nb++;
nb++;
System.out.println(“The
System.out.println(“Thenumber
numberofofUnder
UnderGraduate
GraduateStudents
Students: :""++nb);
nb);
}} }} }}
------ execution------------------
Rectangle Square
-width : double -side : double
-length : double +Square(in sid : double)
+Rectangle(in wid : double, in leng : double) +getSide() : double
+getWidth() : double +area() : double
+getLength() : double +perimeter() : double
+area() : double
+perimeter() : double
Dr. S. HAMMAMI
Test: inheritance of Super-Class Shape
public
publicclass
classShapeTest
ShapeTest{{
public
publicstatic
staticvoid
voidmain(String[]
main(String[]args)
args)
{{
Shape
Shapeshp
shp=new
=newShape();
Shape(); ////shp
shpisisan
anobject
objectfrom
fromclass
classShape
Shape
Rectangle
Rectangle rect =new Rectangle(4.0, 5.0); // rect is an objectfrom
rect =new Rectangle(4.0, 5.0); // rect is an object fromclass
classRectangle
Rectangle
Square sqr = new Square(6.0); // sqr is an object from class
Square sqr = new Square(6.0); // sqr is an object from class SquareSquare
shp.display();
shp.display(); //---
//---uses
usesthe
themethod
methoddisplay()
display()from
fromthe
theclass
classShape
Shape
rect.display();
rect.display(); //--- object rect inherits method display() fromSuperclass
//--- object rect inherits method display() from SuperclassShape
Shape
sqr.display(); //--- object sqr inherits method display() from Superclass Shape
sqr.display(); //--- object sqr inherits method display() from Superclass Shape
}}
}}
----
----execution
execution--------
--------
The
The name of theclass
name of the classisis: :Shape
Shape
The area is :0.0
The area is :0.0
The
Theperimeter
perimeterisis:0.0
:0.0
The
Thename
nameofofthe
theclass
classisis: :Rectangle
Rectangle
The area is :20.0
The area is :20.0
The
Theperimeter
perimeterisis:13.0
:13.0
The
Thename
nameofofthe
theclass
classisis: :Square
Square
The area is :36.0
The area is :36.0
Dr. S. HAMMAMI The
Theperimeter
perimeterisis:24.0
:24.0
Implementation inheritance in Java
public
publicclass
classShape
Shape {{
Case Study 3: public
publicdouble
doublearea()
area() {{ return
return0.0;0.0; }}
Shape public
publicdouble
doubleperimeter()
perimeter(){{return
return0.0;};
0.0;};
public void display()
public void display() {{
System.out.println("The
System.out.println("Thename
nameofofthe theclass
classisis: :""++ this.getClass().getName());
this.getClass().getName());
//---
//--- getClass() a method inherits from the super classObject.
getClass() a method inherits from the super class Object.
//--- getName() a method from the class String.
//--- getName() a method from the class String.
System.out.println("The
System.out.println("Theareaareaisis:"+
:"+area());
area());
System.out.println("The
System.out.println("The perimeter is:"+
perimeter is :"+perimeter()+"\n\n");}
perimeter()+"\n\n");}
}}
public
publicclass
classRectangle
Rectangleextends
extendsShape
Shape{{
private
privatedouble
doublewidth;
width;
private double length;
private double length;
public
publicRectangle(double
Rectangle(doublelength,
length,double
doublewidth) public
{{ this.length = length; this.width =
width)
width; publicclass
classSquare
Squareextends
extendsShape
Shape {{
this.length = length; this.width = width; private
privatedouble
doubleside;
side;
}} public
public public Square(doubleside)
Square(double side){{ this.side
this.side==side;
side;}}
publicdouble
doublegetLength()
getLength(){return
{returnlength;
length;}} public
publicdouble
doublegetSide()
getSide(){{ return
returnside;
side; }}
public
publicdouble
doublegetWidth()
getWidth() {return
{returnwidth;
width;}} public
public publicdouble
doublearea()
area(){{
publicdouble
doublearea(){
area(){ return
return(this.getSide()*this.getSide());
(this.getSide()*this.getSide());
return (this.getLength()*this.getWidth());
return (this.getLength()*this.getWidth()); }}
}} public
public publicdouble
doubleperimeter()
perimeter(){{
publicdouble
doubleperimeter(){
perimeter(){ return
return(4*this.getSide());
(4*this.getSide());
return
return (2*this.getLength()+this.getWidth());}}
(2*this.getLength()+this.getWidth()); }}
Dr. S. HAMMAMI }}
}}
Introduction to Abstract Classes
In the following example, we want to add to the Shape class a display
method that prints the area and perimeter of a shape.
Shape
# color: string
Rectangle Square
-width : double -side : double
-length : double +Square(in sid : double)
+Rectangle(in wid : double, in leng : double) +getSide() : double
+getWidth() : double +area() : double
+getLength() : double +perimeter() : double
+area() : double
+perimeter() : double
Dr. S. HAMMAMI
Introduction to Abstract Classes
Abstract Method
Dr. S. HAMMAMI
Introduction to Abstract Classes
Abstract Method
Dr. S. HAMMAMI
Introduction to Abstract Classes
Abstract Class
Dr. S. HAMMAMI
Introduction to Abstract Classes
Abstract Method
• An abstract method is like a placeholder for a method that will be
fully defined in a descendent class
• It cannot be private
Dr. S. HAMMAMI
Introduction to Abstract Classes
Shape
# color: string
Rectangle Square
-width : double -side : double
-length : double +Square(in sid : double)
+Rectangle(in wid : double, in leng : double) +getSide() : double
+getWidth() : double +area() : double
+getLength() : double +perimeter() : double
+area() : double
+perimeter() : double
Dr. S. HAMMAMI
Introduction to Abstract Classes
Dr. S. HAMMAMI
Pitfall: You Cannot Create Instances of an
Abstract Class
Dr. S. HAMMAMI
Dynamic Binding and Abstract Classes
Dr. S. HAMMAMI
Employee hierarchy UML class diagram.
Dr. S. HAMMAMI
Example: Inheritance Hierarchy of Class Employee
Employee
-fName : string
-lName : string
-ssn : string
+Employee()
+setFirstName(in fNa : string)
+setLastName(in lName : string)
+setSNN(in snn : string)
+getFirstName() : string
+getLastName() : string
+getSNN() : string
+earnings() : double
+toString()
CommssionEmployee HourlyEmployee
SalariedEmployee
-grossSales : double -wage : double
-weeklySalary : double
-commissionRate : double -hours : double
+earnings() : double
+earnings() : double +earnings() : double
+toString() : string
+toString() : string +toString() : string
+.....() +......()
+......()
+....() +....()
+......()
BasePlusCommssionEmployee
-baseSalary : double
+earnings()
+toString()
+.......()
+........()
Dr. S. HAMMAMI
Implementation Employee in Java
Case Study :
public ////return
returnlast
lastname
publicabstract
abstractclass
classEmployee
Employee name
{{ public
public StringgetLastName()
String getLastName()
private {{
privateString
StringfirstName;
firstName;
private String lastName; return
returnlastName;
lastName;
private String lastName;
private }}////end
end methodgetLastName
method
privateString
StringsocialSecurityNumber;
socialSecurityNumber; getLastName
////set
set social securitynumber
social security number
////three-argument public
public void setSocialSecurityNumber(String
void setSocialSecurityNumber( Stringssn
ssn) )
three-argumentconstructor
constructor
public {{ socialSecurityNumber
socialSecurityNumber==ssn;ssn;////should
shouldvalidate
public Employee( Stringfirst,
Employee( String first,String
Stringlast,
last,String
Stringssn
ssn validate
)) }}////end method setSocialSecurityNumber
end method setSocialSecurityNumber
{{ firstName
firstName==first;
first; lastName
lastName==last;
last;
socialSecurityNumber = ssn; ////return
returnsocial
socialsecurity
securitynumber
number
socialSecurityNumber = ssn;
}}////end public String getSocialSecurityNumber()
endthree-argument
three-argumentEmployee
Employeeconstructor
constructor public String getSocialSecurityNumber()
{{ return
returnsocialSecurityNumber;
socialSecurityNumber;
////set }}////end
end methodgetSocialSecurityNumber
method
setfirst
firstname
name getSocialSecurityNumber
public
public voidsetFirstName(
void setFirstName(String
Stringfirst
first) )
{{ firstName ////return
returnString
Stringrepresentation
representationofofEmployee
Employeeobject
firstName==first;
first; object
}}////end method setFirstName public String toString()
public String toString()
end method setFirstName
{return
{return("The
("Thename
nameisis:"+
:"+getFirstName()+"
getFirstName()+""+
"+
////return getLastName()
getLastName() + "\nThe Social Security Number:"+
+ "\nThe Social Security Number:
returnfirst
firstname
name "+
public String getFirstName() getSocialSecurityNumber()
getSocialSecurityNumber() ); );
public String getFirstName()
{{return }}////end
endmethod
methodtoString
returnfirstName;
firstName; toString
}}////end
end methodgetFirstName
method getFirstName
////set last name ////abstract
abstractmethod
methodoverridden
overriddenby
bysubclasses
subclasses
set last name
public public
public abstract double earnings();////no
abstract double earnings();
publicvoid
voidsetLastName(
setLastName(String
Stringlast
last) ) no
{lastName implementation here
{lastName==last; last; implementation here
}}////end }}////end
endabstract
abstractclass
classEmployee
end methodsetLastName
Dr. S. HAMMAMI
method setLastName Employee
Implementation SalariedEmployee in Java
Case Study :
public
publicclassclassSalariedEmployee
SalariedEmployeeextends extendsEmployee
Employee ////calculate
calculateearnings;
earnings;override
overrideabstract
abstractmethod
methodearnings
earnings
{{
ininEmployee
Employee
private
privatedouble
doubleweeklySalary;
weeklySalary; public
publicdouble
doubleearnings()
earnings()
////four-argument constructor
four-argument constructor {{return getWeeklySalary();
return getWeeklySalary();
public
publicSalariedEmployee(
SalariedEmployee(String Stringfirst,
first,String
Stringlast,
last,String
String }}////end
endmethod
methodearnings
earnings
ssn, double salary
ssn, double salary ) )
{{
////return
returnString
Stringrepresentation
representationofofSalariedEmployee
SalariedEmployee
//super(
//super(first,
first,last,
last,ssn
ssn) )code
codereuse
reuse object
object
super(
super( first, last, ssn ); // pass toEmployee
first, last, ssn ); // pass to Employeeconstructor
constructor //// this
thismethod
methodoverride
overridetoString()
toString()ofofsuperclass
superclassmethod
method
setWeeklySalary(
setWeeklySalary( salary ); // validate and storesalary
salary ); // validate and store salary public String toString()
public String toString()
}}////end four-argument SalariedEmployee
end four-argument SalariedEmployee constructor constructor
{{ //*****
//*****super.toString()
super.toString(): :code
codereuse
reuse(good
(good
example)
example)
////set
setsalary
salary return
return( (super.toString()+
super.toString()+"\nearnings
"\nearnings==""++
public
publicvoid
voidsetWeeklySalary(
setWeeklySalary(doubledoublesalary
salary) ) getWeeklySalary());
getWeeklySalary());
{{
}}////end
endmethod
methodtoString
toString
weeklySalary
weeklySalary==salary
salary<<0.0
0.0??0.0
0.0: :salary;
salary; }}////end class SalariedEmployee
end class SalariedEmployee
////this
this mean that, if salary is <0 then putitit00else
mean that, if salary is <0 then put elseput
putititsalary
salary
}}////end method setWeeklySalary
end method setWeeklySalary
////return
returnsalary
salary
public
public doublegetWeeklySalary()
double getWeeklySalary()
{{ return weeklySalary;
return weeklySalary;
}}////end
endmethod
methodgetWeeklySalary
getWeeklySalary
Dr. S. HAMMAMI
Implementation HourlyEmployee in Java
Case Study :
public
publicclass classHourlyEmployee
HourlyEmployeeextends extendsEmployee
Employee
{{ ////calculate
private calculateearnings;
earnings;override
overrideabstract
abstractmethod
methodearnings
earnings
privatedouble doublewage;
wage;////wagewageper perhour
hour ininEmployee
Employee
private
private double hours; // hours workedfor
double hours; // hours worked forweek
week public
////five-argument constructor publicdouble
doubleearnings()
earnings()
five-argument constructor {{
public
publicHourlyEmployee(
HourlyEmployee(String Stringfirst,
first,String
Stringlast,
last,String
String ifif( (getHours()
ssn, double hourlyWage, double hoursWorked ) getHours()<=<=40
40) )////no
noovertime
overtime
ssn, double hourlyWage, double hoursWorked ) return getWage() * getHours();
return getWage() * getHours();
{{ else
//// super( else
super(first,
first,last,
last,ssn
ssn) )code
code(constructor)
(constructor)reuse
reuse return
return4040**getWage()
getWage()++( (getHours()
getHours()- -40
40) )**
super( first, last, ssn
super( first, last, ssn ); ); getWage()
setWage( getWage()**1.5; 1.5;
setWage(hourlyWage
hourlyWage););////validate
validateandandstore
storehourly
hourlywage
wage }}////end
end methodearnings
method earnings
setHours( hoursWorked ); // validate
setHours( hoursWorked ); // validate and store hours and store hours
worked
worked ////return
}}////end returnString
Stringrepresentation
representationofofHourlyEmployee
HourlyEmployee
endfive-argument
five-argumentHourlyEmployee
HourlyEmployeeconstructor
constructor object
object
public
public void setWage( double hourlyWage) )
void setWage( double hourlyWage public
{{ wage publicString
StringtoString()
toString() /*/*here
hereoverriding
overridingthe
the
wage==( (hourlyWage
hourlyWage<<0.0 0.0) )??0.0
0.0: :hourlyWage;
hourlyWage; toString() superclass method
toString() superclass method */ */
}}////end method setWage
end method setWage {{ /*code
public /*codereuse
reuseusing
usingsuper.
super. */*/
publicdoubledoublegetWage()
getWage() return
return(super.toString()
(super.toString()++"\nHourly
"\nHourlywage:
wage:""++
{{return wage;
return wage; getWage()
}}////end getWage()++
endmethod
methodgetWage
getWage "\nHours
"\nHoursworked
worked:"+:"+getHours()+
getHours()+"\nSalary
"\nSalaryisis: :
public
public void setHours(double
void setHours( doublehoursWorked
hoursWorked) ) "+earnings()
{hours "+earnings()););
{hours==( (( (hoursWorked
hoursWorked>= >=0.0
0.0) )&&
&&( (hoursWorked
hoursWorked<= <= }}////endendmethod
methodtoString
toString
168.0 ) ) ? hoursWorked
168.0 ) ) ? hoursWorked : 0.0; : 0.0; }}////end class HourlyEmployee
}}////end end class HourlyEmployee
endmethod
methodsetHours
setHours
public double getHours()
public double getHours()
{{ return returnhours;
hours;
}}////endend methodgetHours
method getHours
Dr. S. HAMMAMI
Implementation ComissionEmployee in Java
Case Study :
public
publicclass
classCommissionEmployee
CommissionEmployeeextends extendsEmployee
Employee ////set
{{ setgross
grosssales
salesamount
amount
public
public void setGrossSales(double
void setGrossSales( doublesalessales) )
private
privatedouble
doublegrossSales;
grossSales;////gross
grossweekly
weeklysales
sales {{grossSales
private double commissionRate; // commission grossSales==( (sales
sales<<0.0
0.0) )??0.0
0.0: :sales;
sales;
private double commissionRate; // commission }}////end method setGrossSales
end method setGrossSales
percentage
percentage
////return
returngross
grosssales
salesamount
amount
////five-argument
five-argumentconstructor
constructor public double getGrossSales()
public public double getGrossSales()
public CommissionEmployee(String
CommissionEmployee( Stringfirst,
first,String
Stringlast,
last, {{return
returngrossSales;
grossSales;
String ssn, double sales, double
String ssn, double sales, double rate ) rate ) }}////end
{{ end methodgetGrossSales
method getGrossSales
super(
super(first,
first,last,
last,ssn
ssn);); ////calculate
setGrossSales( calculateearnings;
earnings;override
overrideabstract
abstractmethod
methodearnings
earnings
setGrossSales(salessales);); setCommissionRate(
setCommissionRate(rate rate);); ininEmployee
Employee
}}////end
endfive-argument
five-argumentCommissionEmployee
CommissionEmployeeconstructor
constructor public
publicdouble
doubleearnings()
earnings()
{{return
return getCommissionRate()**getGrossSales();
getCommissionRate() getGrossSales();
////set
setcommission
commissionrate
rate }}////end method earnings
public end method earnings
public void setCommissionRate(double
void setCommissionRate( doublerate
rate) )
{{commissionRate
commissionRate==( (rate
rate>>0.0
0.0&&
&&rate
rate<<1.0
1.0) )??rate
rate: : ////return
0.0; returnString
Stringrepresentation
representationofof
0.0; CommissionEmployee
CommissionEmployeeobject object
}}////end
endmethod
methodsetCommissionRate
setCommissionRate public String toString()
public String toString()
{{return
return(super.toString()
(super.toString()++"\nGross
"\nGrosssales:
sales:""++
////return
returncommission
commissionrate
rate getGrossSales()
public double getCommissionRate() getGrossSales()++ "\nCommission
"\nCommissionrate:
rate:""++
public double getCommissionRate() getCommissionRate()
getCommissionRate()++"\nearnings
"\nearnings==""++earnings()
earnings()););
{return
{returncommissionRate;
commissionRate; }}////end
}}////end endmethod
methodtoString
toString
end methodgetCommissionRate
method getCommissionRate }}////end class CommissionEmployee
end class CommissionEmployee
Dr. S. HAMMAMI
Implementation BasePlusComissionEmployee in Java
Case Study :
public
publicclass
classBasePlusCommissionEmployee
BasePlusCommissionEmployeeextendsextends ////calculate
CommissionEmployee calculateearnings;
earnings;override
overridemethod
methodearnings
earningsinin
CommissionEmployee CommissionEmployee
CommissionEmployee
{{ public
private publicdouble
doubleearnings()
earnings()
privatedouble
doublebaseSalary;
baseSalary;////base
basesalary
salaryper
perweek
week {{
return
returngetBaseSalary()
getBaseSalary()++super.earnings();
super.earnings();//code
//code
////six-argument
six-argumentconstructor
constructor reuse form CommissionEmployee
public reuse form CommissionEmployee
public BasePlusCommissionEmployee(String
BasePlusCommissionEmployee( Stringfirst,
first, }}////end
endmethod
methodearnings
earnings
String last, String ssn, double sales, double rate,
String last, String ssn, double sales, double rate, double double
salary
salary) ){{ ////return
super( returnString
Stringrepresentation
representationofof
super(first,
first,last,
last,ssn,
ssn,sales,
sales,raterate);); BasePlusCommissionEmployee
BasePlusCommissionEmployeeobject object
setBaseSalary(
setBaseSalary(salary
salary););////validate
validateandandstore
storebase
basesalary
salary public String toString()
}}////end six-argument BasePlusCommissionEmployee public String toString()
end six-argument BasePlusCommissionEmployee {{
constructor
constructor return
return( ("\nBase-salaried
"\nBase-salaried:":"++super.toString()
super.toString()++
"\nBase
"\nBasesalary:
salary:""++getBaseSalary()
getBaseSalary()++"\nearnings
"\nearnings="
="
////set
setbase
basesalary
salary ++earnings() );
public earnings() );
public voidsetBaseSalary(
void setBaseSalary(double
doublesalary
salary) ) }//
}//end
endmethod
methodtoString
toString
{{ }}////end class BasePlusCommissionEmployee
baseSalary end class BasePlusCommissionEmployee
baseSalary==( (salary
salary<<0.0
0.0) )??0.0
0.0: :salary;
salary;////non-
non-
negative
negative
}}////end
endmethod
methodsetBaseSalary
setBaseSalary
////return
returnbase
basesalary
salary
public
public doublegetBaseSalary()
double getBaseSalary()
{{
return
returnbaseSalary;
baseSalary;
}}////end
end methodgetBaseSalary
method getBaseSalary
Dr. S. HAMMAMI
Implementation PayrollSystemTest in Java
public
publicclass
classPayrollSystemTest
PayrollSystemTest
{{
public
publicstatic
staticvoid
voidmain(
main(String
Stringargs[]
args[]) )
{{
////create
createsubclass
subclassobjects
objects
SalariedEmployee
SalariedEmployee SA= new
SA= newSalariedEmployee(
SalariedEmployee(“Ali",
“Ali","Samer",
"Samer","111-11-1111",
"111-11-1111",800.00
800.00););
HourlyEmployee
HourlyEmployeeHE HE== new
newHourlyEmployee(
HourlyEmployee(“Ramzi",
“Ramzi",“Ibrahim",
“Ibrahim","222-22-2222",
"222-22-2222",16.75,
16.75,4040););
CommissionEmployee
CommissionEmployeeCE CE== new
newCommissionEmployee(
CommissionEmployee( “Med",
“Med",“Ahmed",
“Ahmed","333-33-3333",
"333-33-3333",10000,
10000,.06
.06););
BasePlusCommissionEmployee
BasePlusCommissionEmployeeBP BP==newnewBasePlusCommissionEmployee(“Beji",
BasePlusCommissionEmployee(“Beji",“Lotfi",
“Lotfi","444-44-4444",
"444-44-4444",5000,
5000,.04,
.04,300
300););
System.out.println(
System.out.println("Employees
"Employeesprocessed
processedindividually:\n"
individually:\n"););
/*/* salariedEmployee
salariedEmployeeisisthe
thesame
sameasassalariedEmployee.toString()
salariedEmployee.toString() */*/
System.out.println(
System.out.println(SA.toString()+
SA.toString()+"\nearned:
"\nearned:""++SA.earnings()+"\n\n"
SA.earnings()+"\n\n"););
System.out.println(
System.out.println(HE HE++"\n"\nearned:
earned:""++HE.earnings()+"\n\n"
HE.earnings()+"\n\n"););
System.out.println(CE
System.out.println(CE++"\n "\nearned:
earned:""++CE.earnings()+"\n\n"
CE.earnings()+"\n\n"););
System.out.println(BP
System.out.println(BP++"\n "\nearned:
earned:"+"+BP.earnings()+"\n\n"
BP.earnings()+"\n\n"););
////create
createfour-element
four-elementEmployee
Employeearray
array
Employee
Employee employees[] = new Employee[44];];
employees[] = new Employee[
employees[
employees[00] ]==SA;SA; employees[
employees[11] ]==HE;
HE; employees[
employees[22] ]==CE; CE; employees[
employees[33] ]==BP;BP;
System.out.println( "Employees processed polymorphically:\n"
System.out.println( "Employees processed polymorphically:\n" ); );
////generically
genericallyprocess
processeach
eachelement
elementininarray
arrayemployees
employees
for (Employee currentEmployee : employees)
for (Employee currentEmployee : employees) {{
System.out.println(
System.out.println(currentEmployee
currentEmployee);} );}////invokes
invokestoString
toString: :here
hereisispolymorphysim
polymorphysim: :call
calltoString()
toString()ofofclass
classatatthe
theexecutiontime.
executiontime.
////called
calleddynamic
dynamicbinding
bindingororlate
latebinding
binding
////Note
Note:only
:onlymethods
methodsofofsuperclass
superclasscan
canbebecalled
calledvia
viasuperclass
superclassvariable
variable
////get
gettype
typename
nameofofeach
eachobject
objectininemployees
employeesarray
array
for ( int j = 0; j < employees.length; j++
for ( int j = 0; j < employees.length; j++ ) )
System.out.printf(
System.out.printf("Employee
"Employee%d %disisaa%s\n",
%s\n",j,j, employees[
employees[j j].getClass().getName()
].getClass().getName());); ////display
displaythe
thename
nameofofthe
theclass
classwhos
whos
//object
//objectisisemployee[j]
employee[j]
}}S.
Dr. ////end
endmain
main }}////end
HAMMAMI endclass
classPayrollSystemTest
PayrollSystemTest