4주차 - 메서드 method (2) , 스태틱 메서드 static method

2022. 9. 3. 15:16Java/java

static 메서드는 생성자를 사용하지 않아도 바로 사용이 가능하다.

 

일반적인 메서드는 인스턴스 생성후, 클래스 내부에 있는 메서드를 부른다.

이 과정에서 클래스는 heap 영역에 저장된다.

하지만 static은 따로 생성을 하지 않아도 처음부터 static 영역에 별도로 저장된다.

 

나도 아직도 모든 흐름을 완벽하게 이해한것이 아니라 설명이 빈약하지만 static 메서드는 바로 이용이 가능하다는 것만 알아두자.

 

아래는 스태틱 메서드를 만드는 예시

public class Print {
	public static void printArr() {
		System.out.println();
	}

	public static void printArr(int[] arr) {
		for (int i : arr) {
			System.out.println(i);
		}
	}
	
	public static void printArr(String[] arr) {
		for (String i : arr) {
			System.out.println(i);
		}
	}
	public static void printArr(double[] arr) {
		for (double i : arr) {
			System.out.println(i);
		}
	}
}

아래는 위에서 만든 스태틱 메서드를 이용하는 예시

public class PrintMain {
	public static void main(String[] args) {
		int[] scores = { 100, 13, 44 };
		String[] names = { "김변수", "이상수", "박참조" };
		double[] doubles = { 1.1, 2.2, 3.3 };

		Print.printArr(scores);
		Print.printArr();
		Print.printArr(names);
		Print.printArr();
		Print.printArr(doubles);
	}
}