
자바에서 static은 클래스 변수와 클래스 메소드를 선언할 때 사용하는 예약어입니다.
클래스 변수는 해당 클래스의 모든 인스턴스에서 공유되는 변수이며, static 키워드를 사용하여 선언됩니다. 클래스 변수는 객체의 생성 없이도 접근할 수 있습니다.
클래스 메소드는 객체의 생성 없이도 호출할 수 있는 메소드입니다. static 키워드를 사용하여 선언됩니다. 클래스 메소드에서는 인스턴스 변수에 직접 접근할 수 없고, 오직 클래스 변수와 매개변수만 사용할 수 있습니다.
public class MyClass {
static int classVar = 10; // 클래스 변수
int instanceVar = 20; // 인스턴스 변수
static void classMethod() { // 클래스 메소드
System.out.println("Class variable: " + classVar);
//System.out.println("Instance variable: " + instanceVar); (X) 오류 발생
}
void instanceMethod() { // 인스턴스 메소드
System.out.println("Class variable: " + classVar);
System.out.println("Instance variable: " + instanceVar);
}
}
위 예제에서 classVar는 클래스 변수이므로 MyClass.classVar와 같이 객체의 생성 없이 바로 접근할 수 있습니다. 반면 instanceVar는 인스턴스 변수이므로 객체를 생성한 후 new MyClass().instanceVar와 같이 접근해야 합니다.
classMethod는 클래스 메소드이므로 MyClass.classMethod()와 같이 객체의 생성 없이 바로 호출할 수 있습니다. 반면 instanceMethod는 인스턴스 메소드이므로 객체를 생성한 후 new MyClass().instanceMethod()와 같이 호출해야 합니다.
static 키워드는 다른 용도로도 사용될 수 있습니다.
static import: 다른 클래스의 public static 멤버들을 객체 생성 없이 직접 참조할 수 있게 해줍니다.static 블록: 클래스가 로딩될 때 실행되는 초기화 블록입니다.import static java.lang.Math.PI; // Math 클래스의 public static 멤버 PI를 직접 참조할 수 있게 됩니다.
public class MyCircle {
static {
System.out.println("MyCircle 클래스가 로딩됩니다.");
}
private int radius;
public MyCircle(int radius) {
this.radius = radius;
}
public double getArea() {
return PI * radius * radius;
}
}
위 예제에서 static import를 사용하여 Math.PI 대신 PI를 직접 참조할 수 있게 되었습니다. 또한 static 블록을 사용하여 MyCircle 클래스가 로딩될 때 메시지를 출력하도록 했습니다.