Programming/Tips, Fix, Anything Else

[TFAE] 자바 main 메서드에서 static을 왜 쓰는걸까?

Supreme_YS 2022. 2. 28. 12:00

static으로 선언된 변수, 함수(메서드)는 자바 버츄얼 머신에서 인스턴스 객체의 생성없이 호출 할 수 있다.

public class Test {
	public static void main(String[] args) {
    		System.out.println("Hello, World");
    	}
}

 

 

static이 없으면 Test 객체를 생성해서 내부 함수인 main을 호출해야 한다.

class는 공장, 공장에서 만들어진 것이 객체, 객체는 인스턴스(Instance)

 

* 공장(Class)내에 사칙연산 메서드가 있다고 해보자. 덧셈, 뺄셈, 곱셈, 나눗셈

일반적인 메서드 사용법 : 공장에서 객체를 하나 생성함으로써 메서드를 사용할 수 있게끔 하는 것. 즉, 클래스에서 객체 생성 후 -> 메서드 사용

 

* static은 왜 main에 붙어있나?

-> main함수는 프로그램의 시작점 (entry-point)이 되기 때문에 static이 필요하다. 

-> main함수는 일반적인 사용법의 예외로 프로그램의 구동과 동시에 사용되야함으로 자바 설계과정에서 static이 만들어졌다. 

 

* 메모리에 가장 먼저 올라간다.

-> 자바 프로그램을 실행하면 static으로 지정된 메서드를 찾아서 먼저 메모리에 할당시킨다.

-> static으로 지정된 메서드가 여러개인 경우에는 객체를 생성하는 것과 상관없이 모두 메모리에 할당시킨다.

-> 그런 후에, "main" 으로 만들어진 메서드가 있는지를 찾아서, 그 메서드를 가장 먼저 시작점(entry-point)의 메서드로써 호출을 하게 되는 것이다.


public class ExampleStatic {

    public void helloWorld() {
        System.out.println("hello, world!");
    }

    public static void main(String[] args) {
        helloWorld();
    }
}

이 코드는 실행이 될까 안될까? 생각을 해보잣! 정답 및 코드는 더보기

더보기

정답 : 안된다!

그렇다면 실행되게 하려면 어떻게 할 수 있을까?

public class ExampleStatic {

    public void helloWorld() {
        System.out.println("hello, world!");
    }

    public static void main(String[] args) {
        ExampleStatic exampleStatic = new ExampleStatic;
        exampleStatic.helloWorld();
    }
}

위에서 언급했듯이, 일반적인 방법으로 객체를 생성하고 생성된 객체의 메서드를 호출하는 방법이 있을 것이다.

다음으로, 아래의 코드처럼 메서드를 static화 시켜서 객체의 생성이 따로 필요없이 메모리에 올려서 사용하는 방법이 있다!

public class ExampleStatic {

    public static void helloWorld() {
        System.out.println("hello, world!");
    }

    public static void main(String[] args) {
        helloWorld();
    }
}

이 글을 통해, 보다 자바의 static에서 자유로워 지시길 바라며..