스태틱(static)은 클래스에서 공유되는 변수나 메서드를 정의할 때 사용
class HouseMoon {
static String lastName = "문";
}
public class Sample {
public static void main(String[] args) {
HouseMoon moon1 = new HouseMoon();
HouseMoon moon2 = new HouseMoon();
}
}
lastName 필드는 어떤 객체이든지 동일한 값인 '문'이다.
항상 값이 변하지 않는다면 static을 사용해 메모리 낭비를 줄일 수 있다.
static 키워드를 붙이면 자바는 메모리 할당을 딱 한 번만 하게돼 메모리를 적게 사용할 수 있음.
lastName값이 변경되지 않기를 바란다면 final static 키워드를 사용.
자바에서는 상수를 의미한다.
static을 사용하는 또 다른 이유는 값을 공유할 수 있기 때문. static으로 설정하면 같은 메모리 주소만을 바라보기에 static 변수의 값을 공유하게 된다.
class Counter {
static int count = 0;
Couter() {
count++;
System.out.println(count);
}
}
public class Sample {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
}
}
1
2
static 키워드를 붙였더니 count 값이 공유되어 count가 증가되어 출력
static 키워드가 메서드 앞에 붙으면 static 메서드가 됨.
class Counter {
static int count = 0;
public static int getCount() {
return count;
}
}
public class Sample {
System.out.println(Counter.getCount()); // 스태틱 메서드는 클래스를 이용하여 호출
}
메서드 앞에 static 키워드를 붙이면 Counter.getCount()와 같이 객체 생성 없이도 클래스를 통해 메서드를 직접 호출 가능.
static method 안에서는 인스턴스 변수 접근 불가능.
위의 코드는 클래스 변수이기에 static method에서 접근이 가능했다.
자바의 디자인 패턴 중 하나인 싱글톤(singleton).
싱글톤은 단 하나의 객체만을 생성하게 강제하는 디자인 패턴
다시 말해, 클래스를 통해 생성할 수 있는 객체가 한 개만 되도록 만드는 것
디자인 패턴은 소프트웨어 설계에서 반복적으로 나타나는 문제들을 효과적으로 해결하는 데 사용되는 검증된 설계 방법론
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(Stirng[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2); // true
}
}
Singleton 클래스에 one이라는 static 변수를 작성하고, getInstance() 메서드에서 one값이 null인 경우에만 객체를 생성하도록 해 one 객체가 딱 한 번만 만들어지도록 함.