본문 바로가기

자바의 정석 정리

자바의 정석 - 6.7 오버로딩

6.7.1 오버로딩

  • 이름이 같은 메서드를 사용하고 싶을 때, 매개변수를 달리하여 선언 할 수 있다.

6.7.2 오버로딩 조건

  1. 메서드의 이름이 같아야 한다.
  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;
    }
}