static이란 고정된 것이라는 의미이다.
static 변수(정적 필드)와 static 메소드(정적 메소드)를 만들 수 있다. 합쳐서 정적 멤버라고 한다. 이는 객체 인스턴스가 아닌 클래스 레벨에서 접근이 가능하다는 것을 의미한다.
그렇기에 클래스 로더가 클래스를 로딩해서 메소드 메모리 영역에 적재할 때 클래스별로 관리된다. 따라서 클래스의 로딩이 끝나는 즉시 바로 사용할 수 있다.
static을 사용할지에 대한 판단 기준은 공용으로 사용하는지 아닌지에 따라 결정하면 된다. 그냥 생성한다면 자동으로 인스턴스로 생성되며 정적으로 생성하려면 필드와 메소드 선언 시 static 키워드를 붙여주면 된다.
static 키워드를 사용하여 선언된 변수는 클래스 변수로 간주된다. 모든 인스턴스가 해당 변수를 공유하며, 클래스 로딩 시점에 메모리에 할당된다.public class Example {
public static int staticVariable = 0;
public void increment() {
staticVariable++;
}
}
public class Test {
public static void main(String[] args) {
Example example1 = new Example();
Example example2 = new Example();
example1.increment();
System.out.println(Example.staticVariable); // 출력: 1
example2.increment();
System.out.println(Example.staticVariable); // 출력: 2
}
}
두개의 example1과 example2 인스턴스가 생성되었고 각 인스턴스를 통해 increment() 메소드를 실행했지만, 두 인스턴스 모두 static로 선언된 staticVariable변수를 증가시키고 있기 때문에 위와 같은 결과가 나온다.
static 키워드를 사용하여 선언된 정적 메소드는 클래스 메소드로 간주되며, 인스턴스가 아닌 클래스 자체에서 호출된다.
static 메소드는 클래스 레벨에서 작동하기 때문에 인스턴스 변수나 인스턴스 메소드를 직접 참조할 수 없다. 다만, static 변수나 다른 static 메소드는 참조할 수 있다.
정적 메소드는 유틸리티 함수를 만드는데 유용하게 사용된다.
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
public class Test {
public static void main(String[] args) {
int sum = MathUtils.add(5, 10);
System.out.println("Sum: " + sum); // 출력: Sum: 15
}
}