Before 2022/Java & Spring

내부 클래스와 중첩 클래스의 차이점

Eljoe 2019. 4. 1. 13:16

public class Test {
    private int i = 0;

    // 내부 클래스(Inner)
    // 외부 클래스의 필드나 메소드를 자유로이 이용 가능하나
    // 외부 클래스가 인스턴스화 된 이후부터 동작한다.
    class inner {
        void add() {
            System.out.println(++i);
        }
    }

    // 중첩 클래스(Nested)
    // 외부 클래스의 static 영역에만 접근 가능함.
    // 외부 클래스를 인스턴스화 하지 않아도 바로 사용 가능한 내부 클래스(간편함)
    // Builder 패턴의 Builder class
    static class nested {
        static int j = 0;

        static void add() {
            System.out.println(++j);
        }
    }

    public static void main(String[] args) {
        Test test = new Test();

        Test.inner inner = test.new inner();
        inner.add();

        nested.j = 10;
        nested.add();
    }
}