자바 공부 25 : 스태틱

친환경 개발자
|2024. 2. 26. 18:55

static 키워드란?

  • 클래스에서 공유되는 변수나 메서드를 정의할 때 사용하는 키워드
  • 클래스의 인스턴스를 생성하지 않고도 클래스 자체에서 접근할 수 있도록 함
  • 값을 공유할 수 있다.
  • 메모리 할당을 최소화

 

static 변수

  • 클래스영역에서 static키워드 사용 변수 선언
  • 해당 클래스의 모든 객체가 해당 static 변수를 공유하게 됨
class HouseLee{
    static String lastname = "이";     → static 변수 선언
}

public class House {
    public static void main(String[] args) {
        HouseLee lee1 = new HouseLee();      
        HouseLee lee2 = new HouseLee();     → 객체 lee1, lee2 모두 lastname으로 "이"를 갖게됨
    }
}

 

static 메서드

  • 메서드 앞 static 키워드를 붙여 생성
  • 객체 생성 없이도 클래스를 통해 메서드 직접 호출 가능
  • 유틸리티성 메서드 작성에 많이 사용

 

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 Sample {
    public static void main(String[] args) {

        System.out.println(Util.getCurrentDate("yyyyMMdd"));      →오늘 날짜 출력

    }
}

 

 

 

싱글톤 패턴

  •  소프트웨어의 디자인 패턴 중 하나
  •  클래스가 단 하나의 객체만을 생성하도록  만드는 패턴
  •  클래스의 인스턴스가 한 번만 생성되고, 그 이후에는 이미 생성된 인스턴스르 반환
  •  프로그램의 오류 확률을 줄일 수 있다.
class Singleton {
    public static Singleton one;    → singleton클래스에 one이라는 static변수 작성
    private Singleton() {      → new 객체 생성을 막기 위해 생성자 private 만듦
    }

    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();     →one값이 null이므로 객체 생성
        Singleton singleton2 = Singleton.getInstance();     →one객체가 이미 생성되었으므로 one값 리턴
        System.out.println(singleton1 == singleton2);     →true 출력
    }
}