SlideShare a Scribd company logo
1 of 22
Object Oriented Programming
Chapter 4: Polymorphism
Prepared by: Mahmoud Rafeek Alfarra
2016
Outlines
◉ Motivation
◉ What is Polymorphism?
◉ Abstract Classes and Methods
◉ Full Example
◉ final class and method
Note: I have prepared this material Based on (Liang: “Introduction to Programming using Java”, 10’th edition, 2015)
Lecture
Let’s think on Polymorphism
1
o Suppose you will define classes to model circles, rectangles, and
triangles.
o These classes have many common methods, but each one of them
is implemented with different way. What is the best way to
design these classes?
The answer is to use Polymorphism.
Motivation
What is Polymorphism?
o Polymorphism comes from Greek meaning “many forms”.
o In Java, polymorphism refers to the dynamic binding mechanism
that determines which method definition will be used when a
method name has been overridden.
o Polymorphism means that a variable of a supertype can refer to a
subtype object.
Example
Shape
Specialization
+
3-D2-D
getArea() !!
GeometricObject
-color: String
-filled: boolean
-dateCreated: java.util.Date
+GeometricObject()
+GeometricObject(color: String,
filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
The color of the object (default: white).
Indicates whether the object is filled with a color (default: false).
The date when the object was created.
Creates a GeometricObject.
Creates a GeometricObject with the specified color and filled
values.
Returns the color.
Sets a new color.
Returns the filled property.
Sets a new filled property.
Returns the dateCreated.
Returns a string representation of this object.
Circle
-radius: double
+Circle()
+Circle(radius: double)
+Circle(radius: double, color: String,
filled: boolean)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
+getPerimeter(): double
+getDiameter(): double
+printCircle(): void
Rectangle
-width: double
-height: double
+Rectangle()
+Rectangle(width: double, height: double)
+Rectangle(width: double, height: double
color: String, filled: boolean)
+getWidth(): double
+setWidth(width: double): void
+getHeight(): double
+setHeight(height: double): void
+getArea(): double
+getPerimeter(): double
Type of
Class
Concrete
classes
Abstract
classes
Classes that can be used to
instantiate objects, they
provide implementations of
every method they declare.
They are used only as superclass.
They cannot be used to instantiate
objects, because, they are
incomplete. Subclasses must
declare the "missing pieces."
o You make a class abstract by declaring it with keyword abstract.
o An abstract class normally contains one or more abstract
methods.
o An abstract method is one with keyword abstract in its
declaration, as in
Declaring abstract classes
public abstract void draw();
Declaring abstract classes
Each concrete subclass of an abstract superclass
also must provide concrete implementations of
the superclass's abstract methods.
A class that contains any abstract methods must
be declared as an abstract class even if that class
contains concrete (non-abstract) methods.
THANKS!
Any questions?
You can find me at:
Fb/mahmoudRAlfarra
Staff.cst.ps/mfarra
Youtube.com/mralfarra1
@mralfarra
‫فانتبـه‬ ،،، ‫فتنة‬ ‫والشـر‬ ‫اخلري‬!
Lecture
Let’s focus on Implementation of Polymorphism
2
Full Example
Indirect
Concrete
Subclass class
Concrete
Subclass class
Abstract super
class
Employee
Commission
Employee
BasePlus
Commission
Employee
Salaried
Employee
Hourly
Employee
Employee Classpublic abstract class Employee{
private String firstName;
private String lastName;
private String ID;
public Employee( String firstName, String lastName, String ID ) {
this.firstName = firstName;
this.lastName = lastName;
this.ID = ID; }
// set & Get methods
public String info() {
return "The information is: "+ getfirstName()+ getLastName()+ getID() ;
}
// abstract method overridden by subclasses
public abstract double earnings();
}
public class SalariedEmployee extends Employee {
private double weeklySalary;
public SalariedEmployee( String firstName, String lastName, String ID, double
weeklySalary ) {
super( firstName, lastName, ID ); // pass to Employee constructor
this.weeklySalary = weeklySalary ;
} // end four-argument SalariedEmployee constructor
// Set & Get methods
public double earnings() {
return getWeeklySalary();
} // end method earnings
public String info()
{
return super.info()+ getWeeklySalary() ;
} // end method info
} // end class SalariedEmployee
SalariedEmployee
Class
public class CommissionEmployee extends Employee {
private double grossSales; // gross weekly sales
private double commissionRate; // commission percentage
public CommissionEmployee( String firstName, String lastName, String ID,
double grossSales, double commissionRate ){
super( firstName, lastName, ID );
this.grossSales= grossSales;
this.commissionRate= commissionRate; }
public double earnings() {
return getCommissionRate() * getGrossSales();
} // end method earnings
public String info()
{
return super.info()+ getGrossSales()+ getCommissionRate() ;
} // end method info
} // end class CommissionEmployee
CommissionEmployee
Class
public class BasePlusCommissionEmployee extends CommissionEmployee
{
private double baseSalary; // base salary per week
public BasePlusCommissionEmployee( String firstName, String lastName,
String ID, double grossSales, double commissionRate, double baseSalary)
{
super( firstName, lastName, ID, grossSales, commissionRate );
this.baseSalary = baseSalary ;
}
// Set & Get
public double earnings() {
return getBaseSalary() + super.earnings();
} // end method earnings
public String info() {
return super.info()+ getBaseSalary() ;
} // end method info
} // end class BasePlusCommissionEmployee
BasePlusCommissionEmployee
Class
o A method that is declared final in a superclass cannot be
overridden in a subclass.
o Methods that are declared private are implicitly final, because it
is impossible to override them in a subclass.
o Methods that are declared static are also implicitly final,
because static methods cannot be overridden either.
final method
Practices
Practice 1
Using charts, What is
Polymorphism ?
Practice 2
Compare between the
Types of Classes.
Practice 3
By UML class, explain
the concept of
Specialization.
Practice 4
Give 3 examples for
using polymorphism.
Practice 5
Define an abstract
class.
Practice 6
Explain the relationship
between Inheritance
and Polymorphism.
THANKS!
Any questions?
You can find me at:
Fb/mahmoudRAlfarra
Staff.cst.ps/mfarra
Youtube.com/mralfarra1
@mralfarra

More Related Content

What's hot

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 

What's hot (20)

encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
Inheritance
InheritanceInheritance
Inheritance
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
Oops in java
Oops in javaOops in java
Oops in java
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Object and class
Object and classObject and class
Object and class
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 

Viewers also liked

بناء فرق العمل ـ ورشة عمل ـ
بناء فرق العمل ـ ورشة عمل ـبناء فرق العمل ـ ورشة عمل ـ
بناء فرق العمل ـ ورشة عمل ـ
gesgesa
 

Viewers also liked (8)

خمس خطوات لاستثمار وقتك قبل الامتحانات
خمس خطوات لاستثمار وقتك قبل الامتحاناتخمس خطوات لاستثمار وقتك قبل الامتحانات
خمس خطوات لاستثمار وقتك قبل الامتحانات
 
كتابة خطة تطوير الشخصية
كتابة خطة تطوير الشخصيةكتابة خطة تطوير الشخصية
كتابة خطة تطوير الشخصية
 
إدارة الوقت ... أداة تحقيق الطموح
إدارة الوقت ... أداة تحقيق الطموحإدارة الوقت ... أداة تحقيق الطموح
إدارة الوقت ... أداة تحقيق الطموح
 
صفات المتدرب الذكي كما يراه محمود رفيق الفرا
صفات المتدرب الذكي كما يراه محمود رفيق الفراصفات المتدرب الذكي كما يراه محمود رفيق الفرا
صفات المتدرب الذكي كما يراه محمود رفيق الفرا
 
مهارات العرض و التقديم
مهارات العرض و التقديممهارات العرض و التقديم
مهارات العرض و التقديم
 
دورة مهارات العمل الجماعي
دورة مهارات العمل الجماعي دورة مهارات العمل الجماعي
دورة مهارات العمل الجماعي
 
بناء فرق العمل ـ ورشة عمل ـ
بناء فرق العمل ـ ورشة عمل ـبناء فرق العمل ـ ورشة عمل ـ
بناء فرق العمل ـ ورشة عمل ـ
 
Team building ‫‬دورة تدريبية بناء فريق العمل
Team building ‫‬دورة تدريبية بناء فريق العملTeam building ‫‬دورة تدريبية بناء فريق العمل
Team building ‫‬دورة تدريبية بناء فريق العمل
 

Similar to ‫‫Chapter4 Polymorphism

9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
Terry Yoast
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
BapanKar2
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 

Similar to ‫‫Chapter4 Polymorphism (20)

9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Chap11
Chap11Chap11
Chap11
 
Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Classes2
Classes2Classes2
Classes2
 
06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt06 InheritanceAndPolymorphism.ppt
06 InheritanceAndPolymorphism.ppt
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Core java oop
Core java oopCore java oop
Core java oop
 
Oops
OopsOops
Oops
 
OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Only oop
Only oopOnly oop
Only oop
 
Java basics
Java basicsJava basics
Java basics
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 

More from Mahmoud Alfarra

8 programming-using-java decision-making practices 20102011
8 programming-using-java decision-making practices 201020118 programming-using-java decision-making practices 20102011
8 programming-using-java decision-making practices 20102011
Mahmoud Alfarra
 

More from Mahmoud Alfarra (20)

Computer Programming, Loops using Java - part 2
Computer Programming, Loops using Java - part 2Computer Programming, Loops using Java - part 2
Computer Programming, Loops using Java - part 2
 
Computer Programming, Loops using Java
Computer Programming, Loops using JavaComputer Programming, Loops using Java
Computer Programming, Loops using Java
 
Chapter 10: hashing data structure
Chapter 10:  hashing data structureChapter 10:  hashing data structure
Chapter 10: hashing data structure
 
Chapter9 graph data structure
Chapter9  graph data structureChapter9  graph data structure
Chapter9 graph data structure
 
Chapter 8: tree data structure
Chapter 8:  tree data structureChapter 8:  tree data structure
Chapter 8: tree data structure
 
Chapter 7: Queue data structure
Chapter 7:  Queue data structureChapter 7:  Queue data structure
Chapter 7: Queue data structure
 
Chapter 6: stack data structure
Chapter 6:  stack data structureChapter 6:  stack data structure
Chapter 6: stack data structure
 
Chapter 5: linked list data structure
Chapter 5: linked list data structureChapter 5: linked list data structure
Chapter 5: linked list data structure
 
Chapter 4: basic search algorithms data structure
Chapter 4: basic search algorithms data structureChapter 4: basic search algorithms data structure
Chapter 4: basic search algorithms data structure
 
Chapter 3: basic sorting algorithms data structure
Chapter 3: basic sorting algorithms data structureChapter 3: basic sorting algorithms data structure
Chapter 3: basic sorting algorithms data structure
 
Chapter 2: array and array list data structure
Chapter 2: array and array list  data structureChapter 2: array and array list  data structure
Chapter 2: array and array list data structure
 
Chapter1 intro toprincipleofc#_datastructure_b_cs
Chapter1  intro toprincipleofc#_datastructure_b_csChapter1  intro toprincipleofc#_datastructure_b_cs
Chapter1 intro toprincipleofc#_datastructure_b_cs
 
Chapter 0: introduction to data structure
Chapter 0: introduction to data structureChapter 0: introduction to data structure
Chapter 0: introduction to data structure
 
3 classification
3  classification3  classification
3 classification
 
8 programming-using-java decision-making practices 20102011
8 programming-using-java decision-making practices 201020118 programming-using-java decision-making practices 20102011
8 programming-using-java decision-making practices 20102011
 
7 programming-using-java decision-making220102011
7 programming-using-java decision-making2201020117 programming-using-java decision-making220102011
7 programming-using-java decision-making220102011
 
6 programming-using-java decision-making20102011-
6 programming-using-java decision-making20102011-6 programming-using-java decision-making20102011-
6 programming-using-java decision-making20102011-
 
5 programming-using-java intro-tooop20102011
5 programming-using-java intro-tooop201020115 programming-using-java intro-tooop20102011
5 programming-using-java intro-tooop20102011
 
4 programming-using-java intro-tojava20102011
4 programming-using-java intro-tojava201020114 programming-using-java intro-tojava20102011
4 programming-using-java intro-tojava20102011
 
3 programming-using-java introduction-to computer
3 programming-using-java introduction-to computer3 programming-using-java introduction-to computer
3 programming-using-java introduction-to computer
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Recently uploaded (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 

‫‫Chapter4 Polymorphism

  • 1. Object Oriented Programming Chapter 4: Polymorphism Prepared by: Mahmoud Rafeek Alfarra 2016
  • 2.
  • 3. Outlines ◉ Motivation ◉ What is Polymorphism? ◉ Abstract Classes and Methods ◉ Full Example ◉ final class and method Note: I have prepared this material Based on (Liang: “Introduction to Programming using Java”, 10’th edition, 2015)
  • 4. Lecture Let’s think on Polymorphism 1
  • 5. o Suppose you will define classes to model circles, rectangles, and triangles. o These classes have many common methods, but each one of them is implemented with different way. What is the best way to design these classes? The answer is to use Polymorphism. Motivation
  • 6. What is Polymorphism? o Polymorphism comes from Greek meaning “many forms”. o In Java, polymorphism refers to the dynamic binding mechanism that determines which method definition will be used when a method name has been overridden. o Polymorphism means that a variable of a supertype can refer to a subtype object.
  • 8. getArea() !! GeometricObject -color: String -filled: boolean -dateCreated: java.util.Date +GeometricObject() +GeometricObject(color: String, filled: boolean) +getColor(): String +setColor(color: String): void +isFilled(): boolean +setFilled(filled: boolean): void +getDateCreated(): java.util.Date +toString(): String The color of the object (default: white). Indicates whether the object is filled with a color (default: false). The date when the object was created. Creates a GeometricObject. Creates a GeometricObject with the specified color and filled values. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns the dateCreated. Returns a string representation of this object. Circle -radius: double +Circle() +Circle(radius: double) +Circle(radius: double, color: String, filled: boolean) +getRadius(): double +setRadius(radius: double): void +getArea(): double +getPerimeter(): double +getDiameter(): double +printCircle(): void Rectangle -width: double -height: double +Rectangle() +Rectangle(width: double, height: double) +Rectangle(width: double, height: double color: String, filled: boolean) +getWidth(): double +setWidth(width: double): void +getHeight(): double +setHeight(height: double): void +getArea(): double +getPerimeter(): double
  • 9. Type of Class Concrete classes Abstract classes Classes that can be used to instantiate objects, they provide implementations of every method they declare. They are used only as superclass. They cannot be used to instantiate objects, because, they are incomplete. Subclasses must declare the "missing pieces."
  • 10. o You make a class abstract by declaring it with keyword abstract. o An abstract class normally contains one or more abstract methods. o An abstract method is one with keyword abstract in its declaration, as in Declaring abstract classes public abstract void draw();
  • 11. Declaring abstract classes Each concrete subclass of an abstract superclass also must provide concrete implementations of the superclass's abstract methods. A class that contains any abstract methods must be declared as an abstract class even if that class contains concrete (non-abstract) methods.
  • 12. THANKS! Any questions? You can find me at: Fb/mahmoudRAlfarra Staff.cst.ps/mfarra Youtube.com/mralfarra1 @mralfarra
  • 13. ‫فانتبـه‬ ،،، ‫فتنة‬ ‫والشـر‬ ‫اخلري‬!
  • 14. Lecture Let’s focus on Implementation of Polymorphism 2
  • 15. Full Example Indirect Concrete Subclass class Concrete Subclass class Abstract super class Employee Commission Employee BasePlus Commission Employee Salaried Employee Hourly Employee
  • 16. Employee Classpublic abstract class Employee{ private String firstName; private String lastName; private String ID; public Employee( String firstName, String lastName, String ID ) { this.firstName = firstName; this.lastName = lastName; this.ID = ID; } // set & Get methods public String info() { return "The information is: "+ getfirstName()+ getLastName()+ getID() ; } // abstract method overridden by subclasses public abstract double earnings(); }
  • 17. public class SalariedEmployee extends Employee { private double weeklySalary; public SalariedEmployee( String firstName, String lastName, String ID, double weeklySalary ) { super( firstName, lastName, ID ); // pass to Employee constructor this.weeklySalary = weeklySalary ; } // end four-argument SalariedEmployee constructor // Set & Get methods public double earnings() { return getWeeklySalary(); } // end method earnings public String info() { return super.info()+ getWeeklySalary() ; } // end method info } // end class SalariedEmployee SalariedEmployee Class
  • 18. public class CommissionEmployee extends Employee { private double grossSales; // gross weekly sales private double commissionRate; // commission percentage public CommissionEmployee( String firstName, String lastName, String ID, double grossSales, double commissionRate ){ super( firstName, lastName, ID ); this.grossSales= grossSales; this.commissionRate= commissionRate; } public double earnings() { return getCommissionRate() * getGrossSales(); } // end method earnings public String info() { return super.info()+ getGrossSales()+ getCommissionRate() ; } // end method info } // end class CommissionEmployee CommissionEmployee Class
  • 19. public class BasePlusCommissionEmployee extends CommissionEmployee { private double baseSalary; // base salary per week public BasePlusCommissionEmployee( String firstName, String lastName, String ID, double grossSales, double commissionRate, double baseSalary) { super( firstName, lastName, ID, grossSales, commissionRate ); this.baseSalary = baseSalary ; } // Set & Get public double earnings() { return getBaseSalary() + super.earnings(); } // end method earnings public String info() { return super.info()+ getBaseSalary() ; } // end method info } // end class BasePlusCommissionEmployee BasePlusCommissionEmployee Class
  • 20. o A method that is declared final in a superclass cannot be overridden in a subclass. o Methods that are declared private are implicitly final, because it is impossible to override them in a subclass. o Methods that are declared static are also implicitly final, because static methods cannot be overridden either. final method
  • 21. Practices Practice 1 Using charts, What is Polymorphism ? Practice 2 Compare between the Types of Classes. Practice 3 By UML class, explain the concept of Specialization. Practice 4 Give 3 examples for using polymorphism. Practice 5 Define an abstract class. Practice 6 Explain the relationship between Inheritance and Polymorphism.
  • 22. THANKS! Any questions? You can find me at: Fb/mahmoudRAlfarra Staff.cst.ps/mfarra Youtube.com/mralfarra1 @mralfarra