SlideShare a Scribd company logo
What is Polymorphism?
 Polymorphism is the ability of an object to take more than one forms. It is one of the important concept of
object-oriented programming language. JAVA is object-oriented programming language which support the
concept of polymorphisms.
 Alternatively, it is defined as the ability of a reference variable to change behaviour according to what
object instance it is holding.
 This allows multiple objects of different subclasses to be treated as objects of a single parent class, while
automatically selecting the proper methods to apply to an object based on the child class it belongs.
1) compile-time polymorphism (static binding)
2) runtime polymorphism (dynamic binding)
Method overloading is an example of compile time polymorphism, while method overriding is an example of runtime
polymorphism.
There are two types of polymorphism in Java:
1. Compile time Polymorphism:
The type of polymorphism that is implemented when the compiler compiles a program is called compile-time
polymorphism. This type of polymorphism is also called as static polymorphism or early binding.
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
Method overloading is performed within class.
If we must perform only one operation, having same name of the methods increases the readability of the program.
There are three ways to overload the method in java
• By changing number of arguments
• By changing the data type
• By changing both number of arguments and data type
Continue..
a. Method overloading by changing number of argument:
▪ Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the
▪ method such as x(int,int) for two parameters, and y(int,int,int) for three parameters then it may be difficult
for you as well
▪ as other programmers to understand the behaviour of the method because its name differs.
Polymorphism in Java – Example1:
In the following program, two methods are created, first add1() performs addition of two numbers and second
add1() performs addition of three numbers.
In following example, we are creating static methods so that we don’t need to create instance for calling
methods.
5
class Addition
{
static int add1 (int a,int b)
{
return a+b;
}
static int add1(int a,int b,int c)
{
return a+b+c;
}
}
class xyz
{
public static void main(String[] args)
{
System.out.println(Addition.add1(13,13));
System.out.println(Addition.add1(9,9,9));
}
}
b. Method Overloading by changing the data type:
Sometime there is need to use the same method which is having different data type. In the following program, we have
created two methods that differs in data type. The first add1() method receives two integer arguments and second add1()
method receives two double arguments.
class Addition
{
static int add1 (int a,int b)
{
return a+b;
}
static double add1(double a,double b)
{
return a+b;
}
}
.
class xyz1
{
public static void main(String[] args)
{
System.out.println(Addition.add1(13,13));
System.out.println(Addition.add1(9.5,9.5));
}
}
Output:
26
19
c. Method Overloading by changing both number of argument and data type:
Sometimes we may need to use the method which is having the different number of argument and different data type. In
the following program, both number of argument and data type is to be changed. Here the method do() is overloaded 3
times: first having one int parameter, second one has 2 int parameters and third one is having double arg. The methods
are invoked or called with the same type and number of parameters used.
class Overload1
{
void do (int a)
{
System.out.println ("a: " + a);
}
void do (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double do(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
TIME FOR EXPERIMENT
class Overload2
{
public static void main (String args [])
{
Overload1 Obj = new Overload1();
double result;
Obj.do(20);
Obj.do(20, 30);
result = Obj.do(4.5);
System.out.println("Output is: " + result);
}
}
a: 20
a and b: 20,30
double a: 4.5
Output is: 20.25
Continue..
2. Run-time Polymorphism
The type of polymorphism which is implemented dynamically when a program being executed is called as run-
time polymorphism. The run-time polymorphism is also called dynamic polymorphism or late binding.
Method Overriding in Java
Method overriding is used to achieve the runtime polymorphism or dynamic binding. In method overriding the
method must have the same name as in the parent class and it must have the same parameter as in the parent class.
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in
Java. Method overriding occurs in two classes that have IS-A (inheritance) relationship.
Example 1 of method overriding
In the following program, we have defined the do() method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.
11
//parent class
class Animal
{
//define method
void do()
{
System.out.println("Animal is eating food");
}
}
//Create child class
class dog extends Animal
{
//define the same method as in the parent class
void do()
{
System.out.println("Dog is eating food ");
}
public static void main(String args[])
{
dog obj = new dog();//creating object
obj.do();//calling method
}
}
Output:
Dog is eating food
Example 2 of Method Overriding
An example or program given below from real world where Vehicle is parent class. It can have Vehicle class, and its specialized child
classes like bike and car. These subclasses will override the default behavior provided by Vehicle class and some of its own specific
behavior.
public class Vehicle
{
public void run()
{
System.out.println("some speed");
}
}
class bike extends Vehicle
{
public void run()
{
System.out.println("speed is slower than car");
}
}
Copyright @ 2018 Learntek. All Rights Reserved. 15
class car extends Vehicle
{
public void run()
{
System.out.println("speed is faster than bike");
}
}
// Next, run() method will be called, depends on type of actual instance created on runtime
public class Demo
{
public static void main(String[] args)
{
Vehicle v1 = new bike();
v1.run();
Vehicle v2 = new car();
v2.run();
}
}
Copyright @ 2018 Learntek. All Rights Reserved. 16
Output
speed is faster than bike
speed is slower than car
Advantage of polymorphism:
 It helps programmers to reuse the code, classes, methods written once, tested and implemented. They may be
reused in many ways.
 The single variable name can be used to store variables of multiple data types such as Int, Float, double,
Long etc).
 Polymorphism helps in reducing the coupling between different functionalities.
Copyright @ 2018 Learntek. All Rights Reserved. 17
 Method overloading can be implemented on constructors allowing different ways to initialize objects of a class.
This enables you to define multiple constructors for handling different types of initializations.
 Method overriding works together with inheritance to enable code reuse of existing classes without the need for
re-compilation.
Disadvantage of polymorphism:
• One of the main disadvantages of polymorphism is that developers find it difficult to implement polymorphism in
codes.
• Run time polymorphism can lead to the performance issue where machine needs to decide which method or variable
to invoke so it basically degrades the performances as decisions are taken at run time.
• Polymorphism reduces the readability of the program. One needs to identify the runtime behavior of the program to
identify actual execution time.

More Related Content

What's hot

polymorphism
polymorphism polymorphism
polymorphism
Imtiaz Hussain
 
Templates
TemplatesTemplates
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Polymorphism and its types
Polymorphism and its typesPolymorphism and its types
Polymorphism and its types
Suraj Bora
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
harsh kothari
 
Abstract class
Abstract classAbstract class
Abstract class
Tony Nguyen
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Nochiketa Chakraborty
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 
This keyword and final keyword
This keyword and final  keywordThis keyword and final  keyword
This keyword and final keyword
kinjalbirare
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
Harshal Misalkar
 
Javapolymorphism
JavapolymorphismJavapolymorphism
Javapolymorphism
karthikenlume
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
Md. Ashraful Islam
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
Rokonuzzaman Rony
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 

What's hot (20)

polymorphism
polymorphism polymorphism
polymorphism
 
Templates
TemplatesTemplates
Templates
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Polymorphism and its types
Polymorphism and its typesPolymorphism and its types
Polymorphism and its types
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Abstract class
Abstract classAbstract class
Abstract class
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
This keyword and final keyword
This keyword and final  keywordThis keyword and final  keyword
This keyword and final keyword
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
 
Javapolymorphism
JavapolymorphismJavapolymorphism
Javapolymorphism
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
Method overloading
Method overloadingMethod overloading
Method overloading
 

Similar to Polymorphism in java

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.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
RiturajJain8
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Akhil Mittal
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentation
bhargavi804095
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaion
bhargavi804095
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
nishajj
 
polymorphism method overloading and overriding .pptx
polymorphism method overloading  and overriding .pptxpolymorphism method overloading  and overriding .pptx
polymorphism method overloading and overriding .pptx
thamaraiselvangts441
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
AndiNurkholis1
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
SajidTk2
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
Prem Kumar Badri
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
Export Promotion Bureau
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
ilias ahmed
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
Inocentshuja Ahmad
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
Suresh Mohta
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
AnmolVerma363503
 
An Introduction to C# and .NET Framework (Basic)
An Introduction to C# and .NET Framework (Basic)An Introduction to C# and .NET Framework (Basic)
An Introduction to C# and .NET Framework (Basic)
Khubaib Ahmad Kunjahi
 

Similar to Polymorphism in java (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.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentation
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaion
 
Learn java lessons_online
Learn java lessons_onlineLearn java lessons_online
Learn java lessons_online
 
polymorphism method overloading and overriding .pptx
polymorphism method overloading  and overriding .pptxpolymorphism method overloading  and overriding .pptx
polymorphism method overloading and overriding .pptx
 
Object Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. PolymorphismObject Oriented Programming - 7.2. Polymorphism
Object Oriented Programming - 7.2. Polymorphism
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Overloadingmethod
OverloadingmethodOverloadingmethod
Overloadingmethod
 
java poly ppt.pptx
java poly ppt.pptxjava poly ppt.pptx
java poly ppt.pptx
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
An Introduction to C# and .NET Framework (Basic)
An Introduction to C# and .NET Framework (Basic)An Introduction to C# and .NET Framework (Basic)
An Introduction to C# and .NET Framework (Basic)
 

More from Janu Jahnavi

Analytics using r programming
Analytics using r programmingAnalytics using r programming
Analytics using r programming
Janu Jahnavi
 
Software testing
Software testingSoftware testing
Software testing
Janu Jahnavi
 
Software testing
Software testingSoftware testing
Software testing
Janu Jahnavi
 
Spring
SpringSpring
Spring
Janu Jahnavi
 
Stack skills
Stack skillsStack skills
Stack skills
Janu Jahnavi
 
Ui devopler
Ui devoplerUi devopler
Ui devopler
Janu Jahnavi
 
Apache flink
Apache flinkApache flink
Apache flink
Janu Jahnavi
 
Apache flink
Apache flinkApache flink
Apache flink
Janu Jahnavi
 
Angular js
Angular jsAngular js
Angular js
Janu Jahnavi
 
Mysql python
Mysql pythonMysql python
Mysql python
Janu Jahnavi
 
Mysql python
Mysql pythonMysql python
Mysql python
Janu Jahnavi
 
Ruby with cucmber
Ruby with cucmberRuby with cucmber
Ruby with cucmber
Janu Jahnavi
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
Janu Jahnavi
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
Janu Jahnavi
 
Google cloud platform
Google cloud platformGoogle cloud platform
Google cloud platform
Janu Jahnavi
 
Google cloud Platform
Google cloud PlatformGoogle cloud Platform
Google cloud Platform
Janu Jahnavi
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
Janu Jahnavi
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
Janu Jahnavi
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
Janu Jahnavi
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
Janu Jahnavi
 

More from Janu Jahnavi (20)

Analytics using r programming
Analytics using r programmingAnalytics using r programming
Analytics using r programming
 
Software testing
Software testingSoftware testing
Software testing
 
Software testing
Software testingSoftware testing
Software testing
 
Spring
SpringSpring
Spring
 
Stack skills
Stack skillsStack skills
Stack skills
 
Ui devopler
Ui devoplerUi devopler
Ui devopler
 
Apache flink
Apache flinkApache flink
Apache flink
 
Apache flink
Apache flinkApache flink
Apache flink
 
Angular js
Angular jsAngular js
Angular js
 
Mysql python
Mysql pythonMysql python
Mysql python
 
Mysql python
Mysql pythonMysql python
Mysql python
 
Ruby with cucmber
Ruby with cucmberRuby with cucmber
Ruby with cucmber
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Google cloud platform
Google cloud platformGoogle cloud platform
Google cloud platform
 
Google cloud Platform
Google cloud PlatformGoogle cloud Platform
Google cloud Platform
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
 

Recently uploaded

Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 

Recently uploaded (20)

Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 

Polymorphism in java

  • 1.
  • 2. What is Polymorphism?  Polymorphism is the ability of an object to take more than one forms. It is one of the important concept of object-oriented programming language. JAVA is object-oriented programming language which support the concept of polymorphisms.  Alternatively, it is defined as the ability of a reference variable to change behaviour according to what object instance it is holding.  This allows multiple objects of different subclasses to be treated as objects of a single parent class, while automatically selecting the proper methods to apply to an object based on the child class it belongs.
  • 3. 1) compile-time polymorphism (static binding) 2) runtime polymorphism (dynamic binding) Method overloading is an example of compile time polymorphism, while method overriding is an example of runtime polymorphism. There are two types of polymorphism in Java:
  • 4. 1. Compile time Polymorphism: The type of polymorphism that is implemented when the compiler compiles a program is called compile-time polymorphism. This type of polymorphism is also called as static polymorphism or early binding. Method Overloading: If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. Method overloading is performed within class. If we must perform only one operation, having same name of the methods increases the readability of the program. There are three ways to overload the method in java • By changing number of arguments • By changing the data type • By changing both number of arguments and data type
  • 5. Continue.. a. Method overloading by changing number of argument: ▪ Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the ▪ method such as x(int,int) for two parameters, and y(int,int,int) for three parameters then it may be difficult for you as well ▪ as other programmers to understand the behaviour of the method because its name differs. Polymorphism in Java – Example1: In the following program, two methods are created, first add1() performs addition of two numbers and second add1() performs addition of three numbers. In following example, we are creating static methods so that we don’t need to create instance for calling methods. 5
  • 6. class Addition { static int add1 (int a,int b) { return a+b; } static int add1(int a,int b,int c) { return a+b+c; } } class xyz { public static void main(String[] args) { System.out.println(Addition.add1(13,13)); System.out.println(Addition.add1(9,9,9)); } }
  • 7. b. Method Overloading by changing the data type: Sometime there is need to use the same method which is having different data type. In the following program, we have created two methods that differs in data type. The first add1() method receives two integer arguments and second add1() method receives two double arguments. class Addition { static int add1 (int a,int b) { return a+b; } static double add1(double a,double b) { return a+b; } }
  • 8. . class xyz1 { public static void main(String[] args) { System.out.println(Addition.add1(13,13)); System.out.println(Addition.add1(9.5,9.5)); } } Output: 26 19
  • 9. c. Method Overloading by changing both number of argument and data type: Sometimes we may need to use the method which is having the different number of argument and different data type. In the following program, both number of argument and data type is to be changed. Here the method do() is overloaded 3 times: first having one int parameter, second one has 2 int parameters and third one is having double arg. The methods are invoked or called with the same type and number of parameters used. class Overload1 { void do (int a) { System.out.println ("a: " + a); } void do (int a, int b) { System.out.println ("a and b: " + a + "," + b); } double do(double a) { System.out.println("double a: " + a); return a*a; } }
  • 10. TIME FOR EXPERIMENT class Overload2 { public static void main (String args []) { Overload1 Obj = new Overload1(); double result; Obj.do(20); Obj.do(20, 30); result = Obj.do(4.5); System.out.println("Output is: " + result); } } a: 20 a and b: 20,30 double a: 4.5 Output is: 20.25
  • 11. Continue.. 2. Run-time Polymorphism The type of polymorphism which is implemented dynamically when a program being executed is called as run- time polymorphism. The run-time polymorphism is also called dynamic polymorphism or late binding. Method Overriding in Java Method overriding is used to achieve the runtime polymorphism or dynamic binding. In method overriding the method must have the same name as in the parent class and it must have the same parameter as in the parent class. If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. Method overriding occurs in two classes that have IS-A (inheritance) relationship. Example 1 of method overriding In the following program, we have defined the do() method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there is method overriding. 11
  • 12. //parent class class Animal { //define method void do() { System.out.println("Animal is eating food"); } } //Create child class class dog extends Animal { //define the same method as in the parent class void do() { System.out.println("Dog is eating food "); }
  • 13. public static void main(String args[]) { dog obj = new dog();//creating object obj.do();//calling method } } Output: Dog is eating food
  • 14. Example 2 of Method Overriding An example or program given below from real world where Vehicle is parent class. It can have Vehicle class, and its specialized child classes like bike and car. These subclasses will override the default behavior provided by Vehicle class and some of its own specific behavior. public class Vehicle { public void run() { System.out.println("some speed"); } } class bike extends Vehicle { public void run() { System.out.println("speed is slower than car"); } }
  • 15. Copyright @ 2018 Learntek. All Rights Reserved. 15 class car extends Vehicle { public void run() { System.out.println("speed is faster than bike"); } } // Next, run() method will be called, depends on type of actual instance created on runtime public class Demo { public static void main(String[] args) { Vehicle v1 = new bike(); v1.run(); Vehicle v2 = new car(); v2.run(); } }
  • 16. Copyright @ 2018 Learntek. All Rights Reserved. 16 Output speed is faster than bike speed is slower than car Advantage of polymorphism:  It helps programmers to reuse the code, classes, methods written once, tested and implemented. They may be reused in many ways.  The single variable name can be used to store variables of multiple data types such as Int, Float, double, Long etc).  Polymorphism helps in reducing the coupling between different functionalities.
  • 17. Copyright @ 2018 Learntek. All Rights Reserved. 17  Method overloading can be implemented on constructors allowing different ways to initialize objects of a class. This enables you to define multiple constructors for handling different types of initializations.  Method overriding works together with inheritance to enable code reuse of existing classes without the need for re-compilation. Disadvantage of polymorphism: • One of the main disadvantages of polymorphism is that developers find it difficult to implement polymorphism in codes. • Run time polymorphism can lead to the performance issue where machine needs to decide which method or variable to invoke so it basically degrades the performances as decisions are taken at run time. • Polymorphism reduces the readability of the program. One needs to identify the runtime behavior of the program to identify actual execution time.