Several methods can share a name if their parameters differ. Java picks the right one from the arguments you pass.
Java · beginner · 6 min · 11 steps · free
public class OverloadingDemo {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
int two = add(1, 1);
double half = add(0.25, 0.25);
int three = add(1, 1, 1);
System.out.println(two + " " + half + " " + three);
}
}add() has finished, so its variables are gone.two.add() has finished, so its variables are gone.half.add() has finished, so its variables are gone.three.2 0.5 3.int f(int x) and double f(int x) both exist?Answer: No: only the return type differs. The parameters must differ.
print(5) with print(int) and print(double) available calls?Answer: print(int). The exact match wins.
← Methods: Define, Call and Return · Pass by Value: Primitives vs References →