Java
static 변수, static 메서드
hs_developer
2022. 6. 22. 19:23
static을 사용하면 변수나 메서드를 객체화 없이 사용할 수 있다.
따라서 여러 프로그램에서 공통으로 사용하는 경우에 static을 사용한다.
public class NonStaticTest {
int a=10;
public void call()
{
System.out.println("call method");
}
public static void main(String[] args) {
// static 없으면 인스턴스화 해야 함
NonStaticTest nst = new NonStaticTest();
System.out.println(nst.a); // 10
nst.call(); // call method
}
}
public class StaticTest {
static int a=10;
public static void call()
{
System.out.println("static method call");
}
public static void main(String[] args) {
// 객체화 없이 사용 가능
System.out.println(a); // 10
call(); // static method call
}
}
static 사용시 바로 메모리에 할당되기 때문에 객체화 없이 바로 사용 가능하다.
때문에, 계속 값을 공유하는 경우에 static 사용 시 메모리를 덜 소모할 수 있다.