Java에서 흔하게 사용하는 System.out.println()의 오버로딩 형태를 살펴볼 수 있다. 하나의 메서드명을 이용할 수 있는 특징을 살펴볼 수 있다. 아래 코드는 java내에서 제공하는 src.zip 내에 있는 java\lang\System.java 에 존재한다.

 

System.java 내에 println() 메서드

  1.    /**
         * The "standard" output stream. This stream is already
         * open and ready to accept output data. Typically this stream
         * corresponds to display output or another output destination
         * specified by the host environment or user.
         * <p>
         * For simple stand-alone Java applications, a typical way to write
         * a line of output data is:
         * <blockquote><pre>
         *     System.out.println(data)
         * </pre></blockquote>
         * <p>
         * See the <code>println</code> methods in class <code>PrintStream</code>.
         *
         * @see     java.io.PrintStream#println()
         * @see     java.io.PrintStream#println(boolean)
         * @see     java.io.PrintStream#println(char)
         * @see     java.io.PrintStream#println(char[])
         * @see     java.io.PrintStream#println(double)
         * @see     java.io.PrintStream#println(float)
         * @see     java.io.PrintStream#println(int)
         * @see     java.io.PrintStream#println(long)
         * @see     java.io.PrintStream#println(java.lang.Object)
         * @see     java.io.PrintStream#println(java.lang.String)
         */
        public final static PrintStream out = nullPrintStream();

 

오버로딩의 조건

  1. 메서드 이름이 같아야 한다.
  2. 매개변수의 개수 또는 타입이 달라야 한다.
  3. 매개변수는 같고 리턴타입이 다른 경우는 오버로딩이 성립되지 않는다.
    (리턴타입은 오버로딩을 구현하는데 아무런 영향을 주지 못한다.)

 

오버로딩의 장점

만일 메서드도 변수처럼 단지 이름만으로 구별된다면, 한 클래스내의 모든 메서드들은 이름이 달라야 한다. 그렇다면 위에서 예로 들었던 10가지 println메서드들은 각기 다른 이름을 가져야 한다.

예를 들면, 아래와 같은 방식으로 메서드 이름이 변경되어야 할 것이다.

  1. void println()
  2. void printlnBoolean(boolean x)
  3. void printlnChar(char x)
  4. void printlnString(String x)
  5. void printlnDouble(double)

모두 근본적으로는 같은 기능을 하는 메서드들이지만, 서로 다른 이름을 가져야하기 때문에 메서드를 작성하는 쪽에서는 이름을 짓기 어렵고, 메서드를 사용하는 쪽에서는 이름을 일일이 구분해서 기억해야 하기 때문에 서로 부담이 된다. 하지만, 오버로딩을 통해 여러 메서드들이 println이라는 하나의 이름으로 정의될 수 있다면, println이라는 이름만 기억하면 되므로 기억하기도 쉽고 이름도 짧게할 수 있어서 오류의 가능성을 많이 줄일 수 있다. 그리고 메서드의 이름만 보고도 '이 메서드들은 이름이 같으니, 같은 기능을 하겠구나'라고 쉽게 예측할 수 있다.

  또 하나의 장점은 메서드의 이름을 절약할 수 있다. 하나의 이름으로 여러 개의 메서드를 정의할 수 있으니, 메서드의 이름을 짓는데 고민을 덜 수 있다.

 

 

 

이 글은 스프링노트에서 작성되었습니다.

'Java > Language' 카테고리의 다른 글

JDBC 설치 및 적용하기  (0) 2010.01.23
Form 에서 method='post'를 깜빡잊고 코딩하지 않았다면?  (0) 2009.12.23
클래스메서드(static메서드)  (0) 2009.11.25
JVM의 메모리구조  (0) 2009.11.25
JDK 7에 대해서  (0) 2009.11.16

+ Recent posts