Static and Dynamic Polymorphism in Java Demystified

Java programming code

Static and Dynamic Polymorphism in Java Demystified

In the realm of object-oriented programming, Static Polymorphism, also known as compile-time polymorphism, is a concept where the binding of a method call to its body occurs at compile time. This process is often achieved through method overloading, a technique where multiple methods in a class have the same name but different parameters. An interesting aspect of static polymorphism is that it does not require inheritance to be implemented. However, it is generally considered slower compared to its counterpart, dynamic polymorphism.

For instance, in Java, a simple illustration of static polymorphism can be seen in method overloading within a class. Consider a class `HelloWorld` in the package `com.java4coding`. This class contains two methods named `join`, each accepting a different number of string parameters. The first `join` method takes two strings and concatenates them, while the second `join` method accepts three strings and concatenates them. This is a classic example of method overloading, demonstrating static polymorphism.

```java
package com.java4coding;

public class HelloWorld {
    String join(String a, String b) {
        return a + b;
    }

    String add(String a, String b, String c) {
        return a + b + c;
    }
}
```

Exploring Dynamic Polymorphism

Dynamic Polymorphism, on the other hand, is also referred to as runtime polymorphism. This type of polymorphism utilizes the concept of runtime binding (or late binding), where the method call is bound to the method body at runtime. Dynamic polymorphism is typically achieved through method overriding, a process where a method in a subclass has the same name, return type, and parameters as a method in its superclass. Unlike static polymorphism, dynamic polymorphism necessitates the use of inheritance. It’s noteworthy that dynamic polymorphism is faster than static polymorphism.

A classic example of dynamic polymorphism in Java can be seen with method overriding. In this example, there is a superclass named `Fruit` with a method `color` that prints out a generic message. Then, there’s a subclass `Banana` which extends `Fruit`. The `Banana` class overrides the `color` method to specifically print out “Color is Yellow”, illustrating dynamic polymorphism through method overriding.

```java
class Fruit {
    void color() {
        System.out.println("Color is...");
    }
}

class Banana extends Fruit {
    void color() {
        System.out.println("Color is Yellow");
    }
}
```

Conclusion 

In summary, while static polymorphism focuses on compile-time binding through method overloading without the need for inheritance, dynamic polymorphism relies on runtime binding through method overriding, necessitating inheritance. Both forms play a crucial role in the flexibility and reusability of code in object-oriented programming.