6.7.1 오버로딩
- 이름이 같은 메서드를 사용하고 싶을 때, 매개변수를 달리하여 선언 할 수 있다.
6.7.2 오버로딩 조건
- 메서드의 이름이 같아야 한다.
- 매개변수 개수 또는 타입이 달라야 한다.
//타입이 같아 오버로딩이 '안되는' 예제
int add(int x, int y)
int add(int a, int b)
//반환 타입만 달라 오버로딩이 '안되는' 예제
long add(int a)
int add(int a)
//매개변수 순서가 달라 오버로딩이 '되는' 예제
long add(int a, long b)
long add(long b, int a)
6.7.3 가변인자와 오버로딩
- 가변인자 (varargs): 매개변수를 동적으로 할당 할 수 있는 인자
- 가변인자 형식 : '타입... 변수명'
public PrintStream printf(String format, Object... args){ ... }
//컴파일 에러
public PrintStream printf(Object... args, String format){ ... }
class A{
public static void main(String[] args){
String[] strArr = {"100", "200", "300"};
System.out.println(concatenate("", "100", "200", "300"));
System.out.println(concatenate("", strArr));
System.out.println(concatenate("", new String[] {"100", "200", "300"}));
System.out.println("["+concatenate("", new String[0])+"]");
System.out.println("["+concatenate("")+"]");
/*
100200300
100200300
100200300
[]
[]
*/
}
static String concatenate(String delim, String... args){
String result = "";
for(String str : args){
result += (str+delim);
}
return result;
}
}
'자바의 정석 정리' 카테고리의 다른 글
자바의 정석 - 6.9 변수의 초기화 (0) | 2022.06.10 |
---|---|
자바의 정석 - 6.8 생성자 (0) | 2022.06.10 |
자바의 정석 - 6.6 클래스와 인스턴스 (0) | 2022.06.10 |
자바의 정석 - 6.5 재귀호출 (0) | 2022.06.10 |
자바의 정석 - 6.4 JVM의 메모리 구조 (0) | 2022.06.10 |