1_메서드 오버로딩
메서드의 이름이 같고 매개변수가 다른 메서드를 여러개 정의하는 것을 메서드 오버로딩이라 한다.
예) add( int a, int b) / add( double a, double b)
2_오버로딩 규칙
메서드의 이름이 같아도 메개변수의 타입과 순서가 다르면 오버로딩을 할 수 있다. 단, 반환 타입은 인정하지 않는다.
예) int add( int a. int b) / int add( int c, int d) / double add( int a, int b)
3_메서드 시그니처 = 메서드 이름 + 매개변수 타입(순서)
package method;
public class OverLoding1 {
public static void main(String[] args) {
System.out.println("1: " + add(1,2));
System.out.println("2: " + add(1,2,3));
// 1번 호출
// 1: 3
// 2번 호출
// 2: 6
}
public static int add(int a, int b) {
System.out.println("1번 호출");
return a+b;
}
public static int add(int a, int b ,int c) {
System.out.println("2번 호출");
return a+b+c;
}
}
*매개변수 타입이 다른 경우
package method;
public class OverLoding2 {
public static void main(String[] args) {
myMethod(1,1.2);
myMethod(1.2,1);
// int a, double b
// double a, int b
}
public static void myMethod(int a, double b) {
System.out.println("int a, double b");
}
public static void myMethod(double a, int b) {
System.out.println("double a, int b");
}
}
package method;
public class OverLoding3 {
public static void main(String[] args) {
System.out.println("1: " + add(1,2));
System.out.println("1: " + add(1.2,1.5));
// 1번 호출
// 1: 3
// 2번 호출
// 1: 2.7
}
public static int add(int a, int b) {
System.out.println("1번 호출");
return a+b;
}
public static double add(double a, double b) {
System.out.println("2번 호출");
return a+b;
}
}
'백엔드 > Java' 카테고리의 다른 글
[Java]#18 Method와 형변환 (0) | 2023.12.20 |
---|---|
[Java]#17 Method 호출과 값 전달 (1) | 2023.12.20 |
[Java]#16 Method 반환 타입 (0) | 2023.12.20 |
[Java]#15 Method (0) | 2023.12.20 |
[Java]#14 향상된 For (0) | 2023.12.18 |