클래스(정적) 변수
형태: static 키워드가 데이터타입 앞에 명시
선언 위치: 클래스 영역 내
생성 시기: 클래스가 Method Area 영역에 할당될 때
사용 시기: 객체 생성 이전에도 사용 가능
인스턴스 변수
형태: 일반 변수 선언과 동일
선언 위치: 클래스 영역 내
생성 시기: 인스턴스가 생성될 때
사용 시기: 객체 생성 이후에만 사용 가능
정적 변수 예시
class Counter {
static int count = 0;
Counter(){
// 생성자
count++; // count = count + 1;
}
}
public class F_Field {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
Counter c4 = new Counter();
Counter c5 = new Counter();
System.out.println(c3.count);// 5
new Counter();
new Counter();
new Counter();
System.out.println(Counter.count);// 8
}
}
'java' 카테고리의 다른 글
실습) 클래스 생성, 호출 (0) | 2025.02.21 |
---|---|
실습) 인스턴스와 클래스(정적) 변수 (0) | 2025.02.21 |
15. 필드(Filed)-1. 필드와 변수 (0) | 2025.02.21 |
실습) 클래스 (0) | 2025.02.21 |
14. 객체(Object)-3. 클래스의 구조 (0) | 2025.02.21 |