Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

단일 Java 프로그램에서 둘 이상의 클래스를 선언할 수 있습니까?


단일 Java 프로그램에는 둘 이상의 클래스가 포함되며 Java에서는 두 가지 방법으로 가능합니다.

단일 자바 프로그램에서 여러 클래스를 구현하는 두 가지 방법

  • 중첩 클래스
  • 중첩되지 않은 여러 클래스

컴파일러가 중첩되지 않은 여러 클래스에서 작동하는 방식

아래 예에서 Java 프로그램은 두 개의 클래스를 포함합니다. 하나는 클래스 이름인 Computer이고 다른 하나는 랩탑입니다. 두 클래스 모두 고유한 생성자와 메서드가 있습니다. 메인 메서드에서 두 클래스의 개체를 만들고 해당 메서드를 호출할 수 있습니다.

예시

public class Computer {
   Computer() {
      System.out.println("Constructor of Computer class.");
   }
   void computer_method() {
      System.out.println("Power gone! Shut down your PC soon...");
   }
   public static void main(String[] args) {
      Computer c = new Computer();
      Laptop l = new Laptop();
      c.computer_method();
      l.laptop_method();
   }
}
class Laptop {
   Laptop() {
      System.out.println("Constructor of Laptop class.");
   }
   void laptop_method() {
      System.out.println("99% Battery available.");
   }
}

위의 프로그램을 컴파일하면 두 개의 .class 파일 Computer.class 및 Laptop.class가 생성됩니다. 이것은 코드를 다시 컴파일하지 않고도 다른 프로젝트의 어딘가에서 .class 파일을 재사용할 수 있다는 이점이 있습니다. 간단히 말해서 생성된 .class 파일의 수는 코드의 클래스 수와 같습니다. 클래스를 원하는 만큼 만들 수 있지만 하나의 파일에 많은 클래스를 작성하는 것은 코드를 읽기 어렵게 만들기 때문에 모든 클래스에 대해 하나의 파일을 만들 수 있으므로 권장하지 않습니다.

출력

Constructor of Computer class.
Constructor of Laptop class.
Power gone! Shut down your PC soon...
99% Battery available.

컴파일러가 중첩 클래스에서 작동하는 방식

여러 내부 클래스가 있는 기본 클래스가 컴파일되면 컴파일러는 각 내부 클래스에 대해 별도의 .class 파일을 생성합니다.

예시

// Main class
public class Main {
   class Test1 { // Inner class Test1
   }
   class Test2 { // Inner class Test2
   }
   public static void main(String [] args) {
      new Object() { // Anonymous inner class 1
      };
      new Object() { // Anonymous inner class 2
      };
      System.out.println("Welcome to Tutorials Point");
   }
}

위 프로그램에는 4개의 내부 클래스가 있는 Main 클래스가 있습니다. Test1, Test2, Anonymous 내부 클래스 1익명 내부 클래스 2 . 이 클래스를 컴파일하면 다음 클래스 파일이 생성됩니다.

메인 클래스

Main$Test1.class

Main$Test2.class

메인$1.class

메인$2.class

출력

Welcome to Tutorials Point