static 키워드를 사용하여 변수를 선언하면 해당 변수는 클래스 수준에서 공유되며 객체 인스턴스에 종속x
따라서 static 변수는 모든 객체 인스턴스가 공유하게 됨
일반적으로는 static 변수는 클래스 수준의 데이터를 저장하거나 클래스 수준에서 공유해야 하는 데이터를 저장하는 데 사용된다.
Static 변수
클래스 수준에서 하나의 변수를 공유. 따라서 모든 객체 인스턴스에서 같은 변수를 참조한다.
객체 인스턴스를 생성하지 않고도 클래스 이름을 통해 접근할 수 있다.
class Example {
static int staticVariable = 10;
int instanceVariable;
static void staticMethod() {
System.out.println("Static method called");
}
void instanceMethod() {
System.out.println("Instance method called");
}
}
public class Main {
public static void main(String[] args) {
// 클래스 이름을 사용하여 static 변수와 static 메소드에 접근
System.out.println(Example.staticVariable); // 클래스 이름을 사용한 접근
Example.staticMethod(); // 클래스 이름을 사용한 접근
// 객체 인스턴스를 생성하여 instance 변수와 instance 메소드에 접근
Example obj = new Example();
obj.instanceVariable = 20;
System.out.println(obj.instanceVariable); // 객체 인스턴스를 사용한 접근
obj.instanceMethod(); // 객체 인스턴스를 사용한 접근
}
}
인스턴스 변수 (static이 아닌 변수)
각 개체 인스턴스마다 고유한 변수를 갖는다. 따라서 객체 인스턴스를 생성할 때마다 새로운 변수 인스턴스가 생성된다.
객체 인스턴스를 생성한 후에만 해당 변수에 접근할 수 있으며, 다른 객체 인스턴스의 변수에 직접 접근이 불가하다.