static 이란?

: 주로 클래스 변수나 메소드에 사용되어 클래스 로드 시에 메모리에 할당되며, 프로그램 종료 시까지 유지되는 키워드
→ 즉, static 키워드를 사용하면 자바는 메모리 할당을 딱 한번만 하게 되어 메모리를 적게 사용할 수 있고, 모든 인스턴스는 값을 공유한다 !
main 메소드에서의 static
public class Static {
int instanceValue = 10;
static int staticValue = 20;
public static void main(String[] args) {
System.out.println(instanceValue); // 오류
System.out.println(staticValue);
}
}
- 같은 클래스 안에 있어도 instanceValue 변수를 사용할 수 없다.
- main은 static한 메소드이므로 static 하지 않은 필드를 사용할 수 없다.
- static한 필드나 메소드는 클래스가 인스턴스화 되지 않아도 사용할 수 있다.
static한 변수는 공유된다
class StaticExam{
static int staticValue;
int instanceValue;
}
public class Static {
public static void main(String[] args) {
StaticExam v1 = new StaticExam();
StaticExam v2= new StaticExam();
v1.instanceValue = 10;
v2.instanceValue = 20;
System.out.println(v1.instanceValue); // 10
System.out.println(v2.instanceValue); // 20
v1.staticValue = 10;
v2.staticValue = 20;
System.out.println(v1.staticValue); // 20
System.out.println(v2.staticValue); // 20
}
}
→ static으로 설정하면 같은 메모리 주소만을 바라본다.
그러므로 인스턴스가 여러개 생성되어도 static 변수의 값은 공유된다.!
📌 아래는 static을 활용한 싱글톤 패턴에 대한 예제이다 !
class Singleton {
private static Singleton one;
private Singleton() {
}
public static Singleton getInstance() {
if(one==null) {
one = new Singleton();
}
return one;
}
}
public class Sample {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2); // true 출력
}
}
1. Singleton 클래스에 one이라는 static 변수 선언
2. getInstance 메서드에서 one값이 null인 경우 객체 생성
3. 다시 getInstance 메서드가 호출되면 이미 만들어진 싱글톤 객체인 one을 리턴 → 결과적으로 singleton1 과 singleton2 는 같은 객체임을 확인 !
reference
서적 |이것이 자바다