[java] static 변수

YulHee Kim·2021년 10월 19일
0

static 변수(클래스 변수, 정적 변수) 란?

결론적으로 모든 인스턴스가 같은 값을 공유해야 할 경우 static 변수를 사용한다.
처음 프로그램이 로드될 때 단 한번 데이터 영역에 생성된다.
인스턴스의 생성과 상관없이 사용할 수 있으므로 클래스 이름을 참조한다.

클래스 변수 vs 인스턴스 변수

클래스 변수(static 필드)는 클래스 영역에 존재한다. 객체 외부에 존재하므로 여러 객체가 공유에 좋다.
인스턴스 변수는 각 객체 내부에 존재한다.

static 변수 예제

웹 사이트 방문시마다 조회수를 증가시키는 Counter 프로그램

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

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

이 코드의 결과는 다음과 같다.

1
1

c1과 c2의 count는 서로 다른 메모리를 가리키고 있기 때문에 원하던 결과(카운트가 증가된)가 나오지 않는 것이다.

static을 사용한 예제다.

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

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

static 키워드를 통해 count 변수가 공유되고 있는 것이 보인다.
즉 static은 공유하기 위한 용도이다.

static 매소드

날짜를 구하는 Util 클래스 예

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


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

    public static void main(String[] args) {
        System.out.println(Util.getCurrentDate("yyyyMMdd"));
    }
}

Util클래스의 getCurrentDate라는 스태틱 메소드(static method)를 이용하여 오늘의 날짜를 구하는 예제다.

https://peemangit.tistory.com/396
https://wikidocs.net/228
https://cloudstudying.kr/lectures/198

profile
백엔드 개발자

0개의 댓글