본문 바로가기

Java/Java

클래스의 정적 구성 요소

클래스의 기본적인 용도는 객체를 생성하는 것이고, 클래스에 선언된 필드와 메서드는 객체를 생성하고 나면 생성된 객체에 속하게 된다. 하지만, 때로는 클래스 자체에 속하는 구성요소를 선언해야 할 필요도 있다. 그런 구성요소를 정적(static) 구성요소라고 부른다.

정적 필드

일반적으로 필드는 객체의 고유한 데이터 값을 저장하기 위해 사용되지만, 경우에 따라서는 클래스 자체에 속하는 데이터를 저장할 변수도 필요하다. 그럴때는 클래스 안에 정적 필드(static field)를 선언하면 된다.

정적 필드란 필드의 선언문 앞에 static이라는 키워드를 붙여서 선언한 필드를 말한다.

class Accumulator {
	int total = 0;
	static int grandTotal = 0;
	void accumulator(int amount) {
		total += amount;
		grandTotal += amount;
	}
}
위 클래스의 accumulator 메서드에서는 total필드와 grandTotal필드에 똑같은 파라미터 값을 더하고 있지만, 여러객체에 대해 이 메서드를 호출하면 그 결과는 다르게 나타난다. total필드는 객체마다 따로 생기지만 grandTotal필드는 특정 객체에 상관없이 클래스 자체에 하나만 생기는 정적 필드이기 때문이다.

사용예를 보자.

class StaticFieldExample1 {
	public static void main(String args[]) {
		Accumulator obj1 = new Accumulator();
		Accumulator obj2 = new Accumulator();
		obj1.accumulator(10);
		obj2.accumulator(20);
		System.out.println("obj1.total = " + obj1.total);
		System.out.println("obj1.grandTotal = " + obj1.grandTotal);
		System.out.println("obj1.total = " + obj2.total);
		System.out.println("obj1.grandTotal = " + obj2.grandTotal);
	}
}
StaticFieldExample1을 컴파일해서 실행하면 다음과 같은 결과가 나온다.



위 결과를 보면 obj1과 obj2를 통해 누적한 값이, total 필드에는 각각 누적되었는데, grandTotal필드에는 객체에 상관없이 전체 합계가 누적된 것을 볼 수 있다.

위 프로그램에서 정적 필드인 grandTotal필드를 obj1.grandTotal, obj2.grandTotal이라는 이름으로 사용하고 있지만, 정적 필드는 클래스 자체에 속하기 때문에 앞에 객체 이름 대신 클래스 이름을 붙여서 사용할 수도 있다.

System.out.println("총계= " + Accumulator.grandTotal);