static
- 클래스 변수와 클래스 메서드를 정의할 때 사용하는 키워드
- 클래스 수준의 영역을 가지며 인스턴스에 속하는것이 아닌 클래스에 속함
- 모든 인스턴스에서 공유되며 클래스의 인스턴스를 생성하지 않고도 접근 가능
staic 변수
- 클래스의 모든 인스턴스가 공유하는 변수
- 클래스가 로드될 때 메모리에 할당
- 모든 인스턴스에 대해 동일한 값 유지
class Example { static int count = 0; // static 변수
Example() {
count++;
}
}
> static 메서드
- 인스턴스를 생성하지 않고 호출 가능
- this 사용 불가
- 오버라이드 불가
```java
class Example {
static void display() {
System.out.println("This is a static method.");
}
}
static 블록
- 처음으로 로드 될때 실행됨
- 변수의 초기화나 클래스 관련된 초기화 작업에 사용
class Example { static { System.out.println("Static block initialized."); } }
class Example {
static int staticVariable = 5; // 정적 변수
static void staticMethod() { // 정적 메서드
System.out.println("This is a static method.");
}
}
public class Main {
public static void main(String[] args) {
// 정적 변수에 접근
System.out.println("Static variable: " + Example.staticVariable);
// 정적 메서드 호출
Example.staticMethod();
}
}
Example 클래스에는 staticVariable이라는 정적 변수와 staticMethod라는 정적 메서드가 있음
Main 클래스에서 Example 클래스의 정적 변수에 접근하고 정적 메서드를 호출
staticVariable에는 모든 Example 클래스의 인스턴스에서 동일한 값이 할당되며 staticMethod는 클래스의 인스턴스를 생성하지 않고 호출