Code Example 1: static polymorphism

This Java program demonstrates static polymorphism through method overloading. The StaticPolymorphism class has two sum methods, one that takes two integer parameters and another that takes three integer parameters. When the main method is called, two calls are made to the sum method, one with two arguments and the other with three arguments.

Since Java supports method overloading, the compiler can determine which method to call based on the number and types of arguments passed to the method. In this case, the first call to obj.sum(1, 2, 3) will call the sum method that takes three integer parameters, and the second call to obj.sum(1, 2) will call the sum method that takes two integer parameters.

public class StaticPolymorphism {
	void sum(int a, int b) {
		System.out.println(a + b);
	}

	void sum(int a, int b, int c) {
		System.out.println(a + b + c);
	}

	public static void main(String[] args) {
		StaticPolymorphism obj = new StaticPolymorphism();

		obj.sum(1, 2, 3);
		obj.sum(1, 2);
	}
}
Output
6
3

Static Polymorphism with separated class

This Java program demonstrates static polymorphism through method overloading. The Calculate class has two sum methods that have the same name but different parameter lists. When the main method is called, an object of the Calculate class is created.

The sum method of the cal object is then called twice, once with two arguments and once with three arguments. Since the sum method is overloaded in the Calculate class, the behavior of the sum method depends on the number and types of the arguments passed to it.

When the sum method is called with two arguments, it will call the sum method that takes two arguments and print their sum to the console. When the sum method is called with three arguments, it will call the sum method that takes three arguments and print their sum to the console.

class Calculate {
	void sum(int a, int b) {
		System.out.println(a + b);
	}

	void sum(int a, int b, int c) {
		System.out.println(a + b + c);
	}
}

public class StaticPolymorphism {
	public static void main(String[] args) {
		Calculate cal = new Calculate();

		cal.sum(1, 2, 3);
		cal.sum(1, 2);
	}
}
Output
6
3