SlideShare a Scribd company logo
1 of 19
Download to read offline
Polymorphism



               1
Agenda

●   What is and Why Polymorphism?
●   Examples of Polymorphism in Java programs
●   3 forms of Polymorphism




                                                2
What is & Why
Polymorphism?
                 3
What is Polymorphism?

●   Generally, polymorphism refers to the ability to
    appear in many forms
●   Polymorphism in a Java program
    –   The ability of a reference variable to change
        behavior according to what object instance it is
        holding.
    –   This allows multiple objects of different subclasses
        to be treated as objects of a single super class,
        while automatically selecting the proper methods to
        apply to a particular object based on the subclass it
        belongs to

                                                                4
Polymorphism Example

●   For example, given a base class shape,
    polymorphism enables the programmer to define
    different area methods for any number of derived
    classes, such as circles, rectangles and triangles.
    No matter what shape an object is, applying the
    area method to it will return the correct results.




                                                          5
Examples of
Polymorphic Behavior
  in Java Programs
                       6
Example #1: Polymorphism
●   Given the parent class Person and the child class
    Student, we add another subclass of Person
    which is Employee.
●   Below is the class hierarchy




                                                        7
Example #1: Polymorphism
●   In Java, we can create a reference that is of type
    super class, Person, to an object of its subclass,
    Student.
    public static main( String[] args ) {

        Student studentObject = new Student();
        Employee employeeObject = new Employee();

        Person ref = studentObject; // Person reference points
                                    // to a Student object

        // Calling getName() of the Student object instance
        String name = ref.getName();
    }

                                                              8
Example #1: Polymorphism
●   Now suppose we have a getName method in our
    super class Person, and we override this method in
    both Student and Employee subclass's
    public class Student {
       public String getName(){
          System.out.println(“Student Name:” + name);
          return name;
       }
    }

    public class Employee {
       public String getName(){
          System.out.println(“Employee Name:” + name);
          return name;
       }
    }                                                    9
Example #1: Polymorphism

●   Going back to our main method, when we try to call
    the getName method of the reference Person ref,
    the getName method of the Student object will be
    called.

●   Now, if we assign ref to an Employee object, the
    getName method of Employee will be called.




                                                         10
Example #1: Polymorphism
1 public static main( String[] args ) {
2
3    Student studentObject = new Student();
4    Employee employeeObject = new Employee();
5
6    Person ref = studentObject; //Person ref. points to a
7                            // Student object
8
9    // getName() method of Student class is called
10   String temp= ref.getName();
11   System.out.println( temp );
12
13   ref = employeeObject; //Person ref. points to an
14                           // Employee object
15
16   //getName() method of Employee class is called
17   String temp = ref.getName();
18   System.out.println( temp );
19 }

                                                             11
Example #2: Polymorphism

●   Another example that illustrates polymorphism is
    when we try to pass a reference to methods as a
    parameter

●   Suppose we have a static method printInformation
    that takes in a Person reference as parameter.

    public static printInformation( Person p ){
        // It will call getName() method of the
        // actual object instance that is passed
        p.getName();
    }


                                                       12
Example #2: Polymorphism

●   We can actually pass a reference of type Employee
    and type Student to the printInformation method as
    long as it is a subclass of the Person class.

public static main( String[] args ){

       Student    studentObject = new Student();
       Employee   employeeObject = new Employee();

       printInformation( studentObject );

       printInformation( employeeObject );
}



                                                         13
Benefits of
Polymorphism
                14
Benefits of Polymorphism

●   Simplicity
    –   If you need to write code that deals with a family of types,
        the code can ignore type-specific details and just interact
        with the base type of the family
    –   Even though the code thinks it is using an object of the
        base class, the object's class could actually be the base
        class or any one of its subclasses
    –   This makes your code easier for you to write and easier
        for others to understand




                                                                       15
Benefits of Polymorphism

●   Extensibility
    –   Other subclasses could be added later to the family of
        types, and objects of those new subclasses would also
        work with the existing code




                                                                 16
3 Forms of
Polymorphism
               17
3 Forms of Polymorphism
             in Java program
●   Method overriding
    –   Methods of a subclass override the methods of a
        superclass
●   Method overriding (implementation) of the abstract
    methods
    –   Methods of a subclass implement the abstract methods
        of an abstract class
●   Method overriding (implementation) through the
    Java interface
    –   Methods of a concrete class implement the methods of
        the interface
                                                               18
Polymorphism



               19

More Related Content

What's hot

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 

What's hot (20)

Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
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
 
OOP java
OOP javaOOP java
OOP java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
L11 array list
L11 array listL11 array list
L11 array list
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Main method in java
Main method in javaMain method in java
Main method in java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 

Viewers also liked

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Math
MathMath
Math
THN06
 
Rapat kabinet bem fkip untan
Rapat kabinet bem fkip untanRapat kabinet bem fkip untan
Rapat kabinet bem fkip untan
Irwin Septian
 
050113 fax to judy clarke (boston marathon bombing) - armenian
050113   fax to judy clarke (boston marathon bombing) - armenian050113   fax to judy clarke (boston marathon bombing) - armenian
050113 fax to judy clarke (boston marathon bombing) - armenian
VogelDenise
 

Viewers also liked (19)

Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Swt vs swing
Swt vs swingSwt vs swing
Swt vs swing
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Java awt
Java awtJava awt
Java awt
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Inheritance
InheritanceInheritance
Inheritance
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Math
MathMath
Math
 
Rapat kabinet bem fkip untan
Rapat kabinet bem fkip untanRapat kabinet bem fkip untan
Rapat kabinet bem fkip untan
 
050113 fax to judy clarke (boston marathon bombing) - armenian
050113   fax to judy clarke (boston marathon bombing) - armenian050113   fax to judy clarke (boston marathon bombing) - armenian
050113 fax to judy clarke (boston marathon bombing) - armenian
 
Consumo responsable
Consumo responsableConsumo responsable
Consumo responsable
 
BAKER DONELSON - Attorney Layoffs The SINKING OF A TERRORIST REGIME (GALICIAN)
BAKER DONELSON - Attorney Layoffs The SINKING OF A TERRORIST REGIME (GALICIAN)BAKER DONELSON - Attorney Layoffs The SINKING OF A TERRORIST REGIME (GALICIAN)
BAKER DONELSON - Attorney Layoffs The SINKING OF A TERRORIST REGIME (GALICIAN)
 

Similar to Javapolymorphism

P.7 media 2 polymorphism
P.7 media 2 polymorphismP.7 media 2 polymorphism
P.7 media 2 polymorphism
ahmadmuzaqqi
 
Object Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdfObject Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdf
RishuRaj953240
 
9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf
anaveenkumar4
 

Similar to Javapolymorphism (20)

Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
 
javainheritance
javainheritancejavainheritance
javainheritance
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Java
JavaJava
Java
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
P.7 media 2 polymorphism
P.7 media 2 polymorphismP.7 media 2 polymorphism
P.7 media 2 polymorphism
 
Object Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdfObject Oriented programming Using Python.pdf
Object Oriented programming Using Python.pdf
 
9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf
 
Learn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdfLearn Polymorphism in Python with Examples.pdf
Learn Polymorphism in Python with Examples.pdf
 
8 polymorphism
8 polymorphism8 polymorphism
8 polymorphism
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented Programming
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
Oop concept
Oop conceptOop concept
Oop concept
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
java - oop's in depth journey
java - oop's in depth journeyjava - oop's in depth journey
java - oop's in depth journey
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Javapolymorphism

  • 2. Agenda ● What is and Why Polymorphism? ● Examples of Polymorphism in Java programs ● 3 forms of Polymorphism 2
  • 3. What is & Why Polymorphism? 3
  • 4. What is Polymorphism? ● Generally, polymorphism refers to the ability to appear in many forms ● Polymorphism in a Java program – The ability of a reference variable to change behavior according to what object instance it is holding. – This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to 4
  • 5. Polymorphism Example ● For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. 5
  • 6. Examples of Polymorphic Behavior in Java Programs 6
  • 7. Example #1: Polymorphism ● Given the parent class Person and the child class Student, we add another subclass of Person which is Employee. ● Below is the class hierarchy 7
  • 8. Example #1: Polymorphism ● In Java, we can create a reference that is of type super class, Person, to an object of its subclass, Student. public static main( String[] args ) { Student studentObject = new Student(); Employee employeeObject = new Employee(); Person ref = studentObject; // Person reference points // to a Student object // Calling getName() of the Student object instance String name = ref.getName(); } 8
  • 9. Example #1: Polymorphism ● Now suppose we have a getName method in our super class Person, and we override this method in both Student and Employee subclass's public class Student { public String getName(){ System.out.println(“Student Name:” + name); return name; } } public class Employee { public String getName(){ System.out.println(“Employee Name:” + name); return name; } } 9
  • 10. Example #1: Polymorphism ● Going back to our main method, when we try to call the getName method of the reference Person ref, the getName method of the Student object will be called. ● Now, if we assign ref to an Employee object, the getName method of Employee will be called. 10
  • 11. Example #1: Polymorphism 1 public static main( String[] args ) { 2 3 Student studentObject = new Student(); 4 Employee employeeObject = new Employee(); 5 6 Person ref = studentObject; //Person ref. points to a 7 // Student object 8 9 // getName() method of Student class is called 10 String temp= ref.getName(); 11 System.out.println( temp ); 12 13 ref = employeeObject; //Person ref. points to an 14 // Employee object 15 16 //getName() method of Employee class is called 17 String temp = ref.getName(); 18 System.out.println( temp ); 19 } 11
  • 12. Example #2: Polymorphism ● Another example that illustrates polymorphism is when we try to pass a reference to methods as a parameter ● Suppose we have a static method printInformation that takes in a Person reference as parameter. public static printInformation( Person p ){ // It will call getName() method of the // actual object instance that is passed p.getName(); } 12
  • 13. Example #2: Polymorphism ● We can actually pass a reference of type Employee and type Student to the printInformation method as long as it is a subclass of the Person class. public static main( String[] args ){ Student studentObject = new Student(); Employee employeeObject = new Employee(); printInformation( studentObject ); printInformation( employeeObject ); } 13
  • 15. Benefits of Polymorphism ● Simplicity – If you need to write code that deals with a family of types, the code can ignore type-specific details and just interact with the base type of the family – Even though the code thinks it is using an object of the base class, the object's class could actually be the base class or any one of its subclasses – This makes your code easier for you to write and easier for others to understand 15
  • 16. Benefits of Polymorphism ● Extensibility – Other subclasses could be added later to the family of types, and objects of those new subclasses would also work with the existing code 16
  • 18. 3 Forms of Polymorphism in Java program ● Method overriding – Methods of a subclass override the methods of a superclass ● Method overriding (implementation) of the abstract methods – Methods of a subclass implement the abstract methods of an abstract class ● Method overriding (implementation) through the Java interface – Methods of a concrete class implement the methods of the interface 18