본문 바로가기
프로그래밍 언어/자바의 정석 기초편

자바의 정석 기초편 ch6-30,31 오버로딩

by life grow 2022. 8. 2.

6-30 오버로딩(과적하다: 원래 쌓아야 하는 것보다 많이 쌓다.)

 

오버로딩: 한 클래스 안에 같은 이름의 메서드 여러 개 정의하는 것

 

원래 메서드 이름 1개당 메서드 1개를 만드는데

오버로딩은 메서드 이름 1개에 메서드 n개를 만들 수 있다.

보기 1,2는 단순히 메서드를 중복 정의를 한 것이다.

 

보기 3은 오버로딩이 맞다.

그러나 보기 3과 같이 메서드가 정의되었다고 치면

add(3,3)으로 호출하면 오류가 생긴다.

왜냐하면 보기 3의 두 메서드 중 어느 메서드가 호출된 것인지 알 수 없기 때문이다. 

이런 걸 ambiguous 하다. 어떤 메서드를 호출하려고 했는지 모호하다.

 

메서드: 어떤 작업을 하는 것

메서드 이름이 같다: 하는 작업이 같다

 

연산자 오버로딩: 하나의 연산자가 여러 기능을 한다.

+(덧셈기호) 1.부호, 2.덧셈, 3.문자열 결합

자바에서는 직접 연산자 오버로딩를 구현할 수 없게 만들었다.

System.out.println("mm.add(3, 3) 결과:"    + mm.add(3,3)); 

위 문장에서 println, mm.add(3,3)  둘 중 어떤 것이 먼저 호출될까?

 mm.add(3,3)가 먼저 호출된다.

그 결과를 가지고 println()이 호출된다.

 

위 문장은 두 문장을 합친거다.

int result =  mm.add(3,3);   < 이게 먼저 실행된다.
System.out.println("mm.add(3, 3) 결과:"    +result);

 

result 대신 mm.add(3,3) 메서드 호출하는 부분을 직접 넣은 것이다.

문장이 이해가지 않으면 분해해보자!

 

6-10 예제

class Ex6_10 {
	public static void main(String args[]) {
		MyMath3 mm = new MyMath3();
		System.out.println("mm.add(3, 3) 결과:"    + mm.add(3,3));
   		//int result = mm.add(3,3);
       		//System.out.println("mm.add(3, 3) 결과:"    + result);  같다고 생각하면 된다.
        	//println()괄호 안이(mm.add()메서드가) 먼저 호출되고 그 다음 println() 메서드가 호출된다.
		System.out.println("mm.add(3L, 3) 결과: "  + mm.add(3L,3));
		System.out.println("mm.add(3, 3L) 결과: "  + mm.add(3,3L));
		System.out.println("mm.add(3L, 3L) 결과: " + mm.add(3L,3L));

		int[] a = {100, 200, 300};
		System.out.println("mm.add(a) 결과: " + mm.add(a));
   }
}

class MyMath3 {
	int add(int a, int b) {
		System.out.print("int add(int a, int b) - ");
		return a+b;
	}
	
	long add(int a, long b) {
		System.out.print("long add(int a, long b) - ");
		return a+b;
	}
	
	long add(long a, int b) {
		System.out.print("long add(long a, int b) - ");
		return a+b;
	}

	long add(long a, long b) {
		System.out.print("long add(long a, long b) - ");
		return a+b;
	}

	int add(int[] a) {		// 배열의 모든 요소의 합을 결과로 돌려준다.
		System.out.print("int add(int[] a) - ");
		int result = 0;
		for(int i=0; i < a.length;i++) 
			result += a[i];
		
		return result;
	}
}
결과
int add(int a, int b) - mm.add(3, 3) 결과:6
long add(long a, int b) - mm.add(3L, 3) 결과:6
int add(int a, long b) - mm.add(3, 3L) 결과:6
long add(long a, long b) - mm.add(3L, 3L) 결과:6
int add(int[] a) - mm.add(a) 결과: 600

/*여기서 만약 int add(int a, int b) {}메서드가 없다면
System.out.println("mm.add(3, 3) 결과:"    + mm.add(3,3));이 
long add(int a, long b) {} 호출하는 것인지
long add(long a, long b) {}을 호출하는 것인지
확실하지 않다.*/