Code Example 2: static polymorphism

This Java program also demonstrates static polymorphism through method overloading. The StaticPolymorphism class has two print methods, one that takes a single string parameter prename and another that takes two string parameters prename and name.

When the main method is called, two calls are made to the print method, one with a single argument and the other with two arguments. The first call to obj.print("John") will call the print method that takes a single string parameter, and the second call to obj.print("John", "Smith") will call the print method that takes two string parameters.

Since the print methods are private, they cannot be accessed from outside the StaticPolymorphism class. This means that other classes cannot call these methods directly, and can only access them through public methods in the StaticPolymorphism class.

public class StaticPolymorphism {
	private void print(String prename) {
		System.out.println("Hello " + prename);
	}

	private void print(String prename, String name) {
		System.out.println("Hello " + prename + " " + name);
	}

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

		obj.print("John");
		obj.print("John", "Smith");
	}
}
Output
Hello John
Hello John Smith