Polymorphism in Java

Polymorphism in java is one of the fundamental features of Object-Oriented Programming (OOP). In Java Polymorphism simply means more than one form .Polymorphism allows us to perform a single action in different ways which means the same entity (method or operator or object) can perform different operations in different scenario.

Let’s understand by real life example:

Think of it as a person who can play different roles depending on the situation. For example if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person present in different-different behaviors.

Types of Polymorphism in Java

Java supports two types of polymorphism and they are as follows

  1. Compile time Polymorphism (Method Overloading)
  2. Runtime Polymorphism (Method overriding)

Compile time Polymorphism

Compile-time polymorphism in Java is when the compiler choose the correct method to use based on the method name and arguments you provide. The compiler matches the provided arguments to the correct method by considering its unique name and parameter types.

Compile time polymorphism is like choosing the right tool for a specific job before starting work. Java figures out which method to use based on the method’s name and how you want to use it (Arguments), even before running the program. It’s like planning ahead to make sure things work smoothly and efficiently.

Compile Time Polymorphism is also known as Static polymorphism, Early binding, Method overloading.

In Java, compile-time polymorphism is achieved by Method Overloading. Method overloading allows you to define multiple methods with the same name in the same class but with different parameter lists. The Java compiler determines which method to call based on the number and types of arguments passed during the method call.

Method Overloading in Java

Method Overloading is a feature in Java that allows a class to have multiple methods with the same name but different in parameters and different data types. This concept is called method overloading.

Different Ways of Method Overloading in Java

In Java, Method overloading can be performed by two ways listed below :

  • Changing the Number of Parameters.
  • Changing Data Types of the parameters.

Now, let’s have an example to understand the above ways of method overloading :

1. Changing the Number of Parameters.

Let’s illustrate method overloading with changing the number of parameters using a simple example: in given we are creating static method that we don’t need to create object for calling methods.

class Calculator {
    static int add(int a, int b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }

    static int add(int a, int b, int c, int d) {
        return a + b + c + d;
    }

    public static void main(String[] args) {
        System.out.println(add(5, 7));              // Uses the int add(int a, int b) method
        System.out.println(add(1, 2, 3));           // Uses the int add(int a, int b, int c) method
        System.out.println(add(10, 20, 30, 40));    // Uses the int add(int a, int b, int c, int d) method
    }
}

Output:

12
6
100

2. Changing Data Types of the parameters.

In this example, we are overloading the method add() based on the data type of the parameters


class Calculator {
    static int add(int a, int b) {
        return a + b;
    }

    static double add(double a, double b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }

    static double add(double a, double b, double c) {
        return a + b + c;
    }

    public static void main(String[] args) {
        System.out.println(add(5, 7));                      // Uses the int add(int a, int b) method
        System.out.println(add(3.14, 2.71));                // Uses the double add(double a, double b) method
        System.out.println(add(1, 2, 3));                   // Uses the int add(int a, int b, int c) method
        System.out.println(add(1.5, 2.5, 3.5));             // Uses the double add(double a, double b, double c) method
    }
}

Output:

12
5.85
6
7.5

Advantages of Method Overloading in Java

  • Improves code readability and maintainability.
  • Enables code reusability by avoiding duplication.
  • Provides flexibility to handle different argument types or numbers.
  • Organizes code better by grouping related methods.
  • Simplifies method selection during compilation.
  • helps developers focus on functionality, not unique names.

Rules for Method Overloading in java

  • Method Signature: Overloaded methods must have a different method signature. The method signature includes the method name and the number, order, and types of its parameters. Changing the return type alone is not sufficient for overloading. Both static and non static methods can be overloaded in java.
  • Access Modifiers: Overloaded methods can have different access modifiers (e.g., public, private, protected, or default). The access modifier is not considered part of the method signature.
  • Return Type: The return type is not part of the method signature, so changing the return type alone does not create an overloaded method. However, a method can be overloaded based on the return type combined with different parameter lists.
  • Exception Types: Overloaded methods can throw different checked or unchecked exceptions. The exception types are not considered part of the method signature for overloading.
  • static and non static methods: Both static and non static methods can be overloaded in java.
  • Method differ by static keyword: We cannot overload two methods in Java if they differ only by static keyword (the number of parameters and types of parameters is the same) it will give compile time error
  • final methods: Methods declared with final keyword can also be overloaded in java.
  • Overloading Constructors: In addition to regular methods, constructors can also be overloaded in Java.

Run Time Polymorphism in Java

In Runtime polymorphism JVM( Java virtual machine) decides the appropriate version of the method based on the actual type of the object at runtime. Here, Java compiler does not understand which method is called at compilation time as it depends on the actual type of the object created during runtime. Only JVM decides which method is called at run-time.

Runtime polymorphism in Java can be achieved by Method Overriding

Method Overriding in Java

In java, Declaring a method in sub Class which is already present in Super Class is known as method overriding. Sub class must have a method with the same name, parameter list, and return type as a method in its parent class.

let’s see the sample code below to make it more clear 

class Mobile {
    void displayInfo() {
        System.out.println("General mobile information");
    }
}

class Smartphone extends Mobile {
    @Override
    void displayInfo() {
        System.out.println("Smartphone information: Touchscreen, Apps, Internet connectivity");
    }

    void additionalFeature() {
        System.out.println("Additional feature: Face unlock and biometric authentication");
    }
}

public class Main {
    public static void main(String[] args) {
        Smartphone smartphone = new Smartphone(); // Creating a Smartphone object

        smartphone.displayInfo(); // Calls the displayInfo() method of the Smartphone class
        smartphone.additionalFeature(); // Calls the additionalFeature() method of the Smartphone class
    }
}

Output:

Smartphone information: Touchscreen, Apps, Internet connectivity
Additional feature: Face unlock and biometric authentication

Rules for Method Overriding in Java

  • The method should have the same name as the parent class method which is overriding.
  • All the parameters/arguments of the method should match. if the parent class method has two integer arguments, then the child class method should also accept two integer arguments.
  • Static, final, and private access restrict the method from overriding. This means that any parent class method which has a private access specifier or is static or final in nature cannot be overridden by any of its child classes
  • The overriding method access specifier cannot be more restrictive than the parent class access specifier. For example, if the parent method is public, then the child class cannot be default or private or protected
  • if the class is implementing another class which is abstract or implementing an interface, then the class has to override all of the functions, unless the class is an abstract class in itself.
  • The class should follow an “IS-A” relationship, . the classes should be implementing inheritance.
  • We cannot override the main method in Java because method overriding applies to instance methods, not static methods.
  • You can use the @Override annotation when overriding a method. While it is optional, using this annotation helps the compiler to ensure that you are indeed overriding a method from the parent class.
  • If the child class defines a static method with the same name and method signature as a static method in the parent class, it will not be considered method overriding. Instead, it will hide the parent class’s static method.
  • Constructors in Java are not inherited but we can call the constructor of the superclass from its subclasses. For that, we use super keyword.

Advantages of Method Overriding in Java

  • Method Overriding gives child class the ability to change the behavior of parent class method as per the requirement
  • Method Overriding provides multiple implementation of same method.
  • Method Overriding gives you ability to achieve run time polymorphism.
  • Method overriding helps in organizing code by creating a clear hierarchy of classes
  • Reduces redundant code, making the codebase easier to maintain and modify.

Leave a Reply

Your email address will not be published. Required fields are marked *