본문 바로가기

Java SE/Inner class

Inner class


class Outer
{
 class Inner
 {
  /* Instance 멤버인 내부클래스는 바깥 클래스의 인스턴스 멤버이므로
  *  바깥 클래스의 인스턴스 안에 존재해야 한다. 그러므로 인스턴스 내부 클래스는
  *  인스턴스 멤버가 아닌 static 멤버를 가질 수가 없는 것이다. static 멤버는 인스턴스 안에
  *  존재하지 않는 성분이기 때문이다.
  *  그러므로 아래에 선언된 static 멤버변수는 다음과 같은 컴파일 오류를 발생한다.
  *  InnerClassTest.java:15: inner classes cannot have static declarations
  *       static int n = 100;
  *                 ^
  *      1 error
  */
  static int n = 100;
 }

 /* 클래스 내부에 선언된 클래스가 static 으로 선언된 경우를 Static Nested Class라고 한다.
 *  원래 static 멤버는 인스턴스 영역에 로드되는 것이 아니기 때문에 static 으로 선언된 중첩클래스는
 *  당연히 static 멤버변수를 가질 수가 있는 것이다.
 */
 static class StaticNestedClass
 {
  static int n = 100;
 }

}

class InnerClassTest {
 public static void main(String[] args) {
  Outer outer = new Outer();
 }
}