Java

Static

dev_zephyr 2021. 1. 27. 18:19

 

Static은 해당 메소드나 상수, 필드 등을 객체 선언 없이 사용가능하도록

메서드 메모리 영역에 등록시키는 키워드 입니다.

 

 

1. Static으로 선언된 필드, 메서드는 객체 생성 없이 다른 클래스에서 호출 가능합니다.

이때, 클래스명.필드 혹은 클래스명.메서드() 로 호출합니다.

 

class c1학년2반 {
	
	static String teacher = "김선생"; 
	
	String student;
	
	public c1학년2반(String student) {
		this.student = student;
	}
	
}

public class Static01 {
	
	public static void main(String[] args) {
		
		System.out.println(c1학년2반.teacher);

	}
	
}

 

1학년2반이라는 클래스에 선생님의 이름(필드)을 static으로 선언하였고,

Static01 클래스에서 해당 필드를 객체 선언 없이 바로 사용하는 예제입니다.

static 메서드도 동일하게 호출 가능합니다.

 

 

2. Static으로 선언된 멤버변수 클래스 변수라고 합니다.

   클래스 변수는 해당 클래스로 만들어진 객체 모두가 같은 값을 공유합니다.

  

class c1학년2반 {
	
	static String teacher = "김선생"; 
	
	String student;
	
	public c1학년2반(String student) {
		this.student = student;
	}
	
}

public class Static01 {
	
	public static void main(String[] args) {
		
		c1학년2반 test01 = new c1학년2반("태돌이");
		c1학년2반 test02 = new c1학년2반("김지미");

		System.out.println(test01.teacher); // 결과 => 김선생
		System.out.println(test02.teacher); // 결과 => 김선생
        
	}
	
	
}

test01, test02객체 모두 김선생을 호출하였는데,

이때, 어느 한 객체에서 클래스 변수의 내용을 수정하면 다른 객체들도 수정된 결과를 출력하게 됩니다.

 

class c1학년2반 {
	
	static String teacher = "김선생"; 
	
	String student;
	
	public c1학년2반(String student) {
		this.student = student;
	}
	
}

public class Static01 {
	
	public static void main(String[] args) {
		
		c1학년2반 test01 = new c1학년2반("태돌이");
		c1학년2반 test02 = new c1학년2반("김지미");

		System.out.println(test01.teacher); // 결과 => 김선생
		System.out.println(test02.teacher); // 결과 => 김선생
		
		test01.teacher = "박선생";
		
		System.out.println(test01.teacher); // 결과 => 박선생
		System.out.println(test02.teacher); // 결과 => 박선생
		
	}
	
}

 

이처럼 test01에서 변경된 값이 test02에서 호출되는 결과가 나타납니다.

 

why? 

클래스 변수(static 멤버 변수)는 클래스가 메모리에 로드될 때 한번(하나) 생성되고,

해당 클래스로 생성된 객체(인스턴스)들은 모두 한번 생성된 클래스 변수를 

함께 공유하기 때문입니다.

따라서 모든 인스턴스가 같은 값을 공유해야 하는 상황에는 static으로 변수를 선언하고,

각각 인스턴스가 다른 값을 가져야 하는 상황에는 static이 아닌 일반적인 변수로 사용해야 합니다.