Method overloading can be achieved in following three ways −
- By changing the number of parameters in the method.
- By changing the order of parameter types
- By changing the data types of the parameters.
See the example below−
Example
public class Tester { public static void main(String args[]) { Tester tester = new Tester(); System.out.println(tester.add(1, 2)); System.out.println(tester.add(1, 2,3)); System.out.println(tester.add(1.0f, 2,3)); System.out.println(tester.add(1, 2.0f,3)); } public int add(int a, int b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } public float add(float a, int b, int c) { return a + b + c; } public float add(int a, float b, int c) { return a + b + c; } }
Output
3 6 6.0 6.0