자바에서는 같은 이름의 메소드가 여러 개 존재할 수 있다. 이를 메소드 오버로딩 이라고 한다.
메소드 오버로딩을 할경우 매개 변수는 같은 이름이라도 각각 달라야 한다.
1번 예제
package ex04;
public class MyMath {
//오버로딩
int add(int x, int y) {
return x + y;
}
int add(int x, int y, int z) {
return x + y + z;
}
int add(int x, int y, int z, int w) {
return x + y + z + w;
}
public static void main(String[] args) {
MyMath obj;
obj = new MyMath();
System.out.print(obj.add(10, 20) + " ");
System.out.print(obj.add(10, 20, 30) + " ");
System.out.print(obj.add(10, 20, 30, 40) + " ");
}
}
//30 60 100
<aside> 💡 메서드의 반환형이 다르다고 해서 중복할 수 없음 반드시 매개 변수가 달라야함
</aside>