중첩 클래스 -정적 중첩 클래스

2024. 5. 28. 21:06JAVA

 

public class NestedOuter {
    private static int outClassValue = 1;
    private int outInstanceValue = 2;

    static class nested{
        private int nestedInstanceValue = 3;

        public void print() {
            // 자신의 멤버에 접근 - 가능
            System.out.println("nestedInstanceValue = " + nestedInstanceValue);
//            // 바깥 인스턴스에 직접 접근 - 불가능
//            System.out.println("outInstanceValue = " + outInstanceValue);
            // 바깥 클래스의 정적 변수 접근 - 가능
            System.out.println("outClassValue = " + outClassValue);
        }
    }
}

위의 코드를 시각화 해보자.

각 클래스를 인스턴스화 했을 때,

정적 중첩클래스는 외부, 내부가 서로 다른 인스턴스를 갖는다.

따라서, Nested에서 outInstanceValue에 직접 접근할 수 없다.

 

다만, Nested 는 static 클래스로, 메소드 영역에 로드 된다. NestedOuter의 정보에 포함 돼 있으며, outClassValue와 동일 선상에 존재한다. 따라서, Nested에서 NestedOuter의 private 필드에 접근할 수 있다.

public class NestedOuterMain {
    public static void main(String[] args) {
        NestedOuter Outer = new NestedOuter();
        NestedOuter.Nested nested = new NestedOuter.Nested();

        System.out.println("nestedClass = " + nested.getClass());
        
    }
}

- 정적 중첩 클래스는 new Outer.Nested() 로 인스턴스를 생성할 수 있다.

- 중첩 클래스는 Outer.Nested 로 접근할 수 있다.

- new NestedOuter()로 만든 바깥 클래스와 new NestedOuter.Nested()로 만든 중첩 클래스는 서로 무관하다. (구조상의 설계일 뿐이다)

 

정적 중첩 클래스 활용

..

대략 캡슐화를 통해 불필요한 비용(확인, 불필요한 정보 노출 등의 유지보수 등) 줄이고,

응집력 높인다는 내용.

 

 

 

'JAVA' 카테고리의 다른 글

예외처리 - Unchecked Exception(런타임 익셉션)  (0) 2024.06.02
예외처리 -Checked Exception  (0) 2024.06.02
중첩 클래스  (0) 2024.05.28
enum  (0) 2024.05.01
String_String pool  (0) 2024.04.17