static

YYY·2025년 2월 3일

stactic 이란

  1. 변수나 메서드 앞에 붙으며 클래스에 속하게 됨.
  2. 모든 객체(인스턴스)가 공유함. 즉 객체 생성하지 않고도 사용 가능, 서로 다른 클래스여도
class MathUtils {
    // static 메서드: 객체 없이 사용 가능
    public static int add(int a, int b) {
        return a + b;
    }

    // 일반 메서드: 객체를 생성해야 사용 가능
    public int multiply(int a, int b) {
        return a * b;
    }
}

public class Main {
    public static void main(String[] args) {
        // static 메서드는 클래스 이름으로 직접 호출 가능
        int sum = MathUtils.add(5, 3);
        System.out.println("Sum: " + sum); // 출력: Sum: 8

        // 일반 메서드는 객체 생성 후 호출해야 함
        MathUtils math = new MathUtils();
        int product = math.multiply(5, 3);
        System.out.println("Product: " + product); // 출력: Product: 15
    }
}

객체 생성을 위해 호출한다는게 class를 호출하는거임

profile
무지렁이 탈출기

0개의 댓글