SlideShare a Scribd company logo
1 of 19
Download to read offline
Polymorphism in Java
Name: Animesh Sarkar
Subject: CMSA
Semester: 2
Paper: CC3
Roll no.: S49
Session: 2020-2023
1
Index
2
Topic name Page no.
What is Polymorphism? 3
A graphical example of polymorphism in pop culture. 4
Types of polymorphism. 5
Static polymorphism. 6
Example program to illustrate method overloading. 7, 8
Dynamic polymorphism. 9
Example program to illustrate method overriding, 10, 11
Differences between method overloading and overriding. 12
Some other polymorphic behaviours. 13, 14
A program illustrating various kinds of polymorphism. 15, 16, 17
Advantages and disadvantages of polymorphism. 18
Reference sources. 19
What is polymorphism?
● Polymorphism refers to the ability to appear in many
forms. It is the concept of one entity providing multiple
implementations or behaviours.
● It is an important feature of Object-Oriented
Programming. Java supports polymorphism.
3
Henry Cavill Superman
Clerk Kent
Geralt
One person shows different characteristics and
behaviours depending on the character he plays.
This is an example of polymorphism.
4
Java has two types of polymorphism
Compiled
or static
polymorphism
Runtime
or dynamic
polymorphism
5
Compiled or static polymorphism
This type of polymorphism is achieved by method overloading and
operator overloading. However, Java does not support user defined
operator overloading.
Method overloading
When there are multiple methods with same name but different
parameter list then these methods are said to be overloaded. Methods
can be overloaded by changing number of arguments and/or change in
type of arguments.
6
Example program to illustrate method overloading
public class Adder
{
public static int add (int a, int b)
{
System.out.println(“Add 2 int”);
return a+b;
}
public static int add (int a, int b, int c)
{
System.out.println(“Add 3 int”);
return a+b+c;
}
public static double add (double a, double b)
{
System.out.println(“Add 2 double”);
return a+b;
}
Method 1
Method 2
Method 3
The class Adder
provides multiple
implementations
of the add
method (or
function).
7
Example program to illustrate method overloading
public static void main (String[] args)
{
add (5, 7);
add (3, 6, 9);
add (2.4, 4.5);
}
}
Method 1 will be called
At each function
call, the compiler
determines
which add
method to call
based on the
data types and
number of
arguments
passed.
8
Method 2 will be called
Method 3 will be called
Add 2 int
Add 3 int
Add 2 double
Output
Runtime or dynamic polymorphism
It is a process in which a function call to the overridden method is
resolved at runtime. This type of polymorphism is achieved by method
overriding.
Method overriding
Method overriding occurs when a derived class has a definition for one
of the member methods of the base class. That base class function is
said to be overridden by the child class function.
9
Example program to illustrate method overriding
class Pizza
{
protected int radius = 16;
protected double rate = 0.8;
public double price ()
{
System.out.println(“Price of pizza”);
return (rate * Math.PI * Math.pow (radius, 2));
}
}
class HalfPizza extends Pizza
{
public double price ()
{
System.out.println(“Price of half pizza”);
return (rate * 0.5 * Math.PI * Math.pow (radius, 2));
}
}
Base class
Derived class
The base class
and the derived
class both
provide their
own
implementations
of the price
method.
10
Example program to illustrate method overriding
public class Price
{
public static void main (String[] args)
{
Pizza pz = new Pizza();
pz.price();
pz = new HalfPizza();
pz.price();
}
}
When the method price is called on
an object of the base class,
normally the base class method is
called. But when the same object is
initialised with a derived class
constructor, the derived class
method overrides the base class
method and so the derived class
method is called. This cannot be
determined at compile but during
runtime.
11
Price of pizza
Price of half pizza
Output
Differences between method overloading and
method overriding
12
Method overloading Method overriding
Increases the readability of the program by limiting
the need for unique method names.
Provides the specific implementation of the method
that is already provided by its super class.
Occurs within a class.
Occurs in two classes that have inheritance
relationship.
Parameter must be different. Parameter must be same.
Compile time polymorphism. Runtime polymorphism.
Return type can be same or different. Return type must be same or covariant.
There are other characteristics in the Java programming
language that exhibit polymorphism.
➔ Coercion
Polymorphic coercion deals with implicit type conversion done by the compiler to
prevent type errors. Some typical examples are -
double db = 9.7 + 8.1f + 2; // db = 19.8
String sos = “Help-” + 0.2; // sos = “Help-0.2”
➔ Operator overloading
Java supports some pre-defined overloaded operators. For example, the addition
operator is overloaded. It is used for both addition and string concatenation. Like -
int mx = 98 + 25; // mx = 123
String txt = “In” + “ “ + (1 + 2) + ‘D’; // txt = “In 3D”
13
There are other characteristics in the Java programming
language that exhibit polymorphism.
➔ Constructor overloading
Sometimes, we need multiple constructors to initialize different values of a class. We
can easily overload constructors like methods. For example -
public class Cat {
private int age;
public Cat () { age = 0; } // Constructor 1
public Cat (int age) { this.age = age; } // Constructor 2
public static void main (String[] args) {
Cat kit = new Cat (); // Constructor 1 is called
Cat kat = new Cat (3); // Countructor 2 is called
}
}
14
A program illustrating various kinds of polymorphism
interface Sides {
int countSides ();
}
abstract class Polygon {
double length;
abstract double perimeter ();
abstract double area ();
}
class Square extends Polygon implements Sides {
public int countSides() {
return 4;
}
double perimeter () {
return length * countSides();
}
double area () {
return length * length;
}
The class Square inherits from an
abstract class and also an
interface.
The abstract methods have
to be overridden by the
derived concrete class.
Coercion happens in some
of the methods.
The class Square
inherits from the
abstract class Polygon
and the interface
Sides. So the derived
class has two parent
classes.
This is somewhat like
multiple inheritance.
Java does not directly
support multiple
inheritance.
15
A program illustrating various kinds of polymorphism
void print () {
System.out.println ("Name of polygon = Square");
System.out.println ("Number of sides = " + countSides());
System.out.println ("Length = " + length);
System.out.println ("Perimeter = " + perimeter());
System.out.println ("Area = " + area());
}
}
public class GreenSquare extends Square {
void print () {
System.out.println ("Color = Green");
super.print ();
}
void print (String message) {
System.out.println (message);
}
public GreenSquare () {
length = 0 + 1;
}
The class GreenSquare is
a concrete class that
inherits from Square,
which is another another
concrete class.
The method print has been
overloaded.
The class also has
overloaded constructors.
The overloaded
+ operator has
been used for
addition of
integers as well
as for string
concatenation.
The method
print has been
both overridden
and overloaded.
16
A program illustrating various kinds of polymorphism
public GreenSquare (int length) {
this.length = length;
}
public static void main (String args[]) {
Square shape = new GreenSquare (6);
shape.print ();
}
}
All these
different kinds
of polymorphism
provides a lot of
stability and
flexibility.
This example
shows how
polymorphism is
important for
supporting
inheritance.
17
The reference type for
the object shape is
Square while its actual
type is GreenSquare.
The print method
defined in the
derived class
GreenSquare will be
called, instead of the
one defined in
Square.This is
because of method
overriding.
Output
Color = Green
Name of polygon = Square
Number of sides = 4
Length = 8.0
Perimeter = 32.0
Area = 64.0
18
Advantages of Polymorphism
● Polymorphism helps in reducing the coupling between different functionalities.
This increases the modularity of the program.
● It increases reusability which improves maintainability and scalability.
● Ensures the proper implementation of inheritance through method overriding.
● The concept of polymorphism is more aligned with the real world.This allows for
more robust design solutions.
● Makes programming more intuitive.
Disadvantages of Polymorphism
● Increases design complications and makes debugging harder.
● Reduced readability because the program’s runtime actions has to be recognised.
● Dynamic polymorphism may lead to performance issues.
Reference Sources
● https://www.geeksforgeeks.org/polymorphism-in-java
● https://www.mygreatlearning.com/blog/polymorphism-in-java
● https://www.slideshare.net/SpotleAI/polymorphism-in-java-149138166
● https://www.javatpoint.com/constructor-overloading-in-java
● https://www.javatpoint.com/method-overloading-vs-method-overriding-in-java
● https://teachcomputerscience.com/polymorphism
● https://www.baeldung.com/java-interface-vs-abstract-class
● Images have been taken from various websites through Google Images.
19

More Related Content

What's hot

Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Paumil Patel
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java yash jain
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...cprogrammings
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oopsHirra Sultan
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaMOHIT AGARWAL
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in javaJayasankarPR2
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in javaHrithikShinde
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of JavaFu Cheng
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++Sujan Mia
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In JavaCharthaGaglani
 

What's hot (20)

Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Inheritance and polymorphism
Inheritance and polymorphism   Inheritance and polymorphism
Inheritance and polymorphism
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
C# Encapsulation
C# EncapsulationC# Encapsulation
C# Encapsulation
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of Java
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
 

Similar to Polymorphism in Java by Animesh Sarkar

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
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in javasureshraj43
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
Polymorphism & Templates
Polymorphism & TemplatesPolymorphism & Templates
Polymorphism & TemplatesMeghaj Mallick
 
Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismCHAITALIUKE1
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxMalligaarjunanN
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالMahmoud Alfarra
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismAndiNurkholis1
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_onlinenishajj
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismIt Academy
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
Promoting Polymorphism
Promoting PolymorphismPromoting Polymorphism
Promoting PolymorphismKevlin Henney
 
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#Abid Kohistani
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsITNet
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 

Similar to Polymorphism in Java by Animesh Sarkar (20)

Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Polymorphism & Templates
Polymorphism & TemplatesPolymorphism & Templates
Polymorphism & Templates
 
Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphism
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
 
Bc0037
Bc0037Bc0037
Bc0037
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
 
Inheritance
InheritanceInheritance
Inheritance
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
Promoting Polymorphism
Promoting PolymorphismPromoting Polymorphism
Promoting 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#
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 

Recently uploaded

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 

Recently uploaded (20)

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 

Polymorphism in Java by Animesh Sarkar

  • 1. Polymorphism in Java Name: Animesh Sarkar Subject: CMSA Semester: 2 Paper: CC3 Roll no.: S49 Session: 2020-2023 1
  • 2. Index 2 Topic name Page no. What is Polymorphism? 3 A graphical example of polymorphism in pop culture. 4 Types of polymorphism. 5 Static polymorphism. 6 Example program to illustrate method overloading. 7, 8 Dynamic polymorphism. 9 Example program to illustrate method overriding, 10, 11 Differences between method overloading and overriding. 12 Some other polymorphic behaviours. 13, 14 A program illustrating various kinds of polymorphism. 15, 16, 17 Advantages and disadvantages of polymorphism. 18 Reference sources. 19
  • 3. What is polymorphism? ● Polymorphism refers to the ability to appear in many forms. It is the concept of one entity providing multiple implementations or behaviours. ● It is an important feature of Object-Oriented Programming. Java supports polymorphism. 3
  • 4. Henry Cavill Superman Clerk Kent Geralt One person shows different characteristics and behaviours depending on the character he plays. This is an example of polymorphism. 4
  • 5. Java has two types of polymorphism Compiled or static polymorphism Runtime or dynamic polymorphism 5
  • 6. Compiled or static polymorphism This type of polymorphism is achieved by method overloading and operator overloading. However, Java does not support user defined operator overloading. Method overloading When there are multiple methods with same name but different parameter list then these methods are said to be overloaded. Methods can be overloaded by changing number of arguments and/or change in type of arguments. 6
  • 7. Example program to illustrate method overloading public class Adder { public static int add (int a, int b) { System.out.println(“Add 2 int”); return a+b; } public static int add (int a, int b, int c) { System.out.println(“Add 3 int”); return a+b+c; } public static double add (double a, double b) { System.out.println(“Add 2 double”); return a+b; } Method 1 Method 2 Method 3 The class Adder provides multiple implementations of the add method (or function). 7
  • 8. Example program to illustrate method overloading public static void main (String[] args) { add (5, 7); add (3, 6, 9); add (2.4, 4.5); } } Method 1 will be called At each function call, the compiler determines which add method to call based on the data types and number of arguments passed. 8 Method 2 will be called Method 3 will be called Add 2 int Add 3 int Add 2 double Output
  • 9. Runtime or dynamic polymorphism It is a process in which a function call to the overridden method is resolved at runtime. This type of polymorphism is achieved by method overriding. Method overriding Method overriding occurs when a derived class has a definition for one of the member methods of the base class. That base class function is said to be overridden by the child class function. 9
  • 10. Example program to illustrate method overriding class Pizza { protected int radius = 16; protected double rate = 0.8; public double price () { System.out.println(“Price of pizza”); return (rate * Math.PI * Math.pow (radius, 2)); } } class HalfPizza extends Pizza { public double price () { System.out.println(“Price of half pizza”); return (rate * 0.5 * Math.PI * Math.pow (radius, 2)); } } Base class Derived class The base class and the derived class both provide their own implementations of the price method. 10
  • 11. Example program to illustrate method overriding public class Price { public static void main (String[] args) { Pizza pz = new Pizza(); pz.price(); pz = new HalfPizza(); pz.price(); } } When the method price is called on an object of the base class, normally the base class method is called. But when the same object is initialised with a derived class constructor, the derived class method overrides the base class method and so the derived class method is called. This cannot be determined at compile but during runtime. 11 Price of pizza Price of half pizza Output
  • 12. Differences between method overloading and method overriding 12 Method overloading Method overriding Increases the readability of the program by limiting the need for unique method names. Provides the specific implementation of the method that is already provided by its super class. Occurs within a class. Occurs in two classes that have inheritance relationship. Parameter must be different. Parameter must be same. Compile time polymorphism. Runtime polymorphism. Return type can be same or different. Return type must be same or covariant.
  • 13. There are other characteristics in the Java programming language that exhibit polymorphism. ➔ Coercion Polymorphic coercion deals with implicit type conversion done by the compiler to prevent type errors. Some typical examples are - double db = 9.7 + 8.1f + 2; // db = 19.8 String sos = “Help-” + 0.2; // sos = “Help-0.2” ➔ Operator overloading Java supports some pre-defined overloaded operators. For example, the addition operator is overloaded. It is used for both addition and string concatenation. Like - int mx = 98 + 25; // mx = 123 String txt = “In” + “ “ + (1 + 2) + ‘D’; // txt = “In 3D” 13
  • 14. There are other characteristics in the Java programming language that exhibit polymorphism. ➔ Constructor overloading Sometimes, we need multiple constructors to initialize different values of a class. We can easily overload constructors like methods. For example - public class Cat { private int age; public Cat () { age = 0; } // Constructor 1 public Cat (int age) { this.age = age; } // Constructor 2 public static void main (String[] args) { Cat kit = new Cat (); // Constructor 1 is called Cat kat = new Cat (3); // Countructor 2 is called } } 14
  • 15. A program illustrating various kinds of polymorphism interface Sides { int countSides (); } abstract class Polygon { double length; abstract double perimeter (); abstract double area (); } class Square extends Polygon implements Sides { public int countSides() { return 4; } double perimeter () { return length * countSides(); } double area () { return length * length; } The class Square inherits from an abstract class and also an interface. The abstract methods have to be overridden by the derived concrete class. Coercion happens in some of the methods. The class Square inherits from the abstract class Polygon and the interface Sides. So the derived class has two parent classes. This is somewhat like multiple inheritance. Java does not directly support multiple inheritance. 15
  • 16. A program illustrating various kinds of polymorphism void print () { System.out.println ("Name of polygon = Square"); System.out.println ("Number of sides = " + countSides()); System.out.println ("Length = " + length); System.out.println ("Perimeter = " + perimeter()); System.out.println ("Area = " + area()); } } public class GreenSquare extends Square { void print () { System.out.println ("Color = Green"); super.print (); } void print (String message) { System.out.println (message); } public GreenSquare () { length = 0 + 1; } The class GreenSquare is a concrete class that inherits from Square, which is another another concrete class. The method print has been overloaded. The class also has overloaded constructors. The overloaded + operator has been used for addition of integers as well as for string concatenation. The method print has been both overridden and overloaded. 16
  • 17. A program illustrating various kinds of polymorphism public GreenSquare (int length) { this.length = length; } public static void main (String args[]) { Square shape = new GreenSquare (6); shape.print (); } } All these different kinds of polymorphism provides a lot of stability and flexibility. This example shows how polymorphism is important for supporting inheritance. 17 The reference type for the object shape is Square while its actual type is GreenSquare. The print method defined in the derived class GreenSquare will be called, instead of the one defined in Square.This is because of method overriding. Output Color = Green Name of polygon = Square Number of sides = 4 Length = 8.0 Perimeter = 32.0 Area = 64.0
  • 18. 18 Advantages of Polymorphism ● Polymorphism helps in reducing the coupling between different functionalities. This increases the modularity of the program. ● It increases reusability which improves maintainability and scalability. ● Ensures the proper implementation of inheritance through method overriding. ● The concept of polymorphism is more aligned with the real world.This allows for more robust design solutions. ● Makes programming more intuitive. Disadvantages of Polymorphism ● Increases design complications and makes debugging harder. ● Reduced readability because the program’s runtime actions has to be recognised. ● Dynamic polymorphism may lead to performance issues.
  • 19. Reference Sources ● https://www.geeksforgeeks.org/polymorphism-in-java ● https://www.mygreatlearning.com/blog/polymorphism-in-java ● https://www.slideshare.net/SpotleAI/polymorphism-in-java-149138166 ● https://www.javatpoint.com/constructor-overloading-in-java ● https://www.javatpoint.com/method-overloading-vs-method-overriding-in-java ● https://teachcomputerscience.com/polymorphism ● https://www.baeldung.com/java-interface-vs-abstract-class ● Images have been taken from various websites through Google Images. 19