Programing

Java 파일에 둘 이상의 클래스가있을 수 있습니까?

crosscheck 2020. 8. 18. 07:13
반응형

Java 파일에 둘 이상의 클래스가있을 수 있습니까?


Java 파일에 둘 이상의 클래스를 갖는 목적은 무엇입니까? 저는 Java를 처음 사용합니다.

편집 : 퍼블릭 클래스 안에 내부 클래스를 만들어서 달성 할 수 있습니다. 맞죠?


예, 그럴 수 있습니다. 그러나 파일 하나의 공개 최상위 클래스 만있을 수 .java있으며 공개 최상위 클래스는 소스 파일과 동일한 이름을 가져야합니다.

하나의 소스 파일에 여러 클래스를 포함하는 목적은 관련 지원 기능 (내부 데이터 구조, 지원 클래스 등)을 기본 공용 클래스와 함께 묶는 것입니다. 이 작업을 수행하지 않는 것은 항상 괜찮습니다. 유일한 효과는 코드의 가독성에 영향을줍니다.


공용 클래스를 구현하려면 해당 클래스와 이름이 같은 파일에서이를 구현해야합니다. 단일 파일에는 하나의 공용 및 선택적으로 일부 개인 클래스가 포함될 수 있습니다. 이는 클래스가 공용 클래스에 의해 내부적으로 만 사용되는 경우에 유용합니다. 또한 공용 클래스에는 내부 클래스도 포함될 수 있습니다.

단일 소스 파일에 하나 이상의 개인 클래스가있는 것이 좋지만 내부 및 익명 클래스를 대신 사용하는 것이 더 읽기 쉽습니다. 예를 들어 익명 클래스를 사용하여 공용 클래스 내에 Comparator 클래스를 정의 할 수 있습니다.

  public static Comparator MyComparator = new Comparator() {
    public int compare(Object obj, Object anotherObj) {

    }
  };

Comparator 클래스는 일반적으로 공개되기 위해 별도의 파일이 필요합니다. 이런 식으로 사용하는 클래스와 함께 번들로 제공됩니다.


예, 원하는만큼!

그러나 모든 파일에 하나의 "공용"클래스 만 있습니다.


.java 파일을 컴파일 단위라고합니다. 각 컴파일 단위에는 원하는 수의 최상위 클래스 및 인터페이스가 포함될 수 있습니다. 공개 최상위 유형이없는 경우 컴파일 단위의 이름은 무엇이든 지정할 수 있습니다.

//Multiple.java
//preceding package and import statements

class MyClass{...}
interface Service{...}
...
//No public classes or interfaces
...

컴파일 단위에는 하나의 공용 클래스 / 인터페이스 만있을 수 있습니다. cu는이 공개 최상위 유형과 똑같이 이름을 지정해야합니다.

//Test.java
//named exactly as the public class Test
public class Test{...}
//!public class Operations{...}
interface Selector{...}
...
//Other non-public classes/interfaces

주요 방법에 대한 중요 사항-1 부

2 부

(2 부에서 다루는 클래스 수 및 액세스 수준에 대한 포인트)


익명 내부 클래스 외에도 공용 인터페이스를 구현하는 개인 내부 클래스가 사용됩니다 ( 이 문서 참조 ). 외부 클래스는 내부 클래스의 모든 개인 필드 및 메서드에 액세스 할 수 있습니다.

이를 통해 둘 중 하나의 구현을 노출하지 않고도 모델 및 해당 뷰와 같이 밀접하게 연결된 두 클래스를 만들 수 있습니다. 또 다른 예는 컬렉션과 이터레이터입니다.


일반적으로 파일 당 하나의 클래스가 있어야합니다. 이러한 방식으로 구성하면 클래스를 검색 할 때 해당 이름의 파일 만 검색하면된다는 것을 알 수 있습니다.

예외는 클래스가 하나 이상의 작은 도우미 클래스를 사용하여 가장 잘 구현되는 경우입니다. 일반적으로 해당 클래스가 동일한 파일에있을 때 코드를 따르는 것이 가장 쉽습니다. 예를 들어, 메소드 호출간에 일부 데이터를 전달하려면 작은 '튜플'래퍼 클래스가 필요할 수 있습니다. 또 다른 예는 Runnable 또는 Callable을 구현하는 '작업'클래스입니다. 너무 작아서 부모 클래스를 만들고 호출하는 것과 가장 잘 결합 될 수 있습니다.


예, 둘 이상의 공용 클래스를 만들 수 있지만 중첩 된 클래스 여야합니다.

public class first {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }

    public class demo1
    {

        public class demo2
        {

        }
    }
}

예 200 % ,

예:

class A {
 void methodDeclaration() { System.out.println("!!!"); }
 }
 class B {
 public static void main(String[] args) {
new A().methodDeclaration();
    }
 }

예, 가능하지만 Java 컴파일러가 Public 클래스 이름과 동일한 이름의 .Class 파일을 생성하므로 패키지 내부에는 1 개의 공용 클래스 만있을 수 있습니다. 따라서 공용 클래스가 2 개 이상이면 선택하기가 어렵습니다. 컴파일러는 클래스 파일의 이름이어야합니다.


Varies ... 한 가지 예는 익명의 클래스 가 될 것입니다 (이벤트 리스너 등을 사용할 때 많이 접하게 될 것입니다).


".java 파일 당 하나의 NON-STATIC 최상위 공개 클래스 만있을 수 있습니다"라고 생각합니다. 그렇지 않습니까?


If you want to implement a singleton, that is a class that runs in your program with only one instance in memory throughout the execution of the application, then one of the ways to implement a singleton is to nest a private static class inside a public class. Then the inner private class only instantiates itself when its public method to access the private instance is called.

Check out this wiki article,

https://en.wikipedia.org/wiki/Singleton_pattern

The concept takes a while to chew on.


In a .java file,there can be only one public top-level class whose name is the same as the file, but there might be several public inner classes which can be exported to everyone and access the outer class's fields/methods,for example:AlertDialog.Builder(modified by 'public static') in AlertDialog(modified by 'public')


Yes You can have more than one Class in one .Java file . But You have make one of them Public . and save .java file with same name as name of public class. when you will compile that .java file than you will get Separate .class files for each class defined in .java file .

Apart from this there are too many method for defining more than one class in one .java file .

  1. use concept of Inner Classes.
  2. Use Concept of Anonymous Classes .

Yes ! .java file can contain only one public class.

If you want these two classes to be public they have to be put into two .java files: A.java and B.java.


Yes you can have more than one class inside a .java file. At most one of them can be public. The others are package-private. They CANNOT be private or protected. If one is public, the file must have the name of that class. Otherwise ANYTHING can be given to that file as its name.

Having many classes inside one file means those classes are in the same package. So any other classes which are inside that package but not in that file can also use those classes. Moreover, when that package is imported, importing class can use them as well.

For a more detailed investigation, you can visit my blog post in here.


There can only be one public class top level class in a file. The class name of that public class should be the name of the file. It can have many public inner classes.

You can have many classes in a single file. The limits for various levels of class visibility in a file are as follows:

Top level classes:
1 public class
0 private class
any number of default/protected classes

Inner classes:
any number of inner classes with any visibility (default, private, protected, public)

Please correct me if I am wrong.

참고URL : https://stackoverflow.com/questions/968347/can-a-java-file-have-more-than-one-class

반응형