Skip to main content

[Java] 변수나 메서드 static으로 선언하는 이유


graph, visited, sb 를 static으로 선언하는 이유

image.png

  • 자바에서 프로그램 시작점은 public static void main(String[] args)인데 main이 static이라 접근하려면 static으로 선언해야 한다.
  • 객체 선언안하고 전역변수처럼 쓰려고 static으로 쓴다. static이 아니면 객체를 만들어야 한다.
  • static 붙이면 클래스 변수/메서드Main.visited, Main.dfs()
  • static 안 붙이면 인스턴스 변수/메서드new Main().dfs()

static 방식

  • 이 경우는 변수와 메서드가 모두 static이라 객체를 만들 필요가 없다.
  • 즉, 클래스에 속하는 변수이다. 바로 클래스 이름으로 호출 가능하다.
  • → visited와 dfs가 클래스 차원에 고정된다.
    → 그냥 Main.dfs(1); 또는 그냥 dfs(1); 호출
public class Main {
    static boolean[] visited;   // 전역(static 변수)

    static void dfs(int node) { // static 메서드
        visited[node] = true;
        System.out.println("방문: " + node);
        // ... 실제 dfs 로직
    }

    public static void main(String[] args) {
        visited = new boolean[6];  // 배열 초기화
        dfs(1);   // 그냥 바로 호출 가능 (new 필요 없음)
    }
}

인스턴스 방식 (static 없음)

  • 여러 객체를 독립적으로 관리하고 싶을때 사용한다.
    → Main m = new Main(5);
    → m.dfs(1);
public class Main {
    boolean[] visited;   // 인스턴스 변수

    // 생성자에서 초기화
    public Main(int n) {
        visited = new boolean[n + 1];
    }

    // 인스턴스 메서드
    void dfs(int node) {
        visited[node] = true;
        System.out.println("방문: " + node);
        // ... 실제 dfs 로직
    }

    public static void main(String[] args) {
        // 객체 생성 (new Main)
        Main m = new Main(5);  

        // 인스턴스 메서드 호출
        m.dfs(1);  
    }
}