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

What's hot (20)

Method overloading
Method overloadingMethod overloading
Method overloading
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Main method in java
Main method in javaMain method in java
Main method in java
 
Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
polymorphism
polymorphism polymorphism
polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

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
 
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
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdfriyawagh2
 

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)
 
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
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
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
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 

Recently uploaded (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
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
 
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...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 

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