[JAVA - 점프 투 자바 #23]

스태틱

스태틱(static)은 클래스에서 공유되는 변수나 메서드를 정의할 때 사용된다. 객체 생성 없이 클래스의 메서드나 변수를 사용할 수 있다.

class HouseLee {
    String lastname = "이";
}

public class Sample {
    public static void main(String[] args) {
        HouseLee lee1 = new HouseLee();
        HouseLee lee2 = new HouseLee();
    }
}

HouseLee 클래스를 만들고 객체를 생성하면 객체마다 객체 변수 lastname을 저장하기 위한 메모리가 별도로 할당된다.

하지만 가만히 생각해 보면 HouseLee 클래스의 lastname은 어떤 객체이든지 동일한 값인 ‘이’이어야 할 것 같지 않은가?

이렇게 항상 값이 변하지 않는다면 static을 사용해 메모리 낭비를 줄일 수 있다.

만약 변경되지 않기를 바란다면 static 키워드 앞에 final을 붙이면 된다.

class HouseLee {
    static String lastname = "이";
}

public class Sample {
    public static void main(String[] args) {
        HouseLee lee1 = new HouseLee();
        HouseLee lee2 = new HouseLee();
    }
}

static를 사용하는 이유는 값을 공유할 수 있기 때문이다.

class Counter  {
    int count = 0;
    Counter() {
        this.count++;
        System.out.println(this.count);
    }
}

public class Sample {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
    }
}

이렇게 하면 서로 다른 메모리를 같고 있기 때문에 증가된 값이 나오진 않는다.

class Counter  {
    static int count = 0;
    Counter() {
        count++;  // count는 더이상 객체변수가 아니므로 this를 제거하는 것이 좋다.
        System.out.println(count);  // this 제거
    }
}

public class Sample {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
    }
}

static 메서드

메서드 앞에 static키워드를 붙이면 Util.getCurrentDate(“yyyyMMdd”)와 같이 객체 생성 없이도 클래스를 통해 메서드를 직접 호출할 수 있다.

import java.text.SimpleDateFormat;
import java.util.Date;

class Util {
    public static String getCurrentDate(String fmt) {
        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
        return sdf.format(new Date());
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Util.getCurrentDate("yyyyMMdd"));  // 오늘 날짜 출력
    }
}

싱글톤 패턴

Singleton 클래스에 one이라는 static 변수를 작성하고, getInstance 메서드에서 one값이 null인 경우에만 객체를 생성하도록 하여 one 객체가 딱 한 번만 만들어지도록 했다.

처음 getInstance가 호출되면 one이 null이므로 new에 의해서 one 객체가 생성된다. 이렇게 한 번 생성되면 one은 static 변수이기 때문에 그 이후로는 null이 아니다. 이어서 다시 getInstance 메서드가 호출되면 이미 만들어진 싱글톤 객체인 one을 항상 리턴한다.

main 메서드에서 getInstance를 두 번 호출하여 각각 얻은 객체가 같은 객체인지 조사해 보았다. 프로그램을 실행하면 예상대로 true가 출력되어 같은 객체임을 확인할 수 있다.
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 출력
    }
}

카테고리: ,

태그:

업데이트: