Java

[JAVA] 오버로딩(Overloading)이란?

YEJI ⍢ 2022. 12. 27. 01:56
728x90

오버로딩(Overloading)이란?

동일 클래스(class)에서 동일한 이름의 메소드(method)를 여러 개 정의할 수 있음을 의미합니다.

 

물론 조건이 존재합니다.

 

매개변수(parameter)의 개수나 타입이 달라야 합니다.

(Different signature)

 

 

 

예제를 살펴봅시다.


public class main {
	public static void main(String[] args) {
		int n1 = 2;
		int n2 = 100;
		double f1 = 2.0;
		double f2 = 100.0;
		String s1 = "Hello ";
		String s2 = "World!";	
		
		int result_1 = adder(n1, n2);
		double result_2 = adder(f1, f2);
		String result_3 = adder(s1, s2);
		
		System.out.println("Result_1: " + result_1);
		System.out.println("Result_2: " + result_2);
		System.out.println("Result_3: " + result_3);
	}
	
	private static int adder(int a, int b) {
		return a+b;
	}
	
	private static double adder(double a, double b) {
		return a+b;
	}
	private static String adder(String a, String b) {
		return a+b;
	}
}

같은 이름의 함수가 여러 개 선언되어도 error가 뜨지 않고 결과가 잘 출력될 수 있는 것을 확인할 수 있습니다.

 

 

오버로딩(overloading)된 메소드(method)를 하나씩 살펴보겠습니다.

private static int adder(int a, int b) {
    return a+b;
}

Return type: int

Parameter Signature: int

 

 

private static double adder(double a, double b) {
    return a+b;
}

Return type: double

Parameter Signature: double

 

 

private static String adder(String a, String b) {
    return a+b;
}

Return type: String

Parameter Signature: String

 

 

이렇게 함수의 이름이 같아도 여러개의 메소드(method)를 선언할 수 있는 이유는 different signature을 갖기 때문입니다.

 

 

 

◡̈