프로그래밍 문법/java

정적(static) 함수, 변수

씩씩한 IT블로그 2023. 5. 27. 20:46
반응형

정적함수, 정적변수

- 정적함수 : 인스턴스 없이도 사용할 수 있는 함수, 맴버변수를 사용할 수 없다.

- 정적변수 : 인스턴스 없이도 접근할 수 있는 변수

- ex)

public class CalculationTest {
    int ans = 4;
    static String name = "calculater";

    //static 함수
    static int add(int x, int y) {
        // return x+y+ans; //맴버변수는 사용할 수 없다.
        return x+y;
    }

    //맴버함수
    int subtractFour(int x, int y) {
        return x-y-this.ans;
    }


    public static void main(String[] args) {
        //함수들의 사용
        CalculationTest calculation = new CalculationTest();
        System.out.println("3 + 4 = "+calculation.add(3,4));
        System.out.println("10 - 4 - 4= "+calculation.subtractFour(10,4));

        //인스턴스 없이 접근할 수 있다
        System.out.println("4 + 7 = "+CalculationTest.add(4,7));
        System.out.println(CalculationTest.name);
    }
}
반응형