반응형

[Oracle Java Tutorial을 읽고 순서에 의해 정리한 후 본인의 경험과 이해를 바탕으로 작성된 글임을 밝힌다.]

[Java Tutorial, 자바 프로그래밍 기초 배우기, Java Programming, 자바 튜토리얼]

지역 클래스 (Local Classes)

로컬(지역) 클래스(Local classes)는 중괄호{ } 사이에 0개 또는 그 이상의 구문의 그룹이 있는 블록에 정의된 클래스다. 일반적으로 메서드의 몸체에서 지역변수가 정의된 걸 찾을 수 있다.

지역 클래스는 내부 클래스와 닮았다(Local Classes Are Similar To Inner Classes)

지역 클래스는 어떤 static 멤버를 선언이나 정의할 수 없는 이유로 내부 클래스와 닮았다.

vaildatePhoneNumber static메서드에서 정의된 PhoneNumber 클래스 같은 static메서드내 지역 클래스는 감싸고 있는 클래스의 static멤버만 참조할 수 있다. 예를 들어 만약 static으로 regularExpression 멤버변수를 선언하지 않았다면 자바 컴파일러는 non-static 변수인 regularExpressionstatic구문에서 참조될 수 없다. 라는 비슷한 에러 메시지를 만든다.

지역 클래스는 non-static이다. 왜냐하면 포함된 블록의 인스턴스 멤버에 접근권이 있기 때문이다. 그 결과 대부분 static으로 선언된 종류들을 포함할 수 없다.

인터페이스는 본질적으로 static이라서 블록 내에 인터페이스를 선언할 수 없다. 예를 들어 아래 발취된 코드는 컴파일되지 않는다. 왜냐하면 인터페이스 HelloTheregreetInEnglish 메서드의 몸체 내에 정의되어 있다.

    public void greetInEnglish(){

       interface HelloThere {

          public void greet();

       }

       class EnglishHelloThere implements HelloThere {

            public void greet(){

                System.out.println(“Hello “ + name);

           }

      }

      HelloThere myGreeting = new EmglishHelloThere();

      myGreeting.greet();

    }

 

 

지역 클래스에서 static을 초기화 하는 부분 또는 멤버 인터페이스를 선언할 수 없다. 아래 발췌된 소스도 컴파일되지 않는다. 왜냐하면 EnglishGoodbye 메서드 때문이다. sayGoodbyestatic로 선언되어 있다. Static은 오직 상수 선언시만 허용된다.라는 비슷한 오류 메시지를 만들 것이다.

    public void sayGoodbyeInEnglish(){

       class EnglishGoodbye() {

          public static void sayGoodbye(){

             System.out.println(“Bye bye”);

         }

      }

      EnglishGoodbye.sayGoodbye();

    }

지역 클래스는 상수로 제공되는 static 멤버를 가질 수 있다. EnglishGoodbye static멤버이기 때문에 아래 발췌 코드는 컴파일된다.

farewell은 상수다.

    public void sayGoodbyeInEnglish(){

       class EnglishGoodbye{

           public static final String farewell = “Bye bye”;

           public void sayGoodBye(){

               System.out.println(farewell);

           }

       }

        EnglishGoodbye myEnglishGoodbye = new EnglishGoodbye(); 

        myEnglishGoodbye.sayGoodbye()’

   }

 

반응형
반응형

[Oracle Java Tutorial을 읽고 순서에 의해 정리한 후 본인의 경험과 이해를 바탕으로 작성된 글임을 밝힌다.]

[Java Tutorial, 자바 프로그래밍 기초 배우기, Java Programming, 자바 튜토리얼]

내부 클래스 예제(Inner Class Example)

먼저 배열을 이용한 내부 클래스(inner class) 사용에 대해 아래 예제를 통해 알아본다. 먼저 배열을 생성하고 값을 할당한 뒤 짝수 인덱스를 순서대로 호출하는 프로그램을 만들어 볼 것이다.

DataStructure.java 프로그램은 다음과 같이 구성되어 있다.

  • 외부 클래스(Outer Class)DataStructure는 연 이은 integer값인 0,1,2,3 등을 배열에 할당하는 객체를 생성하는 생성자를 포함하고 있다.

  • 내부 클래스(Inner Class)EvenIteratorIterator인터페이스를 확장(extends) DataStructureIterator인터페이스를 구현(implements)하고 있다. Iterators는 데이터 구조를 단계별로 수행하고 마지막 요소를 체크하거나 현재 값을 가져오거나 다음 값으로 이동하는 전형적인 메서드가 있다.

  • DataStructure 객체를 인스턴스 하는 main메서드는 짝수 인덱스 값을 가진 arrayOfInts 배열을 출력하는 printEven메서드를 호출한다.

 

   public class DataStructure {

 

    private final static int SIZE = 15;

    private int[] arrayOfInts = new int[SIZE];

 

    public DataStructure() {

       for (int i = 0; i < SIZE ; i++) {

          arrayOfInts[i] = i;

          }

    }

 

    public void printEven() {

       DataStructureIterator iterator = this.new EvenIterator();

       while(iterator.hasNext()) {

          System.out.println(iterator.next() + " ");

       }

       System.out.println();

    }

    interface DataStructureIterator extends java.util.Iterator{ }

 

    private class EvenIterator implements DataStructureIterator {

       private int nextIndex = 0;

       public boolean hasNext() {

          return (nextIndex <= SIZE - 1);

       }

 

    public Integer next() {

       Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);

       nextIndex += 2;

       return retValue;

      }

   }

   public static void main(String[] args) { 

      DataStructure ds = new DataStructure();

      ds.printEven();

   }

}

 

결과는 0, 2, 4, 6, 8, 10, 12, 14

주목해 보면 EvenIterator클래스는 DataStructure 객체의 인스턴스 변수인 arrayOfInts 직접 참조한다.

예제에서 보여준 것처럼 헬퍼 클래스로 구현하기 위해 내부 클래스를 사용할 있다. 사용자 인터페이스의 이벤트들을 다룰 있고 물론 내부 클래스를 어떻게 사용해야 하는지 반드시 알아야 하는 것이다. 왜냐하면 이벤트 핸들링 기술은 그것들을 광범위하게 사용할 있다.

 

 

로컬 및 익명 클래스(Local and Anonymous Classes)

 

내부 클래스에는 2가지 타입이 더 있다. 메서드의 몸체 내에 내부 클래스를 선언할 수 있다. 이 클래스들은 지역 클래스로 알려져 있다. 또한 클래스의 이름 없이 메서드의 몸체 내에 내부 클래스를 선언할 수도 있다. 이 클래스들을 익명 클래스라고 한다.

수식어/한정어(Modifiers)

외부 클래스의 다른 멤버 클래스를 위해 사용하는 내부 클래스를 위한 같은 수식어를 사용할 수 있다. 예를 들어, 다른 클래스 멤버들의 제한적 접근을 위해 사용할 수 있는 것처럼 내부 클래스의 접속을 제한하기 위해 접근 제어자인 private, public 그리고 protected를 사용할 수 있다.

반응형