Ad-hoc polymorphism allows functions to be defined with different behaviors for different types. This can be achieved through function overloading or operator overloading.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Solution {
    public void print(int a) {
        System.out.println("Printing int: " + a);
    }

    public void print(String a) {
        System.out.println("Printing String: " + a);
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.print(10);       // Output: Printing int: 10
        solution.print("Hello");  // Output: Printing String: Hello
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
In Python:
class Solution:
    def print(self, a):
        if isinstance(a, int):
            print(f"Printing int: {a}")
        elif isinstance(a, str):
            print(f"Printing String: {a}")

# Example usage
sol = Solution()
sol.print(10)  # Output: Printing int: 10
sol.print("Hello")  # Output: Printing String: Hello