복습
https://shins99.tistory.com/21
[자바 기초] C R U D 의 개념
복습 https://shins99.tistory.com/20 [자바 기초] this 키워드 복습 https://shins99.tistory.com/18 [자바 기초] 접근 제어 지시자, get(), set() 메서드 복습 https://shins99.tistory.com/17 [자바 기초] 객체와 객체 간 상호작
shins99.tistory.com
static 이란 무엇일까?
💡 학습 목표
1. static 이란 무엇일까?
2. 데이터 영역, static 메모리 영역 이란 무엇일까?
3. static 은 태양이다.
static 변수 (클래스, 정적)
// 선언
static 자료형 멤버변수명;
- 여러 객체들이 공유하는 하나의 변수(데이터) 가 필요할 때 사용하는 멤버 변수
→ 여러 인스턴스가 공유하는 기준 값이 필요한 경우
→ 사람마다 새로운 번호 생성 등
- 객체가 생성되기 이전 (new 키워드 이전), 처음 프로그램이 메모리에 로딩될 때 메모리를 할당 받음
→ 객체 생성과 관계 없이 해당 멤버변수에 접근할 수 있음
→ 참조변수 대신, 클래스 이름으로 직접 참조 가능 : 클래스명.멤버변수명
- 객체(인스턴스) 들이 공통으로 사용하는 영역
→ 모든 객체가 같은 값을 담음
→ static 변수만 사용하면 각각의 객체가 고유한 값을 가지게 할 수 없음
→ 다른 멤버변수를 활용해서 저장할 것.
번호표 출력 프로그램
public class NumberPrinter {
private int id;
private static int waitNumber = 1; // 선언과 동시에 초기화
public NumberPrinter(int id) {
this.id = id;
}
// 기능
// 번호표를 출력 합니다.
public void printwaitNumber() {
System.out.println(id + "번 대기 순번은 " + waitNumber);
waitNumber++;
}
public static void main(String[] args) {
NumberPrinter numberPrinter1 = new NumberPrinter(1);
NumberPrinter numberPrinter2 = new NumberPrinter(2);
numberPrinter1.printwaitNumber();
System.out.println("-----------------------");
numberPrinter2.printwaitNumber();
}
}
출력 결과
1번 대기 순번은 1
-----------------------
2번 대기 순번은 2
static 메서드 (클래스, 정적)
// 구현
[접근제어자] static 자료형 메서드명 (자료형 매개변수) {
코드;
}
객체가 생성되기 이전(new 이전), 처음 프로그램이 메모리에 로딩될 때 메모리를 할당 받음
→ 객체 생성과 관계 없이 해당 메서드 호출 가능
→ 참조변수 대신, 클래스 이름으로 호출 가능 : 클래스명.메서드명(매개변수);
static 메서드 안에서는 (static이 아닌) 멤버변수를 활용할 수 없음
→ 객체가 메모리에 로드된 상태라고 보장할 수 없기 때문
→ 지역 변수는 사용 가능

static 응용 - 싱글톤 패턴(singleton pattern)
- 프로그램에서 인스턴스가 단 한 개만 생성되어야 하는 경우 사용하는 디자인 패턴
- static 변수, 메서드를 활용하여 구현 할 수 있음
싱글톤 패턴으로 회사 객체 구현하기
1. 생성자는 private으로 선언
private Company() {};
2. 클래스 내부에 유일한 private 인스턴스(객체) 생성
private static Company instance = new Company();
3. 외부에서 유일한 인스턴스를 참조할 수 있는 public 메서드 제공
public static Company getInstance() {
if( instance == null) {
instance = new Company();
}
return instance;
}
main 테스트
// 1. 테스트
// 생성자를 private 로 선언했기 때문에
// 기본 생성자로 호출할 수 없다.
// Company company = new Company();
// 2. 테스트
// Company.instance; = 접근 제어 지시자가 private 이다.
// 3. 테스트
// 외부에서 유일하게 Company 객체 주소값에 접근할 수 있는 메서드
// stack메모리에 저장됨
Company naver = Company.getInstance();
Company tenco = Company.getInstance();
System.out.println(naver);
System.out.println(tenco);
'[JAVA] > [자바 기초]' 카테고리의 다른 글
[자바 기초] 책 스토어 프로그램 만들어보기 C R U D (0) | 2023.08.04 |
---|---|
[자바 기초] 배열 (0) | 2023.08.04 |
[자바 기초] C R U D 의 개념 (0) | 2023.08.02 |
[자바 기초] this 키워드 (0) | 2023.08.02 |
[자바 기초] 접근 제어 지시자, get(), set() 메서드 (0) | 2023.08.01 |