• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Introduction » What is Polymorphism in java? With Example
Next →
← Prev

What is Polymorphism in java? With Example

By Dinesh Thakur

Polymorphism is a very powerful concept that allows you to design amazingly flexible applications. The word ‘Polymorphism: is derived form two Greek words ‘poly‘ which means many and ‘morphos‘ which means forms. So, polymorphism means the ability to take many forms.

Polymorphism can be defined as a one interface muitiple methods which means that one interface can be used to perform different but related activities. In programming terms, it means the ability by which a single variable of given type can be used to reference objects of different types and to automatically call the method that is specific to the type of object the variable references. This enables a single method call to behave differently depending on the type of object to which the call applies.

We’ll be covering the following topics in this tutorial:

  • Polymorphism Explanation
  • Referencing Subclass Object using Superclass Reference Variable
  • Types of Polymorphism in Java
  • Characteristics of Polymorphism in Java
  • Runtime vs. Compile Time Polymorphism
  • The important points to remember about polymorphism

Polymorphism Explanation

In order to understand this concept, consider an example of collection of shapes in a Graphic package. Each shape in it may be completely different as eash may be of different structure and have different way of drawing such as rectangle, circle, triangle etc, If we want to draw different shapes, the same task has to be performed in principle (i.e, draw a shape) but depending on the shape, it may look very different as method for drawing each shape is different. The user’s request in everyday language to draw a shape will therefore lead to various different actions. In order to simulate this, a separate version of draw a shape needs to be implemented for every class that describes a kind of shape (derive class). The class hierarchy is as shown in the following figure.

Class HierarchyIn the above figure, draw() method is present in the base class Shape to draw any shape. As the technique for drawing different shapes is unique so we have redefined (override) the draw () method in each of the subclass. With polymorphism, whenever a user wants to draw a particular shape (say circle), it simply sends the request to the super class Shape by invoking its method draw () which in reality be calling a method draw () of the appropriate sub class so as to display the requested shape.

The advantage of polymorphism is that even for such heterogenous collection of different shapes, the general draw () method can be invoked, which automatically results in respective method being called according to the actual type of shape. In other words, user need not to be concerned about which draw () method is executed in order to fulfil its requests. In the above example, the single interface is the draw () method present in the base class Shape and different tasks are the draw () method present in the subclasses.

So, polymorphism can also be defined as the ability of an object of different classes (sub classes) to respond to the same request each in its own way.

The main benefit of polymorphism is that it reduces the complexity by allowing the same name to perform different tasks. As in the above example, same named method draw () can be used for drawing any kind of shape.

Another benefit of polymorphism is that it is possible to design and implement systems that are easily extensible. New classes can be added in the class hierarchy with little or no modification in the super class. For example, if user wishes to draw another shape Ellipse then we need to add Ellipse class in the class hierarchy and there is no need to modify any code in the super class Shape.

Before implementing polymorphism, you need to understand how superclass reference variable can refer to a subclass object.

Referencing Subclass Object using Superclass Reference Variable

As we know that in order to declare a variable that references an object, we use the following syntax.

ClassName variableName;

Here, variableName is the name of the reference variable and ClassName is the name of its class. Thus, variablename can reference any object of class ClassName. However, it can also reference any object whose class is a subclass of ClassName. For example: If a class A is a superclass of class B and class B is a superclass of class C then in that case, variable of class A can reference any object derived from that class (i.e. object of class B and class c). This is possible because each subclass object is an object of its superclass but not vice versa.

To illustrate how a superclass reference variable can refer the derive class object, let us consider the following program in which the class Derv1 and Derv2 are derived from common superclass Base. All these classes have methods with the same name and we are accessing these methods using superclass reference variable.

//Show how superclass reference variable contain subclass object

//base class

class Base {

    publicvoid display(){

        System.out.println(“Base class display method is called“);

    }

}

//derived class 1 that extends class Base

class Derv1 extends Base {

      publicvoid display(){

        System.out.println(“Derv1 class display method is called“);

     }

}

//derived class 2 that extends class Base

class Derv2 extends Base {

    publicvoid display(){

       System.out.println(“Derv2 class display method is called“);

   }

}

class PolymorphismDemo {

     publicstaticvoid main (String[] args){

        Base ptr;//Base class reference variable

       Derv1 d1 =new Derv1();

       Derv2 d2 =new Derv2();

       ptr = d1;// ptr contain reference of derv1 object

      ptr.display();

     ptr = d2; // ptr contain reference of derv2 object

     ptr.display();

}

}

Output :

Derv1 class display method is called

Derv2 class display method is called

Explanation: The output of the program reveals that the method display () of the subclasses are invoked. If the reference variable ptr of the superclass Base contains a reference to Derv1 object, the display () method for that object will be called. Similarly, if the reference variable ptr contains a reference to Derv2 object, display() method for that object will be called. This means that one method call,

ptr().display;

can call different methods depending on the momentary contents of ptr. This is how polymorphism is achieved. Notice that which overridden method will called is always determined by the type of the object referenced by the variable, not the type of the object reference variable. This task of determining which implementation of method will be used is performed by the JVM dynamically at run time. This is known as dynamic binding.

 

The polymorphic behaviour can only be achieved if the following requirements are fulfilled.

• The method call for a subclass object must be through a superclass reference variable.

• The method called must be declared in the superclass and defined in the subclass.

• The method in the superclass and subclass must have the same name and parameter list with the same number of parameters where corresponding parameters must be of the same type.

• The method return type must either be the same in the superclass and subclasses or must be covariant. Return types are said to be covariant if the return type of the method in the derived class is a subclass of the return type of the base class.

• The method access specifier must be no more restrictive in the subclass than in the superclass.

                           Visibility increases and Restriction decreases

                          ———————————————————-

                        private, none (if modifier used), protected, public

Now let us consider a practical example to understand the importance of polymorphism. Consider Rectangle and Circle be the subclasses of class Shape. Suppose we want to calculate area of any shape so we will define an area () method in the Shape class and override it in the Rectangle and Circle subclass to calculate area of rectangle and circle.

//Show how superclass reference variable contain subclass object

class Shape {

     publicvoid area(){

        System.out.println(“Base class area method is called“);

   }

}

class Rectangle extends Shape {

       privatedouble length,breadth;

       Rectangle(double x,double y){ length = x ; breadth = y ;}

       publicvoid area(){ System.out.println(“Area of Rectangle is =“+(length * breadth));}

}

class Circle extends Shape {

      privatedouble radius; Circle(double r){ radius = r }

     publicvoid area(){ System.out.println(“Area of Circle is = “+(Math.PI*radius*radius));}

}

class ShapeDemo {

    publicstaticvoid main(String[] args){

     Shape s;//Shape class reference variable

     Rectangle r =new Rectangle(10,20);

     s = r;//Assign rectangle reference to shape reference

     s.area ();

    Circle c =new Circle(5);

    s = c;//Assign circle reference to shape reference

    s.area ();

}}

Output Area of Rectangle is=200.0

Area of Circle is=78.53981633974483

Types of Polymorphism in Java

Java supports Method Overriding and Overloading are two forms of polymorphism they are as follows.

Static Polymorphism ( Compile Time Polymorphism )

Static Polymorphism (also known as Method overloading) is a way you can have multiple methods in the same class have the same name but differ in the number or types of parameters, it is known as method overloading. When an overloaded method is invoked, it can be determined as Compile time polymorphism may also be known as early or static binding to select the appropriate overloaded method based on the number of argument(s) passed and if the number of argument(s) are same then depending upon the type of argument(s) passed to the method. Thus, the key to method overloading is a method’s parameter list. A method’s return type is not enough to distinguish between two overloaded methods. if the compiler detects two methods declarations with the same name and parameter list but different return types then it will generate an error.

Implementing Compile Time Polymorphism

In the below example, two methods are defined and invoked which have the same name area () but differ only in their parameter types. For each call of the method, the compiler chooses the appropriate method by comparing the types of the arguments in the call against the parameter list of each defined method. That is the reason this is also known as compile time polymorphism.

public class Shape{
          //It could be a circle or rectangle or square
     private String type;
         //To calculate area of rectangle
     public Double area(Long length, Long breadth) {
              return (Double) length * breadth;
      }
         //To calculate area of a circle
      public Double area(Long radius) {
              return (Double) 3.14 * r * r;
      }
}

Why is this called static polymorphism?

Well that’s because When an overloaded method is invoked, it can be determined at compile time (static binding) to select the appropriate overloaded method based on the number of argument(s) passed and if the number of argument(s) are same then depending upon the type of argument(s) passed to the method.

Advantages of Static Polymorphism

1. We need to remember single name instead of multiple names of the methods that perform similar type of operations. This helps in reducing the complexity of making large programs.

2. It perform similar tasks can make complex programs more readable, understandable and easy to debug.

3. Maintainability of the program becomes easier.

4. It extensively used for handling class objects.

Dynamic Polymorphism ( Runtime Polymorphism )

Dynamic (runtime) polymorphism (also known as Method overriding) is a process in which a subclass inherits methods from a superclass at runtime,that’s why it is called runtime polymorphism. Method Overriding is one of the ways to achieve Dynamic Polymorphism.However in certain situations, the subclass need to modifY the implementation (code) of a method defined in the superclass without changing the parameter list. This is achieved by overriding or redefining the method in the subclass.

Implementing Runtime Polymorphism

To override a subclass method, we simply redefine the method in the subclass with the same name, same return type and same parameter list as its superclass counterpart. When the method with the same name exists in both the superclass as well as in the subclass, the object of the subclass will invoke the method of the subclass, not the method inherited from the base class. The following program illustrates the concept of method overriding.

class Person {
      private String name;
      private int age ;
      Person(String n,int pAge) {
         name = n; age=pAge;
      }
     public String toString() {
         return(“Name : “+ name+“\n“+ “Age : “+age+“\n“);
      }
}
class Student extends Person {
     private int rollno;
     private String stuClass ;
     private double percentage;
     Student(int rno,String n,int page,String c,double p) {
         super(n,page);
        //call superclass constructor
         rollno = rno;
         stuClass=c;
         percentage = p;
      }
       //override toString()method
      public String toString() {
           return(“Rollno : “+ rollno +“\n“+ super.toString() +“Class : “+stuClass +“\n“+“Percentage : “+percentage);
       }
}
class OverridingMethods {
      public static void main(String[] args) {
         Student s=new Student(1,“Dinesh Thakur”,35,“MCA”,90.5);
         System.out.println(s.toString());
      }
}

Advantages of Dynamic Polymorphism

• Dynamic (run time) polymorphism can support Java method overriding which is central for run-time polymorphism.

• It occurs when a subclass method and a superclass method use the same signature (name, parameter list, return type), such that the subclass method blocks out the superclass method.

• We invoke the overridden method of the superclass from the-subclass.

Characteristics of Polymorphism in Java

The Characteristics of Polymorphism that have made them so useful that they are supported in java.

Let’s discuss some of these characteristics.

Polymorphic coercion

The conversion of a data type which is carried out automatically by the compiler to prevent type errors without programmer intervention is called the implicit type conversion, that has also been defined as a form of polymorphism, referred to as “coercion polymorphism“. Below is the typical example of an integer and string concatenation.

String s =”MCQExam”=10;

Operator Overloading

Operator overloading is a type of polymorphism in which an operator having different meanings (forms) depending on the context. For example, the plus symbol (+) can represent both concatenation and addition.In any case, only argument types decide the conclued of the symbol.

String s = “10” + 10;

int total = 10 + 10;

System.out.println(“S = %s\n total = %d\n”, s, total);

Parametric polymorphism

Parametric polymorphism, allows a name of a function or a data type can be written generically in a class so that it can handle values identically without depending on their type. Such parameter or method are called generic functions and generic datatypes respectively and form the basis of generic programming.

Runtime vs. Compile Time Polymorphism

There are several fundamental differences between the two types of polymorphism:
• With compile-time polymorphism, the compiler resolves the call; in runtime polymorphism, the compiler does not get involved.  
• Compile time polymorphism is also called early or static binding; runtime  polymorphism is also called late or dynamic binding.  
• Compile time polymorphism is achieved by function and operator overloading,; in runtime, it achieved by virtual functions.  
• Compile time polymorphism is fast to execute because it already knows which method it wants at compile time; in runtime polymorphism, it is slower because it waits for the runtime to decide on the method call.  
• Compile time polymorphism is not so flexible because everything executed at compile time; in runtime polymorphism, things are more flexible because everything executed at runtime.

The important points to remember about polymorphism

• It makes an object far less complicated.  
• We can replace total implementation by reusing identical signatures.  
• As far as object handling goes, polymorphism reduces the workload.
• Java has no direct support for operator overloading.  
• Java has no support for compile-time polymorphism – I only told you about it because it is part of the concept.
• There is no role in function overloading for access modifiers or specifiers.  
• If you wish to make each function have the same number of arguments but still overload them, you need to change the argument data type.  
• If the value is being returned by a function, you do not need to catch the value when you call it.  
• A function’s return type does not have any role to play in function overloading.  
• You can only achieve function overloading by modifying the arguments. 

You’ll also like:

  1. What is Polymorphism in C#
  2. What is Polymorphism?
  3. Polymorphism in C++
  4. What is Overloading or Compile Time Polymorphism
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW