개발/자바

Java - static 키워드

웅'jk 2023. 1. 18. 17:52

static 은 클래스 변수 나 메소드를 선언하기 위해 사용합니다.

 

여기서 클래스 변수 , 메소드는 객체들마다 동일한 값을 공유하기 위해 사용됩니다.

 

예시를 한번 들겠습니다.

 

먼저 statics,java는 다음과 같이 정의되어 있습니다.

 

public class statics {
	static int a = 10;
	
	int b ;
	
	public static void prints() {
		System.out.println(a);
		//System.out.println(b);
	}
	
	public void prints2() {
		System.out.println(a);
		System.out.println(b);
	}
}

a 변수는 클래스 변수로, b는 인스턴스 변수로 만들었습니다.

 

여기서 prints 메소드는 b를 출력할 수 없습니다. 

 

이는 클래스 변수 , 메소드가 인스턴스 변수보다 먼저 생성이 되기 때문에 프로그램에서 b는 선언이 안되었다고 인식하기 때문입니다.

 

다음으로는 statictest.java를 보겠습니다.

public class statictest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		statics test = new statics();
		
		
		test.b = 20;
		System.out.println("첫번째 실행");
		test.prints();
		test.prints2();
		
		System.out.println("두번째 실행");
		test.a = 30;
		test.prints2();
		
		statics test2 = new statics();
		System.out.println("세번째 실행");
		test2.b = 40;
		test2.prints2();
		
	}

}

 다음과 같이 간단한 실행 소스 입니다.

실행값은 다음과 같습니다.

첫번째 실행
10
10
20
두번째 실행
30
20
세번째 실행
30
40

test 에서 a 값을 30으로 설정을 한게 test2 라는 다른객체에서도 똑같이 나타내게 됩니다.

즉 a의 30 이란 값이 객체마다 공유가 된 셈이죠.

 

이런식으로 클래스 변수 나 메소드는 각 객체별로 공유 를 하기 위해 사용됩니다.