Multiple classes in single file

前端 未结 8 1645
北荒
北荒 2020-11-29 07:57

I\'m having trouble putting multiple classes into a single file. For example, when my file looks like:

public class FirstClass() {}
public class SecondClass(         


        
8条回答
  •  遥遥无期
    2020-11-29 08:35

    One Java file can contain at most one top-level public class. That public top-level class can contain any number of public nested classes.

    You can eliminate your compiler errors by any of the following approaches:

    • Moving the other classes into their own files. For example: FirstClass.java, SecondClass.java, and ThirdClass.java.
    • Nesting the classes whose name is not the file basename. For example:

      public class FirstClass() {
          public class SecondClass() {}   
          public class ThirdClass() {}
      }
      
    • Removing the public qualifier from all but the one class whose name is the file basename. This approach has become less common after the introduction of nested classes in Java v1.1. For example, in file FirstClass.java, you could have:

      public class FirstClass() {}
      class SecondClass() {}   
      class ThirdClass() {}
      

    From the Java Language Specification, section 7.6: Top Level Type Declarations:

    If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

    • The type is referred to by code in other compilation units of the package in which the type is declared.

    • The type is declared public (and therefore is potentially accessible from code in other packages).

提交回复
热议问题