자바의 메모리 구조는 크게 메서드 영역, 스택 영역, 힙 영역 3개로 나눌 수 있다.
static(클래스, 정적) 변수 혹은 메서드는 모두 메서드 영역에 저장된다. 이들은 객체를 생성하지 않고도 접근할 수 있다. 코드를 통해서 하나씩 알아보자.
만약에 내가 생성된 객체의 개수를 카운트할때는 어떻게 하면 될까? 이때는 클래스에 공통적으로 사용하는 변수인 static 변수를 사용하면 된다.
public class Data3 {
public String name;
public static int count; //static (정적 변수, 클래스 변수)
public Data3(String name) {
this.name = name;
count++;
}
}
public class Data3CountMain3 {
public static void main(String[] args) {
Data3 data1 = new Data3("a");
System.out.println(Data3.count); //1
Data3 data2 = new Data3("b");
System.out.println(Data3.count); //2
Data3 data3 = new Data3("c");
System.out.println(Data3.count); //3
}
}
main
을 실행하면 아래와 같이 동작한다.count
의 값을 1 증가 시킨다.static 메서드는 static 변수와 마찬가지로 따로 객체를 생성하지 않고 사용할 수 있는 메서드이다.
public class DecoUtil2 {
public static String deco(String str) {
return "*" + str + "*";
}
}
deco
는 문자 앞뒤에 *
를 붙여주는 static
메서드 이다.public class DecoMain2 {
public static void main(String[] args) {
String s = "hello java";
String deco = DecoUtil2.deco(s);
System.out.println(s);
System.out.println(deco);
}
}
DecoUtil2
객체를 만들지 않고도, deco
메서드를 사용할 수 있다.
참고로 static
메서드는 static
변수 혹은 다른 static
메서드에만 접근할 수 있다. 그래서 객체 생성이 필요 없이 메서드의 호출만으로 필요한 기능을 수행할 때 주로 사용한다. 수학의 여러가지 기능을 담은 유틸리티성 메서드를 만들 때 static
메서드를 활용할 수 있다.