위로 아래

메서드의 구조

메서드의 구조

public static int sum (int1, int2)

public -> 접근 지정자 : 메서드의 특징. 컴파일러에 메서드의 접근 범위를 알려준다.

static -> 객체 생성 없이 함수 실행

int -> 리턴 반환 타입 : 반환할 리턴이 없으면 void

sum -> 메서드 이름

(int i1, int i2) -> 매개변수 목록 : 매개변수 개수만큼 자료형을 선언해주어야 한다

 

예시

import java.util.Scanner;

public class Method3Demo {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("반드시 정수를 입력하시오 연이어 두 번");
		int i1 = in.nextInt();
		int i2 = in.nextInt();
		int result = 0;
		if(i1>i2) {
			result = i1_big(i1, i2);
		} else {
			result = i2_big(i1, i2);
		}
		System.out.println("당신이 입력한 값은 "+i1+", "+i2+"이고\n두 수 사이의 차는 "+result+"이다.");
	}

	
	static int i1_big(int i1, int i2) {
		return i1-i2;
	}
	static int i2_big(int i1, int i2) {
		return i2-i1;
	}
}

 

메서드의 종류

값 전달 (call by value) : 인숫값의 복사본을 매개변수로 전달하는 방식.

 

메서드 시그니처 : 메서드 이름, 매개변수 개수, 매개변수 순서, 매개변수 타입

 

 

메서드 오버로딩

메서드 이름은 같은데, 매개변수의 개수나 타입이 다른 경우. (메서드 시그니처 중 메서드 이름만 같은 메서드.)

객체지향 중 다형성에 포함된다.

중요하다. 자주 쓰인다.

public class OverloadDemo {
	public static void main(String[] args) {
		int i1 = 3, i2 = 7, i3 = 10;
		double d1 = 7.0, d2 = 3.0;
		short s1 = 3, s2 = 7;   // short는 int 계열이라 int 대신 넣어도 먹는다
		float f1 = 7.0f, f2 = 3.0f;   // float은 double 계열이라 double 대신 넣어도 먹는다
		
		System.out.printf("%d\n",max(i1, i2));   // 결과 7
		System.out.printf("%d\n",max(s1, s2));   // 결과 7
		System.out.printf("%.1f\n",max(d1, d2));   // 결과 7.0
		System.out.printf("%.1f\n",max(f1, f2));   // 결과 7.0
		System.out.printf("%d\n",max(i1, i2, i3));   // 결과 10
	}
	
	public static int max(int i1, int i2) {
		int result = i1 > i2 ? i1 : i2;
		return result;
	}
	
	public static double max(double i1, double i2) {
		double result = i1 > i2 ? i1 : i2;
		return result;
	}
	
	public static int max(int i1, int i2, int i3) {
		int result = max(max(i1, i2), i3);
		return result;
	}
}