Polymorphism means many forms. In Java, two ways to achieve polymorphism are:

  • Method overloading (compile-time polymorphism)
  • Method overriding (runtime polymorphism)

Method overloading

Method overloading is to create multiple methods with the same name but different parameters. Depends on the parameters passed into the method, the right method is call.

Example:

The two multiply methods below have the same name “multiply” but different number of parameters. Which method is called depends on the number of parameters passed in.

class Utils {
	public static int multiply(int a, int b) {
		return a * b;
	}

	public static int multiply(int a, int b, int c) {
		return a * b * c;
	}
}

public class Utility {

	public static void main(String[] args) {

		System.out.println(Utils.multiply(4, 5));
		System.out.println(Utils.multiply(4, 5, 6));

	}

}

The result is below:

Method overriding

Each subclass can override the same method in the super class with its own implementation. In the example below, different animal sounds differently.

class Animal {

	public void says() {
		System.out.println("What does the animal say?");
	}

}

class Cow extends Animal {

	public void says() {
		System.out.println("The cow says: Moo-Moo");
	}

}

class Pig extends Animal {

	public void says() {
		System.out.println("The pig says: Oink-Oink");
	}

}

class Main {
	public static void main(String[] args) {

		Animal animal = new Animal();
		animal.says();
		
		animal = new Cow();
		animal.says();
		
		animal = new Pig();
		animal.says();

	}
}

As a result, depends on which object it is, the says method behaves differently. The result is below: