고래씌

[JAVA] 7-3. 메소드(Method) 본문

JAVA/JAVA 기초

[JAVA] 7-3. 메소드(Method)

고래씌 2023. 10. 12. 17:30

1. 메소드

[표현법]
접근제한자 [예약어] 반환할 값의 자료형 메소드명 ([매개변수]) {
         수행할코드
         
         return 반환할 값; (반환형이 void일 경우 생략 가능)
}
=> 한번 정의하면 내가 원하는 만큼 호출해서 재사용할 수 있다.

package com.kh.chap06_method.controller;

public class MethodTest1 {

	
	// 1. 매개변수가 없고 반환값도 없는 메소드
	public void method1() {
		System.out.println("매개변수와 반환값이 둘다 없는 메소드입니다.");
		
//		return;  // JVM이 자동으로 생성해줌
	}
	
	// 2. 매개변수가 없고, 반환값은 있는 메소드
	public int method2() {
		System.out.println("매개변수가 없고 반환값은 있는 메소드입니다.");
		
		return 1;
	}
	
	// 3. 매개변수가 있고, 반환값은 없는 메소드
	public void method3(int num1, int num2) {
		System.out.println("매개변수가 있고, 반환값은 없는 메소드입니다.");
		
		// num1과 num2의 값을 비교하여, 결과를 출력하는 메소드
		// 더 큰값 : xx
		// 더 작은 값 : xx
		
		int min = num1;
		int max = num2;
		
		if(num1 > num2) {
			min = num2;
			max = num1;
		}
		
		System.out.println("더큰값 : " +max);
		System.out.println("더작은값 : " +min);
	}
	
	// 4. 매개변수도 있고, 반환값도 있는 메소드
	public int method4(int a, int b) {
		System.out.println("매개변수? 있습니다. 반환값도 있습니다.");
		
		return a*b;
	}
}
package com.kh.chap06_method.run;

import com.kh.chap06_method.controller.MethodTest1;

public class Run {

	public static void main(String[] args) {
		MethodTest1 mt1 = new MethodTest1();
		mt1.method1();
		mt1.method2();  // 1의 값이 저장됨
		System.out.println(mt1.method2()); // 1의 값 출력
		
		mt1.method3(1,2); 
		
		int result = mt1.method4(2, 10);
		System.out.println(result);
		
	}
}

2. static 메소드

[표현법]
접근제한자 static 예약어 반환형 메소드명([매개변수]) {
      수행할코드
      return 반환값;
}
 
- 호출시 객체 생성할 필요가 없음
- 프로그램 시작시에 정적메모리 영역에 메소드가 저장되어 있기 때문
- 클래스명메소드명(전달값);으로 호출이 가능
- 예약어, 매개변수, return은 생략 가능
 

package com.kh.chap06_method.controller;

public class MethodTest2 {
	
	public static int count = 100;
	int count2 = 100;
	
	public static void method1() {
		System.out.println("매개변수 x, 반환값 x");
	}
	
	public static String method2() {
		return "매개변수는 없고요, 반환값은 있습니다";
	}
	
	public static void method3(String name, int age) {
		System.out.println(name +"님은 "+age+"살 입니다.");
	}
	
	// static 메소드 내부에서는 static 필드만 쓸 수 있다!
	public static int method4(int num1) {
		
		/*
		 * static 메소드 안에서는 static이 아닌 필드는 접근이 불가능하다.
		 * static 메소드는 프로그램 시작시 정적메모리영역에 들어가는데
		 * 이때, static으로 선언된 필드도 함께 같은 메모리 영역에 생성되므로 가능하다.
		 * 하지만, static이 아닌 일반 필드는, static 메소드 및 변수들과 생성시점이 다르기때문에
		 * 같은 영역안에서 사용이 불가능하다.
		 * 
		 * 즉, static메소드 안에는 static 필드만 사용이 가능하다.
		 */
		
		
		return num1 * count;
//		reutrn num1 * count2; (X)  // 
	}

}

☞ (method4)
static 메소드 안에서는 static이 아닌 필드는 접근이 불가능!!!
    static 메소드는 프로그램 시작시 정적메모리영역에 들어가는데
   이때, static으로 선언된 필드도 함께 같은 메모리 영역에 생성되므로 가능하다.
   하지만, static이 아닌 일반 필드는, static 메소드 및 변수들과 생성시점이 다르기때문에 같은 영역안에서 사용이 불가능하다.

☞  즉, static메소드 안에는 static 필드만 사용이 가능하다.

package com.kh.chap06_method.run;

import com.kh.chap06_method.controller.*;

public class Run {

	public static void main(String[] args) {
		MethodTest1 mt1 = new MethodTest1();
//		mt1.method1();
//		mt1.method2();  // 1의 값이 저장됨
//		System.out.println(mt1.method2()); // 1의 값 출력
//		
//		mt1.method3(1,2); 
//		
//		int result = mt1.method4(2, 10);
//		System.out.println(result);
		
//		MethodTest2.count;
		MethodTest2.method1();   // 매개변수 x, 반환값 x
		
		
		System.out.println(MethodTest2.method4(1) ); // 100
		
	}
}

 

'JAVA > JAVA 기초' 카테고리의 다른 글

[JAVA] 8. 객체 배열 & 실습문제  (0) 2023.10.13
[JAVA] 7-4. 오버로딩 & 클래스 실습문제  (0) 2023.10.13
[JAVA] 7-2. 생성자  (0) 2023.10.12
[JAVA] 7-1. 클래스(Class)  (0) 2023.10.12
[JAVA] 배열까지 종합문제  (0) 2023.10.12