산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

자바 - 내부 클래스

이 장에서는 Java의 내부 클래스에 대해 설명합니다.

중첩 클래스

Java에서 메소드와 마찬가지로 클래스의 변수도 다른 클래스를 멤버로 가질 수 있습니다. 다른 클래스 내에 클래스를 작성하는 것은 Java에서 허용됩니다. 내부에 작성된 클래스를 중첩 클래스라고 합니다. , 내부 클래스를 보유하는 클래스를 외부 클래스라고 합니다. .

구문

다음은 중첩 클래스를 작성하는 구문입니다. 여기에서 Outer_Demo 클래스 외부 클래스이고 Inner_Demo 클래스입니다. 중첩 클래스입니다.

class Outer_Demo {
   class Inner_Demo {
   }
}

중첩 클래스는 두 가지 유형으로 나뉩니다 -

내부 클래스(비정적 중첩 클래스)

내부 클래스는 Java의 보안 메커니즘입니다. 클래스를 액세스 수정자 private와 연결할 수 없다는 것을 알고 있습니다. 그러나 다른 클래스의 멤버로 클래스가 있는 경우 내부 클래스를 private로 만들 수 있습니다. 이것은 또한 클래스의 private 멤버에 액세스하는 데 사용됩니다.

내부 클래스는 정의하는 방법과 위치에 따라 세 가지 유형이 있습니다. 그들은 -

이너 클래스

내부 클래스를 만드는 것은 매우 간단합니다. 클래스 내에서 클래스를 작성하기만 하면 됩니다. 클래스와 달리 내부 클래스는 private일 수 있으며 내부 클래스를 private로 선언하면 클래스 외부의 개체에서 액세스할 수 없습니다.

다음은 내부 클래스를 생성하고 접근하는 프로그램이다. 주어진 예에서 우리는 내부 클래스를 private로 만들고 메소드를 통해 클래스에 접근합니다.

라이브 데모
class Outer_Demo {
   int num;
   
   // inner class
   private class Inner_Demo {
      public void print() {
         System.out.println("This is an inner class");
      }
   }
   
   // Accessing he inner class from the method within
   void display_Inner() {
      Inner_Demo inner = new Inner_Demo();
      inner.print();
   }
}
   
public class My_class {

   public static void main(String args[]) {
      // Instantiating the outer class 
      Outer_Demo outer = new Outer_Demo();
      
      // Accessing the display_Inner() method.
      outer.display_Inner();
   }
}

여기에서 Outer_Demo 외부 클래스, Inner_Demo 내부 클래스, display_Inner() 내부 클래스를 인스턴스화하는 메소드이며 이 메소드는 main에서 호출됩니다. 방법.

위의 프로그램을 컴파일하고 실행하면 다음과 같은 결과를 얻을 수 있습니다 -

출력

This is an inner class.

비공개 회원 액세스

앞서 언급했듯이 내부 클래스는 클래스의 private 멤버에 액세스하는 데에도 사용됩니다. 클래스에 액세스할 수 있는 private 멤버가 있다고 가정합니다. 내부 클래스를 작성하고 내부 클래스 내의 메서드에서 개인 멤버를 반환합니다(예:getValue()). , 그리고 마지막으로 다른 클래스(프라이빗 멤버에 액세스하려는 클래스)에서 내부 클래스의 getValue() 메서드를 호출합니다.

내부 클래스를 인스턴스화하려면 처음에 외부 클래스를 인스턴스화해야 합니다. 이후 외부 클래스의 객체를 사용하여 내부 클래스를 인스턴스화하는 방법은 다음과 같습니다.

Outer_Demo outer = new Outer_Demo();
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();

다음 프로그램은 내부 클래스를 사용하여 클래스의 private 멤버에 액세스하는 방법을 보여줍니다.

라이브 데모
class Outer_Demo {
   // private variable of the outer class
   private int num = 175;  
   
   // inner class
   public class Inner_Demo {
      public int getNum() {
         System.out.println("This is the getnum method of the inner class");
         return num;
      }
   }
}

public class My_class2 {

   public static void main(String args[]) {
      // Instantiating the outer class
      Outer_Demo outer = new Outer_Demo();
      
      // Instantiating the inner class
      Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
      System.out.println(inner.getNum());
   }
}

위의 프로그램을 컴파일하고 실행하면 다음과 같은 결과를 얻을 수 있습니다 -

출력

This is the getnum method of the inner class: 175

메서드 로컬 내부 클래스

Java에서는 메소드 내에 클래스를 작성할 수 있으며 이는 로컬 유형이 됩니다. 지역 변수와 마찬가지로 내부 클래스의 범위는 메서드 내에서 제한됩니다.

메서드 로컬 내부 클래스는 내부 클래스가 정의된 메서드 내에서만 인스턴스화할 수 있습니다. 다음 프로그램은 method-local 내부 클래스를 사용하는 방법을 보여줍니다.

라이브 데모
public class Outerclass {
   // instance method of the outer class 
   void my_Method() {
      int num = 23;

      // method-local inner class
      class MethodInner_Demo {
         public void print() {
            System.out.println("This is method inner class "+num);	   
         }   
      } // end of inner class
	   
      // Accessing the inner class
      MethodInner_Demo inner = new MethodInner_Demo();
      inner.print();
   }
   
   public static void main(String args[]) {
      Outerclass outer = new Outerclass();
      outer.my_Method();	   	   
   }
}

위의 프로그램을 컴파일하고 실행하면 다음과 같은 결과를 얻을 수 있습니다 -

출력

This is method inner class 23

익명 내부 클래스

클래스 이름 없이 선언된 내부 클래스를 익명 내부 클래스라고 합니다. . 익명 내부 클래스의 경우 선언과 동시에 인스턴스화합니다. 일반적으로 클래스 또는 인터페이스의 메서드를 재정의해야 할 때마다 사용됩니다. 익명 내부 클래스의 구문은 다음과 같습니다 -

구문

AnonymousInner an_inner = new AnonymousInner() {
   public void my_method() {
      ........
      ........
   }   
};

다음 프로그램은 익명의 내부 클래스를 사용하여 클래스의 메서드를 재정의하는 방법을 보여줍니다.

라이브 데모
abstract class AnonymousInner {
   public abstract void mymethod();
}

public class Outer_class {

   public static void main(String args[]) {
      AnonymousInner inner = new AnonymousInner() {
         public void mymethod() {
            System.out.println("This is an example of anonymous inner class");
         }
      };
      inner.mymethod();	
   }
}

위의 프로그램을 컴파일하고 실행하면 다음과 같은 결과를 얻을 수 있습니다 -

출력

This is an example of anonymous inner class

같은 방법으로 익명의 내부 클래스를 사용하여 인터페이스뿐만 아니라 구체적인 클래스의 메서드를 재정의할 수 있습니다.

인수로서의 익명 내부 클래스

일반적으로 메서드가 인터페이스, 추상 클래스 또는 구체적인 클래스의 개체를 수락하면 인터페이스를 구현하고 추상 클래스를 확장하고 개체를 메서드에 전달할 수 있습니다. 클래스라면 메서드에 직접 전달할 수 있습니다.

그러나 세 가지 경우 모두 익명의 내부 클래스를 메서드에 전달할 수 있습니다. 다음은 익명 내부 클래스를 메서드 인수로 전달하는 구문입니다. -

obj.my_Method(new My_Class() {
   public void Do() {
      .....
      .....
   }
});

다음 프로그램은 익명 내부 클래스를 메서드 인수로 전달하는 방법을 보여줍니다.

라이브 데모
// interface
interface Message {
   String greet();
}

public class My_class {
   // method which accepts the object of interface Message
   public void displayMessage(Message m) {
      System.out.println(m.greet() +
         ", This is an example of anonymous inner class as an argument");  
   }

   public static void main(String args[]) {
      // Instantiating the class
      My_class obj = new My_class();

      // Passing an anonymous inner class as an argument
      obj.displayMessage(new Message() {
         public String greet() {
            return "Hello";
         }
      });
   }
}

위의 프로그램을 컴파일하고 실행하면 다음과 같은 결과를 얻을 수 있습니다. -

출력

Hello, This is an example of anonymous inner class as an argument

정적 중첩 클래스

정적 내부 클래스는 외부 클래스의 정적 멤버인 중첩 클래스입니다. 다른 정적 멤버를 사용하여 외부 클래스를 인스턴스화하지 않고 액세스할 수 있습니다. 정적 멤버와 마찬가지로 정적 중첩 클래스는 외부 클래스의 인스턴스 변수와 메서드에 액세스할 수 없습니다. 정적 중첩 클래스의 구문은 다음과 같습니다 -

구문

class MyOuter {
   static class Nested_Demo {
   }
}

정적 중첩 클래스를 인스턴스화하는 것은 내부 클래스를 인스턴스화하는 것과 약간 다릅니다. 다음 프로그램은 정적 중첩 클래스를 사용하는 방법을 보여줍니다.

라이브 데모
public class Outer {
   static class Nested_Demo {
      public void my_method() {
         System.out.println("This is my nested class");
      }
   }
   
   public static void main(String args[]) {
      Outer.Nested_Demo nested = new Outer.Nested_Demo();	 
      nested.my_method();
   }
}

위의 프로그램을 컴파일하고 실행하면 다음과 같은 결과를 얻을 수 있습니다 -

출력

This is my nested class

java

  1. 자바 최종 키워드
  2. 자바 instanceof 연산자
  3. Java 중첩 및 내부 클래스
  4. 자바 중첩 정적 클래스
  5. 자바 익명 클래스
  6. 자바 싱글톤 클래스
  7. 자바 리플렉션
  8. 자바 ObjectOutputStream 클래스
  9. 자바 제네릭
  10. 자바 파일 클래스