같은 이름의 메소드가 여러 개 존재할 수 있다.
1. 메소드 오버로딩 (기초)
package ex04;
public class MyMath {
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
MyMath mm = new MyMath();
int r1 = mm.add(1, 2);
System.out.println("1+2=" + r1);
}
}

2. Parameter의 개수가 다른 경우
package ex04;
public class MyMath {
int add(int a, int b) {
return a + b;
}
// 1. Parameter(매개변수)의 개수가 다르다.
int add(int a, int b, int c) {
return a + b + c;
}
// 2. Parameter(매개변수)의 개수가 다르다.
int add(int a, int b, int c, int d) {
return a + b + c + d;
}
public static void main(String[] args) {
MyMath mm = new MyMath();
int r1 = mm.add(1, 2);
System.out.println("1+2=" + r1);
int r2 = mm.add(1, 2, 3);
System.out.println("1+2+3=" + r2);
int r3 = mm.add(1, 2, 3, 4);
System.out.println("1+2+3+4=" + r3);
}
}

3. Parameter의 타입이 다른 경우
package ex04;
public class OverLoad01 {
public static void main(String[] args) {
// 2. Prameter의 타입이 다르면 오버로딩 된다.
System.out.println(1);
System.out.println(1.0);
System.out.println("문자열");
System.out.println('A');
System.out.println(true);
}
}
Share article