(메서드)오버로딩이란?
-> 한 클래스 내에 같은 이름의 메서드를 여러 개 정의하는 것
오버로딩의 조건
1. 메서드 이름이 같아야 한다
2. 매개변수의 개수 또는 타입이 달라야 한다.
public class Ex6_10 {
public static void main(String args[]){
//객체 생성
Mymath3 mm = new Mymath3();
System.out.println("mm.add(3, 3) 결과:" + mm.add(3,3));
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
long 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
println문이 실행이 되기전에 mm.add(3, 3)이 먼저 호출이 되어 문장이 완성된 다음 println문이 실행되기 때문에 저러한 출력이 나온다.