변수의 종류 선언위치 생성시기 static 클래스 영역 클래스가 메모리에 올라갈때 instance 클래스 영역 인스턴스 생성 시 local 메서드 영역 변수 선언문 수행시
같은 클래스의 모든 인스턴스들이 공유하는 변수
class명.변수(or method)명으로 접근 가능)참조변수.인스턴스변수명으로 접근
이때 static인 countOfGoods는 새로운 Goods instance가 생성 되더라도 Class 전역에서 공유되여 사용
접근 가능 범위 (Scope)
static영역 ->instance변수 접근 불가
instance영역 ->static변수 접근 가능
instance영역 -> 타instance변수 접근 불가
전역 변수와 전역함수를 만들때 사용
static 메서드 내에선 this사용 불가static 메서드 내에서 static멤버만 접근 가능static멤버의 초기화는 static블록에서 할 수 있음static 초기화 : static { ... // static 초기화 영역 ... }public class StaticEx {
public static int refCount; // 클래스(static) 멤버
public static String classVar; // 클래스 멤버
public String instanceVar; // 인스턴스 멤버
// static 블록으로 static 영역 초기화
static {
refCount = 0;
classVar = "Static Member";
// instanceVar = "Instance Member"; // 접근 불가
System.out.println("Static Block");
}
// 생성자
StaticEx() {
// 참조 카운트 증가
// 인스턴스 맴버 -> static 멤버 접근은 가능
refCount++;
System.out.println("인스턴스 개수:" + refCount);
}
}