SlideShare a Scribd company logo
JAVA ROADMAP
Java Polymorphism – Types And
Examples
Polymorphism is one of the 4 pillars of Object-Oriented Programming. It is a
combination of two Greek words: poly and morphs. “Poly” means “many,” and
“morphs” means “forms.” So in Java, polymorphism means many forms.
Polymorphism is defined as the ability of a message to be displayed in more than
one form.
Let’s understand the meaning of polymorphism by an example:
Consider a woman in society. The same woman performs different roles in society.
The woman can be the wife of someone, the mother of her child, can be at the role
of a manager in an organization, and many more at the same time. But the Woman
is only one. So, the same woman performing different roles is polymorphism.
Another best example is your smartphone. The smartphone can act as a phone,
camera, music player, alarm, and whatnot, taking different forms and hence
polymorphism
Introduction
Polymorphism in Java refers to an object’s ability to take on multiple forms or types.
It enables the treatment of objects of different classes as objects of a common
superclass or interface. In simpler terms, polymorphism allows us to represent
different types of objects using a single variable or method.
We can relate polymorphism in real life by the following example. Consider different
types of animals. Each animal makes a distinct sound. By leveraging polymorphism,
you can define a common “makeSound” method in a superclass called “Animal,”
which is overridden in each subclass with the specific sound implementation.
// Base class Animal
class Animal {
public void makeSound() {
System.out.println("Animal making a generic sound...");
}
}
// Subclass Dog
class Dog extends Animal {
// Override the makeSound method in the Dog class
public void makeSound() {
System.out.println("Dog barking: Woof!");
}
}
// Subclass Cat
class Cat extends Animal {
// Override the makeSound method in the Cat class
public void makeSound() {
System.out.println("Cat meowing: Meow!");
}
}
// Subclass Cow
class Cow extends Animal {
// Override the makeSound method in the Cow class
public void makeSound() {
System.out.println("Cow mooing: Moo!");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
Animal cow = new Cow();
dog.makeSound();
cat.makeSound();
cow.makeSound();
}
}
Output:
Dog barking: Woof!
Cat meowing: Meow!
Cow mooing: Moo!
In this example, we have a base class Animal with a makeSound method. The
subclasses Dog, Cat, and Cow inherit from the Animal class and override the
makeSound method with their specific sound. By creating objects of each subclass
and calling the makeSound method, we observe polymorphic behavior where each
animal produces its unique sound.
This example demonstrates how polymorphism allows for the flexibility of handling
different objects through a common interface or superclass, enabling code reuse and
promoting flexibility in real-life scenarios.
How polymorphism can be achieved?
Polymorphism in Java can be achieved through two concepts i.e. method
overloading and method overriding. Let’s dive into each of these concepts:
Method Overloading
Polymorphism via method overloading enables a class to have multiple methods with
the same name but different parameters. The methods can perform similar actions
but with different data types or parameters. The Java compiler determines which
method to invoke based on the method call arguments.
Example:
class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(5, 10)); // Output: 15
System.out.println(calculator.add(3.5, 2.5)); // Output: 6.0
}
}
In the example above, the Calculator class has two add() methods. One accepts two
integers as parameters, while the other accepts two doubles. Depending on the
arguments passed during the method call, the compiler determines the appropriate
method to invoke. This allows us to use the same method name add() for different
data types, enhancing code readability and flexibility.
Method Overriding
Polymorphism through method overriding allows a subclass to provide its own
implementation of a method defined in its parent class. It involves creating a method
in the subclass with the same name, return type, and parameters as the method in
the parent class. The method in the subclass overrides the implementation of the
method in the parent class, allowing the subclass to exhibit its unique behavior.
Example:
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound(); // Output: Dog barks
}
}
In the example above, we have a superclass called Animal with a makeSound()
method. The Dog class extends the Animal class and overrides the makeSound()
method with its own implementation. When we create an object of type Animal and
assign it to a Dog object, and then call the makeSound() method, it invokes the
overridden method in the Dog class, displaying “Dog barks” as the output.
Types Of Polymorphism In Java
There are two types of polymorphism in Java: compile-time polymorphism (also
known as method overloading) and runtime polymorphism (also known as method
overriding).
1. Compile-Time Polymorphism (Method Overloading)
This type of polymorphism in Java is also called static polymorphism or static
method dispatch. It can be achieved by method overloading. In this process, an
overloaded method is resolved at compile time rather than resolving at runtime.
● Method overloading allows a class to have multiple methods with the same
name but different parameters.
● Based on the number and type of the arguments passed the compiler
determines which method to call.
● The methods may have different return types, but this alone is insufficient
to distinguish overloaded methods.
Example 1: Method Overloading with Different Number of Parameters
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(2, 3));
System.out.println(calculator.add(2, 3, 4));
}
}
Output:
5
9
In this example, the Calculator class has two add methods. The first add method
takes two parameters, a and b, and returns their sum. The second add method takes
three parameters, a, b, and c, and returns their sum. The two methods have the
same name but different numbers of parameters. Depending on the number of
arguments passed the compiler selects the appropriate method.
Example 2: Method Overloading with Different Types of Parameters
public class Converter {
public String convertToString(int number) {
return String.valueOf(number);
}
public String convertToString(double number) {
return String.valueOf(number);
}
public static void main(String[] args) {
Converter converter = new Converter();
System.out.println(converter.convertToString(42));
System.out.println(converter.convertToString(3.14));
}
}
Output:
42
3.14
In this example, the Converter class has two convertToString methods. The first
convertToString method takes an int parameter and converts it to a String. The
second convertToString method takes a double parameter and converts it to a String.
The two methods have the same name but different types of parameters. Based on
the type of the argument passed the compiler determines which method to invoke.
2. Runtime Polymorphism (Method Overriding)
Dynamic method dispatch is another name for runtime polymorphism. This
polymorphism is achieved by method overriding. The overridden method is resolved
at runtime rather than at compile time.
In Java, runtime polymorphism occurs when two or more classes are related through
inheritance. We must create an “IS-A” relationship between classes and override a
method to achieve runtime polymorphism.
● Method overriding occurs when a subclass implements a method that is
already defined in the parent class.
● The must rule of method overriding is that the subclass method must have
the same name, return type, and parameter list as the parent class
method.
● The method to invoke is determined at runtime based on the actual type of
the object.
● The @Override annotation (optional but recommended) is frequently used
to indicate that a method is intended to override a superclass method.
Example 1: Method Overriding
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat is meowing");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Cat();
Animal animal2 = new Dog();
animal1.makeSound();
animal2.makeSound();
}
}
Output:
Cat is meowing
Dog is barking
VISIT
BLOG.GEEKSTER.IN
FOR THE REMAINING

More Related Content

Similar to Java Polymorphism: Types And Examples (Geekster)

‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
Mahmoud Alfarra
 
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
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
manish kumar
 
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
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
SakkaravarthiS1
 
Virtual function
Virtual functionVirtual function
Virtual function
zindadili
 
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
 
Inheritance
InheritanceInheritance
Inheritance
Mavoori Soshmitha
 
Chapter 05 polymorphism
Chapter 05 polymorphismChapter 05 polymorphism
Chapter 05 polymorphismNurhanna Aziz
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class featuresRakesh Madugula
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
sureshraj43
 
28c
28c28c
28csharp
28csharp28csharp
28csharp
Sireesh K
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Polymorphism & Templates
Polymorphism & TemplatesPolymorphism & Templates
Polymorphism & Templates
Meghaj Mallick
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
Ahsan Raja
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
omkar bhagat
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 

Similar to Java Polymorphism: Types And Examples (Geekster) (20)

‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
 
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
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
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#
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Virtual function
Virtual functionVirtual function
Virtual function
 
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
 
Inheritance
InheritanceInheritance
Inheritance
 
Chapter 05 polymorphism
Chapter 05 polymorphismChapter 05 polymorphism
Chapter 05 polymorphism
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
28c
28c28c
28c
 
28csharp
28csharp28csharp
28csharp
 
Core java oop
Core java oopCore java oop
Core java oop
 
Polymorphism & Templates
Polymorphism & TemplatesPolymorphism & Templates
Polymorphism & Templates
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 

More from Geekster

Constructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationConstructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object Creation
Geekster
 
JVM Architecture – How It Works.pdf
JVM Architecture – How It Works.pdfJVM Architecture – How It Works.pdf
JVM Architecture – How It Works.pdf
Geekster
 
Setting Up Java Environment | PDF
Setting Up Java Environment | PDFSetting Up Java Environment | PDF
Setting Up Java Environment | PDF
Geekster
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDF
Geekster
 
OOps Interview questions.pdf
OOps Interview questions.pdfOOps Interview questions.pdf
OOps Interview questions.pdf
Geekster
 
2 Important Data Structure Interview Questions
2 Important Data Structure Interview Questions2 Important Data Structure Interview Questions
2 Important Data Structure Interview Questions
Geekster
 
What are the 7 features of Python?pdf
What are the 7 features of Python?pdfWhat are the 7 features of Python?pdf
What are the 7 features of Python?pdf
Geekster
 

More from Geekster (7)

Constructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationConstructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object Creation
 
JVM Architecture – How It Works.pdf
JVM Architecture – How It Works.pdfJVM Architecture – How It Works.pdf
JVM Architecture – How It Works.pdf
 
Setting Up Java Environment | PDF
Setting Up Java Environment | PDFSetting Up Java Environment | PDF
Setting Up Java Environment | PDF
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDF
 
OOps Interview questions.pdf
OOps Interview questions.pdfOOps Interview questions.pdf
OOps Interview questions.pdf
 
2 Important Data Structure Interview Questions
2 Important Data Structure Interview Questions2 Important Data Structure Interview Questions
2 Important Data Structure Interview Questions
 
What are the 7 features of Python?pdf
What are the 7 features of Python?pdfWhat are the 7 features of Python?pdf
What are the 7 features of Python?pdf
 

Recently uploaded

Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 

Recently uploaded (20)

Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 

Java Polymorphism: Types And Examples (Geekster)

  • 1. JAVA ROADMAP Java Polymorphism – Types And Examples Polymorphism is one of the 4 pillars of Object-Oriented Programming. It is a combination of two Greek words: poly and morphs. “Poly” means “many,” and “morphs” means “forms.” So in Java, polymorphism means many forms. Polymorphism is defined as the ability of a message to be displayed in more than one form. Let’s understand the meaning of polymorphism by an example: Consider a woman in society. The same woman performs different roles in society. The woman can be the wife of someone, the mother of her child, can be at the role of a manager in an organization, and many more at the same time. But the Woman is only one. So, the same woman performing different roles is polymorphism. Another best example is your smartphone. The smartphone can act as a phone, camera, music player, alarm, and whatnot, taking different forms and hence polymorphism
  • 2. Introduction Polymorphism in Java refers to an object’s ability to take on multiple forms or types. It enables the treatment of objects of different classes as objects of a common superclass or interface. In simpler terms, polymorphism allows us to represent different types of objects using a single variable or method. We can relate polymorphism in real life by the following example. Consider different types of animals. Each animal makes a distinct sound. By leveraging polymorphism, you can define a common “makeSound” method in a superclass called “Animal,” which is overridden in each subclass with the specific sound implementation. // Base class Animal class Animal { public void makeSound() { System.out.println("Animal making a generic sound..."); } } // Subclass Dog class Dog extends Animal { // Override the makeSound method in the Dog class public void makeSound() { System.out.println("Dog barking: Woof!");
  • 3. } } // Subclass Cat class Cat extends Animal { // Override the makeSound method in the Cat class public void makeSound() { System.out.println("Cat meowing: Meow!"); } } // Subclass Cow class Cow extends Animal { // Override the makeSound method in the Cow class public void makeSound() { System.out.println("Cow mooing: Moo!"); } } public class Main { public static void main(String[] args) { Animal dog = new Dog(); Animal cat = new Cat(); Animal cow = new Cow(); dog.makeSound(); cat.makeSound(); cow.makeSound(); } } Output: Dog barking: Woof! Cat meowing: Meow! Cow mooing: Moo! In this example, we have a base class Animal with a makeSound method. The subclasses Dog, Cat, and Cow inherit from the Animal class and override the makeSound method with their specific sound. By creating objects of each subclass and calling the makeSound method, we observe polymorphic behavior where each animal produces its unique sound. This example demonstrates how polymorphism allows for the flexibility of handling different objects through a common interface or superclass, enabling code reuse and promoting flexibility in real-life scenarios.
  • 4. How polymorphism can be achieved? Polymorphism in Java can be achieved through two concepts i.e. method overloading and method overriding. Let’s dive into each of these concepts: Method Overloading Polymorphism via method overloading enables a class to have multiple methods with the same name but different parameters. The methods can perform similar actions but with different data types or parameters. The Java compiler determines which method to invoke based on the method call arguments. Example: class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } } public class Main { public static void main(String[] args) { Calculator calculator = new Calculator(); System.out.println(calculator.add(5, 10)); // Output: 15 System.out.println(calculator.add(3.5, 2.5)); // Output: 6.0 } } In the example above, the Calculator class has two add() methods. One accepts two integers as parameters, while the other accepts two doubles. Depending on the arguments passed during the method call, the compiler determines the appropriate method to invoke. This allows us to use the same method name add() for different data types, enhancing code readability and flexibility. Method Overriding Polymorphism through method overriding allows a subclass to provide its own implementation of a method defined in its parent class. It involves creating a method in the subclass with the same name, return type, and parameters as the method in the parent class. The method in the subclass overrides the implementation of the method in the parent class, allowing the subclass to exhibit its unique behavior.
  • 5. Example: class Animal { public void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override public void makeSound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal animal = new Dog(); animal.makeSound(); // Output: Dog barks } } In the example above, we have a superclass called Animal with a makeSound() method. The Dog class extends the Animal class and overrides the makeSound() method with its own implementation. When we create an object of type Animal and assign it to a Dog object, and then call the makeSound() method, it invokes the overridden method in the Dog class, displaying “Dog barks” as the output. Types Of Polymorphism In Java There are two types of polymorphism in Java: compile-time polymorphism (also known as method overloading) and runtime polymorphism (also known as method overriding). 1. Compile-Time Polymorphism (Method Overloading) This type of polymorphism in Java is also called static polymorphism or static method dispatch. It can be achieved by method overloading. In this process, an overloaded method is resolved at compile time rather than resolving at runtime. ● Method overloading allows a class to have multiple methods with the same name but different parameters.
  • 6. ● Based on the number and type of the arguments passed the compiler determines which method to call. ● The methods may have different return types, but this alone is insufficient to distinguish overloaded methods. Example 1: Method Overloading with Different Number of Parameters public class Calculator { public int add(int a, int b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } public static void main(String[] args) { Calculator calculator = new Calculator(); System.out.println(calculator.add(2, 3)); System.out.println(calculator.add(2, 3, 4)); } } Output: 5 9 In this example, the Calculator class has two add methods. The first add method takes two parameters, a and b, and returns their sum. The second add method takes three parameters, a, b, and c, and returns their sum. The two methods have the same name but different numbers of parameters. Depending on the number of arguments passed the compiler selects the appropriate method. Example 2: Method Overloading with Different Types of Parameters public class Converter { public String convertToString(int number) { return String.valueOf(number); } public String convertToString(double number) { return String.valueOf(number); }
  • 7. public static void main(String[] args) { Converter converter = new Converter(); System.out.println(converter.convertToString(42)); System.out.println(converter.convertToString(3.14)); } } Output: 42 3.14 In this example, the Converter class has two convertToString methods. The first convertToString method takes an int parameter and converts it to a String. The second convertToString method takes a double parameter and converts it to a String. The two methods have the same name but different types of parameters. Based on the type of the argument passed the compiler determines which method to invoke. 2. Runtime Polymorphism (Method Overriding) Dynamic method dispatch is another name for runtime polymorphism. This polymorphism is achieved by method overriding. The overridden method is resolved at runtime rather than at compile time. In Java, runtime polymorphism occurs when two or more classes are related through inheritance. We must create an “IS-A” relationship between classes and override a method to achieve runtime polymorphism. ● Method overriding occurs when a subclass implements a method that is already defined in the parent class. ● The must rule of method overriding is that the subclass method must have the same name, return type, and parameter list as the parent class method. ● The method to invoke is determined at runtime based on the actual type of the object. ● The @Override annotation (optional but recommended) is frequently used to indicate that a method is intended to override a superclass method. Example 1: Method Overriding class Animal { public void makeSound() {
  • 8. System.out.println("Animal is making a sound"); } } class Cat extends Animal { @Override public void makeSound() { System.out.println("Cat is meowing"); } } class Dog extends Animal { @Override public void makeSound() { System.out.println("Dog is barking"); } } public class Main { public static void main(String[] args) { Animal animal1 = new Cat(); Animal animal2 = new Dog(); animal1.makeSound(); animal2.makeSound(); } } Output: Cat is meowing Dog is barking VISIT BLOG.GEEKSTER.IN FOR THE REMAINING