Nested Class 1

man soup·2020년 4월 16일
0

자바 문법

목록 보기
1/15

Nested Class

  • 클래스 안에 정의된 클래스

  • 종류 2 가지 ( inner & static nested class )

    • inner class( non static nested class ) :
      • 자신을 포함하는 클래스의 맴버들에 접근 가능하다. ( private 맴버도 포함해서 )
      • 2가지 종류 존재 ( local class & anonymous class )
    • static nested class는 맴버에 접근 불가능
  • Outer 클래스의 멤버이다.

  • private, public, protected, package-private로 선언 가능

    • ( outer class는 public 또는 package-private만 가능 )

Why Use Nested Classes?

  • 한 곳에서만 사용하는 클래스들을 grouping 하는 방법
    (ex) node 클래스는 tree 클래스 안에서만 사용
  • 캡슐화 증가
  • 코드를 readable 하고 matinable하게 함

Static Nested Class

  • static class methods와 같이 encloing class의 instance 변수 나 함수를 직접 접근 할 수 없고 오직 object reference를 통해서만 사용할 수 있다.

  • 접근 방법 : OuterClass 이름으로

    • OuterClass.StaticNestedClass
  • OuterClass.StaticNestedClass nestedObject =
    new OuterClass.StaticNestedClass();

Inner Class

  • instance methods and variables와 같이 OuterClass의 인스턴스와 관련있다.

  • enclosing class object의 method 와 fields 에 직접 접근 가능하다.

  • instance 와 관련 있으므로 static 맴버를 정의 할 수 없다.

  • InnerClass 인스턴스는 오직 OuterClass의 인스턴스 안에서만 존재할 수 있고(클래스의 non-static 함수,필드처럼) OuterClass 인스턴스의 함수와 필드에 직접 접근 할 수 있다.

  • InnerClass를 인스턴스화하기 위해 먼저 OuterClass를 인스턴스화 해야한다.

  • OuterClass outerObject = new OuterClass();
    OuterClass.InnerClass innerObject = outerObject.new InnerClass();

  • 2가지 종류의 inner class 존재

    • local class
    • anonymous class
  • outerObject로 OuterClass를 참조하고 있어 enclosing class의 맴버에 접근 할 수 있다. -> 장점보다 단점이 많다(외부 인스턴스에 대한 참조가 존재하기 때문에, 가비지 컬렉션이 인스턴스 수거를 하지 못하여 메모리 누수가 생길 수 있다.)

Shadowing

  • 만약 특정scope에서 선언한 타입(A)과 그 scope를 감싸고 있는 scope에서 같은 이름으로 선언된 타입(B)이 존재한다면, A는 B를 따라간다.(A -shadow-> B)
  • shadow된 선언(B)은 이름만으론 접근할 수 없다.
public class ShadowTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}

출력
x = 23
this.x = 1
ShadowTest.this.x = 0

출처 :
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

https://siyoon210.tistory.com/141

profile
안녕하세요

0개의 댓글