Open In App

Polymorphism in Java

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The word ‘polymorphism’ means ‘having many forms’. In simple words, we can define Java Polymorphism as the ability of a message to be displayed in more than one form. In this article, we will learn what is polymorphism and its type.

Real-life Illustration of Polymorphism in Java: A person can have different characteristics at the same time. Like a man at the same time is a father, a husband, and an employee. So the same person possesses different behaviors in different situations. This is called polymorphism. 

What is Polymorphism in Java?

Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.

Polymorphism enables Java developers to create more flexible and reusable code. Understanding when and how to use it can make your code more maintainable. The Java Programming Course offers practical examples and projects that showcase the power of polymorphism in real-world applications.

Types of Java Polymorphism

In Java Polymorphism is mainly divided into two types: 

  • Compile-time Polymorphism
  • Runtime Polymorphism

Compile-Time Polymorphism in Java

It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. 

Note: But Java doesn’t support the Operator Overloading.

Java Polymorphism

Method Overloading

When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments.

Example 1:

Java
// Java Program for Method overloading
// By using Different Types of Arguments 

// Class 1
// Helper class
class Helper {

    // Method with 2 integer parameters
    static int Multiply(int a, int b)
    {
        // Returns product of integer numbers
        return a * b;
    }

    // Method 2
    // With same name but with 2 double parameters
    static double Multiply(double a, double b)
    {
        // Returns product of double numbers
        return a * b;
    }
}

// Class 2
// Main class
class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Calling method by passing
        // input as in arguments
        System.out.println(Helper.Multiply(2, 4));
        System.out.println(Helper.Multiply(5.5, 6.3));
    }
}

Output
8
34.65

Example 2:

Java
// Java program for Method Overloading
// by Using Different Numbers of Arguments

// Class 1
// Helper class
class Helper {

    // Method 1
    // Multiplication of 2 numbers
    static int Multiply(int a, int b)
    {

        // Return product
        return a * b;
    }

    // Method 2
    // // Multiplication of 3 numbers
    static int Multiply(int a, int b, int c)
    {

        // Return product
        return a * b * c;
    }
}

// Class 2
// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Calling method by passing
        // input as in arguments
        System.out.println(Helper.Multiply(2, 4));
        System.out.println(Helper.Multiply(2, 7, 3));
    }
}

Output
8
42

Subtypes of Compile-time Polymorphism

1. Function Overloading

It is a feature in C++ where multiple functions can have the same name but with different parameter lists. The compiler will decide which function to call based on the number and types of arguments passed to the function.

2. Operator Overloading

It is a feature in C++ where the operators such as +, -, *, etc. can be given additional meanings when applied to user-defined data types.

3. Template

it is a powerful feature in C++ that allows us to write generic functions and classes. A template is a blueprint for creating a family of functions or classes.

Runtime Polymorphism in Java

It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

Example

Java
// Java Program for Method Overriding

// Class 1
// Helper class
class Parent {

    // Method of parent class
    void Print()
    {

        // Print statement
        System.out.println("parent class");
    }
}

// Class 2
// Helper class
class subclass1 extends Parent {

    // Method
    void Print() { System.out.println("subclass1"); }
}

// Class 3
// Helper class
class subclass2 extends Parent {

    // Method
    void Print()
    {

        // Print statement
        System.out.println("subclass2");
    }
}

// Class 4
// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Creating object of class 1
        Parent a;

        // Now we will be calling print methods
        // inside main() method

        a = new subclass1();
        a.Print();

        a = new subclass2();
        a.Print();
    }
}

Output
subclass1
subclass2

Explanation of the above code:

Here in this program, When an object of a child class is created, then the method inside the child class is called. This is because The method in the parent class is overridden by the child class. Since The method is overridden, This method has more priority than the parent method inside the child class. So, the body inside the child class is executed.

Subtype of Run-time Polymorphism

i. Virtual functions

It allows an object of a derived class to behave as if it were an object of the base class. The derived class can override the virtual function of the base class to provide its own implementation. The function call is resolved at runtime, depending on the actual type of the object.

Diagram – 

Types of Polymorphism in Java

Polymorphism in Java is a concept that allows objects of different classes to be treated as objects of a common class. It enables objects to behave differently based on their specific class type.

Advantages of Polymorphism in Java

  1. Increases code reusability by allowing objects of different classes to be treated as objects of a common class.
  2. Improves readability and maintainability of code by reducing the amount of code that needs to be written and maintained.
  3. Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual class of the object.
  4. Enables objects to be treated as a single type, making it easier to write generic code that can handle objects of different types.

Disadvantages of Polymorphism in Java

  1. Can make it more difficult to understand the behavior of an object, especially if the code is complex.
  2. This may lead to performance issues, as polymorphic behavior may require additional computations at runtime.


Previous Article
Next Article

Similar Reads

Interfaces and Polymorphism in Java
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help
6 min read
Variables in Java Do Not Follow Polymorphism and Overriding
Variables in Java do not follow polymorphism. Overriding is only applicable to methods but not to variables. In Java, if the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. This concept is known as Variable Hiding. In the case of method over
2 min read
Output of Java program | Set 25 (Polymorphism)
Pre-requisite: Polymorphism in java 1) What is the output of the following program? class GFG { protected void getData() { System.out.println("Inside GFG"); } } class GeeksforGeeks extends GFG { protected void getData() { System.out.println("Inside GeeksforGeeks"); } } public class Test { public static void main(String[] args) {
3 min read
Compile Time Polymorphism in Java
Polymorphism in Java refers to an object's capacity to take several forms. Polymorphism allows us to perform the same action in multiple ways in Java. Polymorphism is divided into two types: Compile-time polymorphismRun time polymorphismNote: Run time polymorphism is implemented through Method overriding. Whereas Compile Time polymorphism is implem
7 min read
Difference between Compile-time and Run-time Polymorphism in Java
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. In this article, we will see the difference between two types of polymorphisms, compile time and run time. Compile Time Polymorphism: Whenever an object is bound with its functionality at the
3 min read
Dynamic Method Dispatch or Runtime Polymorphism in Java
Prerequisite: Overriding in java, Inheritance Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. When an overridden method is called through a superclass reference, Java determines which
5 min read
Understanding Encapsulation, Inheritance, Polymorphism, Abstraction in OOPs
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of t
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Java.math.BigInteger.modInverse() method in Java
Prerequisite : BigInteger Basics The modInverse() method returns modular multiplicative inverse of this, mod m. This method throws an ArithmeticException if m <= 0 or this has no multiplicative inverse mod m (i.e., gcd(this, m) != 1). Syntax: public BigInteger modInverse(BigInteger m) Parameters: m - the modulus. Return Value: This method return
2 min read
Java.math.BigInteger.probablePrime() method in Java
Prerequisite : BigInteger Basics The probablePrime() method will return a Biginteger of bitLength bits which is prime. bitLength is provided as parameter to method probablePrime() and method will return a prime BigInteger of bitLength bits. The probability that a BigInteger returned by this method is composite and does not exceed 2^-100. Syntax: pu
2 min read
Java | How to start learning Java
Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg