Java에서 클래스가 가질 수 있는 변수는 크게 세 가지 유형으로 나뉩니다. 바로 지역 변수(Local Variable), 인스턴스 변수(Instance Variable), 그리고 클래스/정적 변수(Class/Static Variable)입니다.
지역 변수(Local Variable)
지역 변수는 메서드, 코드 블록, 생성자 내부에서 선언되는 변수입니다. 프로그램의 실행 흐름이 해당 메서드, 코드 블록, 생성자에 진입하면 지역 변수가 생성되고, 실행 흐름이 해당 영역을 벗어나면 소멸됩니다. 또한 지역 변수는 사용하기 전에 반드시 어떤 값으로든 초기화해야 한다는 점을 기억해야 합니다.
예제
public class LocalVariableTest {
public void show() {
int num = 100; // 지역 변수
System.out.println("The number is : " + num);
}
public static void main(String args[]) {
LocalVariableTest test = new LocalVariableTest();
test.show();
}
}
실행 결과
The number is : 100
인스턴스 변수(Instance Variable)
인스턴스 변수는 블록, 메서드 또는 생성자의 외부에 위치하면서 클래스 내부에 선언되는 변수입니다. 인스턴스 변수는 클래스의 객체가 생성될 때 함께 생성되며, 객체가 소멸할 때 함께 소멸됩니다. 즉, 각 객체마다 독립적인 값을 가질 수 있습니다.
예제
public class InstanceVariableTest {
int num; // 인스턴스 변수
InstanceVariableTest(int n) {
num = n;
}
public void show() {
System.out.println("The number is: " + num);
}
public static void main(String args[]) {
InstanceVariableTest test = new InstanceVariableTest(75);
test.show();
}
}
실행 결과
The number is : 75
정적/클래스 변수(Static/Class Variable)
정적(static)/클래스 변수는 static 키워드를 사용하여 정의합니다. 이 변수는 클래스 내부에 선언되지만 메서드와 코드 블록의 외부에 위치합니다. 정적 변수는 프로그램이 시작될 때 생성되고 프로그램이 종료될 때 소멸되며, 모든 객체가 이 변수를 공유한다는 특징이 있습니다. 아래 예제처럼 생성된 객체의 개수를 세는 용도로 활용할 수 있습니다.
예제
public class StaticVaribleTest {
int num;
static int count; // 정적 변수
StaticVaribleTest(int n) {
num = n;
count++;
}
public void show() {
System.out.println("The number is: " + num);
}
public static void main(String args[]) {
StaticVaribleTest test1 = new StaticVaribleTest(75);
test1.show();
StaticVaribleTest test2 = new StaticVaribleTest(90);
test2.show();
System.out.println("The total objects of a class created are: " + count);
}
}
실행 결과
The number is: 75 The number is: 90 The total objects of a class created are: 2