SlideShare a Scribd company logo
1 of 13
Polymorphism
Definition, types and implementation
22-Dec-14 assadchadhar- assadchadhar@gmail.com 1
22-Dec-14 assadchadhar- assadchadhar@gmail.com 2
Contents / Agenda
• Definition and Types
• Ad-hoc polymorphism
• Implementation of all types of ad-hoc polymorphism
• Parametric Polymorphism
• Implementation of parametric polymorphism
• Subtyping polymorphism
• Implementation of Subtyping polymorphism
22-Dec-14 assadchadhar- assadchadhar@gmail.com 3
Definition
• Polymorphism is an object-oriented programming concept that refers
to the ability of a variable, function or object to take on multiple
forms. A language that features polymorphism allows developers to
program in the general rather than program in the specific.
• Following are the main types of polymorphism
1. Ad-hoc Polymorphism
2. Parametric Polymorphism
3. Subtyping Polymorphism
22-Dec-14 assadchadhar- assadchadhar@gmail.com 4
Ad-hoc Polymorphism
• It is also known as Function Overloading or Static Binding and also
Operator Overloading.
• Ad-hoc Polymorphism is a phenomenon in which you can create
multiple functions with the same name but that have different
headers or signature.
• It can be achieved using following ways
1. By changing the type of arguments
2. By changing the order of arguments
3. By changing number of arguments
• You can not change the return-type of a function in overloading.
Implementation (1)
by changing number of arguments
• You can change the number of arguments to overload a method.
A simple example is shown in the picture, where a
method “Add” is overloaded three times with same
return-type but with different number of arguments.
First method takes one argument, second take two and
third takes three arguments. You can call the Add method
with any number of arguments (from 1 to 3 of course)
compiler will choose a proper method on compile time.
As the compiler choses the proper method on compile
time that’s why it is called compile time polymorphism or
Static polymorphism.
Note: in example all arguments are of type integer but
you can give any type of argument and provide a proper
functionality. And same is the case with Constructors.
22-Dec-14 assadchadhar- assadchadhar@gmail.com 5
Implementation (2)
by changing type of arguments
• You can achieve this by just changing the type of arguments.
You see that, we don’t change the
number of arguments here in this
example, but we change the type
from integer to double. And by doing
this we have achieved the
polymorphism.
22-Dec-14 assadchadhar- assadchadhar@gmail.com 6
Implementation (3)
by changing order of arguments
• You can also just change the order of arguments to overload a method
Here in this example, there are two overloaded
method in the class. We overload them by just
changing the order of arguments.
In first method, integer is 1st argument and string is 2nd
argument but in the second method string is 1st
argument and integer is the 1st argument.
22-Dec-14 assadchadhar- assadchadhar@gmail.com 7
22-Dec-14 assadchadhar- assadchadhar@gmail.com 8
Parametric Polymorphism
• It is also known as Template Polymorphism or Late/dynamic Binding.
• Parametric polymorphism allows a function or a data type to be written
generically, so that it can handle values identically without depending on
their type. Parametric polymorphism is a way to make a language more
expressive, while still maintaining full static type-safety.
• The concept of parametric polymorphism applies to both data types and
functions. A function that can evaluate to or be applied to values of
different types is known as a polymorphic function. A data type that can
appear to be of a generalized type (e.g., a list with elements of arbitrary
type) is designated polymorphic data type like the generalized type from
which such specializations are made.
Implementation
A generic function swap is shown in the picture.
This method can work with any type you will
provide in angle brackets even with strings and
complex types.
I have created integers and characters in this
example and same function will swap both type of
variables.
This is parametric polymorphism and swap
function is polymorphic function.
22-Dec-14 assadchadhar- assadchadhar@gmail.com 9
22-Dec-14 assadchadhar- assadchadhar@gmail.com 10
Subtyping Polymorphism
• It is also known as Method Overriding or Late Binding or Dynamic
Binding or Inclusion Polymorphism.
• Method Overriding is when a method defined in a superclass or
interface is re-defined by one of its subclasses, thus
modifying/replacing the behavior the superclass provides. The
decision to call an implementation or another is dynamically taken at
runtime, depending on the object the operation is called from. Notice
the signature of the method remains the same when overriding.
Implementation
The picture shows the implementation of method overriding or
subtyping polymorphism.
Abstract class has a method that is re-defined in each concrete class
with respect to their requirements with same signature.
In the main method, when we create objects of concrete classes and
call there talk method we get different output as implemented.
letsHear(new Cat()) => Meow!
letsHear(new Dog()) => Woof!
The abstract class’s method is overridden on runtime, the compiler sees
which object is calling the method, if that method is available in same
class then it would be called, if not, then super class’s method would be
called.
22-Dec-14 assadchadhar- assadchadhar@gmail.com 11
22-Dec-14 assadchadhar- assadchadhar@gmail.com 12
Casting in Polymorphism (1)
• Two types of castings are done in polymorphism
1. Up Casting
2. Down Casting
• Up-casting is casting to a supertype, while Down-casting is casting to a subtype. Supercasting is always
allowed, but subcasting involves a type check and can throw a ClassCastException. A cast from from Dog to
an Animal is a upcast, because a Dog is-a Animal. In general, you can upcast whenever there is an is-a
relationship between two classes. Downcasting would be something like this:
• Animal animal = new Dog();
• Dog castedDog = (Dog) animal;
• Basically what you're doing is telling the program that you know what the runtime type of the object really
is. The program will do the conversion, but will still do a sanity check to make sure that it's possible. In this
case, the cast is possible because at runtime animal is actually a Dog even though the static type of animal is
Animal. However, if you were to do this:
• Animal animal = new Animal();
• Dog dog = (Dog) animal;
• You'd get a ClassCastException. The reason why is because animal's runtime type is Animal, and so when you
tell the runtime to perform the cast it sees that animal isn't really a Dog and so throws a ClassCastException.
To call a superclass's method you can do super.method() or be performing the upcast. To call a subclass's
method you have to do a downcast and risk the ClassCastException.
Casting in Polymorphism (2)
22-Dec-14 assadchadhar- assadchadhar@gmail.com 13

More Related Content

Similar to Polymorphism OOP new Gate.pptx

Chapter4__Method_Lim Lyheng_RULE (2).pdf
Chapter4__Method_Lim Lyheng_RULE (2).pdfChapter4__Method_Lim Lyheng_RULE (2).pdf
Chapter4__Method_Lim Lyheng_RULE (2).pdfMornThea
 
Object Oriented Programming.pptx
 Object Oriented Programming.pptx Object Oriented Programming.pptx
Object Oriented Programming.pptxShuvrojitMajumder
 
Learn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdfLearn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdfDatacademy.ai
 
Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Geekster
 
Refactoring bad codesmell
Refactoring bad codesmellRefactoring bad codesmell
Refactoring bad codesmellhyunglak kim
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarAnimesh Sarkar
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java Janu Jahnavi
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and PolymorphismKartikKapgate
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismIt Academy
 
Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++smumbahelp
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP conceptsAhmed Farag
 

Similar to Polymorphism OOP new Gate.pptx (20)

Chapter4__Method_Lim Lyheng_RULE (2).pdf
Chapter4__Method_Lim Lyheng_RULE (2).pdfChapter4__Method_Lim Lyheng_RULE (2).pdf
Chapter4__Method_Lim Lyheng_RULE (2).pdf
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Object Oriented Programming.pptx
 Object Oriented Programming.pptx Object Oriented Programming.pptx
Object Oriented Programming.pptx
 
Learn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdfLearn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdf
 
Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
 
Refactoring bad codesmell
Refactoring bad codesmellRefactoring bad codesmell
Refactoring bad codesmell
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Java
JavaJava
Java
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
 
Mca2030 object oriented programming – c++
Mca2030  object oriented programming – c++Mca2030  object oriented programming – c++
Mca2030 object oriented programming – c++
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 

More from AssadLeo1

half day batch male hafizabad list of pos and apos
half day batch male hafizabad list of pos and aposhalf day batch male hafizabad list of pos and apos
half day batch male hafizabad list of pos and aposAssadLeo1
 
Database management book slides.ppt
Database management book slides.pptDatabase management book slides.ppt
Database management book slides.pptAssadLeo1
 
MS Excel Detailed into.pptx
MS Excel Detailed into.pptxMS Excel Detailed into.pptx
MS Excel Detailed into.pptxAssadLeo1
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxAssadLeo1
 
Polymorphism OOP Old Gate.pptx
Polymorphism OOP Old Gate.pptxPolymorphism OOP Old Gate.pptx
Polymorphism OOP Old Gate.pptxAssadLeo1
 
MS Excel Detailed intorduction.pptx
MS Excel Detailed intorduction.pptxMS Excel Detailed intorduction.pptx
MS Excel Detailed intorduction.pptxAssadLeo1
 
network-management Web base.ppt
network-management Web base.pptnetwork-management Web base.ppt
network-management Web base.pptAssadLeo1
 
polymorphism OOP.pptx
polymorphism OOP.pptxpolymorphism OOP.pptx
polymorphism OOP.pptxAssadLeo1
 
MS Excel Lite Introduction.ppt
MS Excel Lite Introduction.pptMS Excel Lite Introduction.ppt
MS Excel Lite Introduction.pptAssadLeo1
 
Monitoring sytem.ppt
Monitoring sytem.pptMonitoring sytem.ppt
Monitoring sytem.pptAssadLeo1
 

More from AssadLeo1 (10)

half day batch male hafizabad list of pos and apos
half day batch male hafizabad list of pos and aposhalf day batch male hafizabad list of pos and apos
half day batch male hafizabad list of pos and apos
 
Database management book slides.ppt
Database management book slides.pptDatabase management book slides.ppt
Database management book slides.ppt
 
MS Excel Detailed into.pptx
MS Excel Detailed into.pptxMS Excel Detailed into.pptx
MS Excel Detailed into.pptx
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
Polymorphism OOP Old Gate.pptx
Polymorphism OOP Old Gate.pptxPolymorphism OOP Old Gate.pptx
Polymorphism OOP Old Gate.pptx
 
MS Excel Detailed intorduction.pptx
MS Excel Detailed intorduction.pptxMS Excel Detailed intorduction.pptx
MS Excel Detailed intorduction.pptx
 
network-management Web base.ppt
network-management Web base.pptnetwork-management Web base.ppt
network-management Web base.ppt
 
polymorphism OOP.pptx
polymorphism OOP.pptxpolymorphism OOP.pptx
polymorphism OOP.pptx
 
MS Excel Lite Introduction.ppt
MS Excel Lite Introduction.pptMS Excel Lite Introduction.ppt
MS Excel Lite Introduction.ppt
 
Monitoring sytem.ppt
Monitoring sytem.pptMonitoring sytem.ppt
Monitoring sytem.ppt
 

Recently uploaded

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Polymorphism OOP new Gate.pptx

  • 1. Polymorphism Definition, types and implementation 22-Dec-14 assadchadhar- assadchadhar@gmail.com 1
  • 2. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 2 Contents / Agenda • Definition and Types • Ad-hoc polymorphism • Implementation of all types of ad-hoc polymorphism • Parametric Polymorphism • Implementation of parametric polymorphism • Subtyping polymorphism • Implementation of Subtyping polymorphism
  • 3. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 3 Definition • Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms. A language that features polymorphism allows developers to program in the general rather than program in the specific. • Following are the main types of polymorphism 1. Ad-hoc Polymorphism 2. Parametric Polymorphism 3. Subtyping Polymorphism
  • 4. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 4 Ad-hoc Polymorphism • It is also known as Function Overloading or Static Binding and also Operator Overloading. • Ad-hoc Polymorphism is a phenomenon in which you can create multiple functions with the same name but that have different headers or signature. • It can be achieved using following ways 1. By changing the type of arguments 2. By changing the order of arguments 3. By changing number of arguments • You can not change the return-type of a function in overloading.
  • 5. Implementation (1) by changing number of arguments • You can change the number of arguments to overload a method. A simple example is shown in the picture, where a method “Add” is overloaded three times with same return-type but with different number of arguments. First method takes one argument, second take two and third takes three arguments. You can call the Add method with any number of arguments (from 1 to 3 of course) compiler will choose a proper method on compile time. As the compiler choses the proper method on compile time that’s why it is called compile time polymorphism or Static polymorphism. Note: in example all arguments are of type integer but you can give any type of argument and provide a proper functionality. And same is the case with Constructors. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 5
  • 6. Implementation (2) by changing type of arguments • You can achieve this by just changing the type of arguments. You see that, we don’t change the number of arguments here in this example, but we change the type from integer to double. And by doing this we have achieved the polymorphism. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 6
  • 7. Implementation (3) by changing order of arguments • You can also just change the order of arguments to overload a method Here in this example, there are two overloaded method in the class. We overload them by just changing the order of arguments. In first method, integer is 1st argument and string is 2nd argument but in the second method string is 1st argument and integer is the 1st argument. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 7
  • 8. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 8 Parametric Polymorphism • It is also known as Template Polymorphism or Late/dynamic Binding. • Parametric polymorphism allows a function or a data type to be written generically, so that it can handle values identically without depending on their type. Parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety. • The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.
  • 9. Implementation A generic function swap is shown in the picture. This method can work with any type you will provide in angle brackets even with strings and complex types. I have created integers and characters in this example and same function will swap both type of variables. This is parametric polymorphism and swap function is polymorphic function. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 9
  • 10. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 10 Subtyping Polymorphism • It is also known as Method Overriding or Late Binding or Dynamic Binding or Inclusion Polymorphism. • Method Overriding is when a method defined in a superclass or interface is re-defined by one of its subclasses, thus modifying/replacing the behavior the superclass provides. The decision to call an implementation or another is dynamically taken at runtime, depending on the object the operation is called from. Notice the signature of the method remains the same when overriding.
  • 11. Implementation The picture shows the implementation of method overriding or subtyping polymorphism. Abstract class has a method that is re-defined in each concrete class with respect to their requirements with same signature. In the main method, when we create objects of concrete classes and call there talk method we get different output as implemented. letsHear(new Cat()) => Meow! letsHear(new Dog()) => Woof! The abstract class’s method is overridden on runtime, the compiler sees which object is calling the method, if that method is available in same class then it would be called, if not, then super class’s method would be called. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 11
  • 12. 22-Dec-14 assadchadhar- assadchadhar@gmail.com 12 Casting in Polymorphism (1) • Two types of castings are done in polymorphism 1. Up Casting 2. Down Casting • Up-casting is casting to a supertype, while Down-casting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException. A cast from from Dog to an Animal is a upcast, because a Dog is-a Animal. In general, you can upcast whenever there is an is-a relationship between two classes. Downcasting would be something like this: • Animal animal = new Dog(); • Dog castedDog = (Dog) animal; • Basically what you're doing is telling the program that you know what the runtime type of the object really is. The program will do the conversion, but will still do a sanity check to make sure that it's possible. In this case, the cast is possible because at runtime animal is actually a Dog even though the static type of animal is Animal. However, if you were to do this: • Animal animal = new Animal(); • Dog dog = (Dog) animal; • You'd get a ClassCastException. The reason why is because animal's runtime type is Animal, and so when you tell the runtime to perform the cast it sees that animal isn't really a Dog and so throws a ClassCastException. To call a superclass's method you can do super.method() or be performing the upcast. To call a subclass's method you have to do a downcast and risk the ClassCastException.
  • 13. Casting in Polymorphism (2) 22-Dec-14 assadchadhar- assadchadhar@gmail.com 13