Summary there can be more than one class in a Java source file, but why is there only one public class? And when this class is decorated as public, why should the source file name be the same as the class name?

Source: Internet
Author: User

A passage in Java programming thought:

When writing a Java source code file, this file is often referred to as a compilation unit (sometimes referred to as a translation unit). Each compilation unit must have a suffix name. java, and within the compilation unit you can have a public class that has the same name as the file (including case, but not the suffix of the file. Java). Each compilation unit can have only one public class, or the compiler will not accept it. If there are additional classes in the compilation unit, these classes cannot be seen in the world outside the package because they are not public and are primarily used to provide support for the primary public class.

Understand:

Each Java file that is written is a Java compiler compiled Java source code of a compilation unit, how to compile it? This needs to understand how the Java compiler works. Each compiler compiles a. java file (the compilation unit), and each class in the. java file has an output file with the same name as each class in the. java file, with just one more suffix. class. Therefore, after compiling a small number of. java files, you get a large number of. class files. In a. java file, you do not have to include the public class. The public class is simply used to indicate that there is an open interface in the compilation unit.

However, if you have a public class, you can have at most one, and you must have the same name as the file name. Because the Java compiler will determine that if there is a public class, the class loader needs to load the class as an external interface to the compilation unit. For a public class, it can be referenced by any class in the project, just before using it to import the corresponding class file, the class name and the file name one by one can be convenient for the virtual machine in the corresponding path (package name) to find the corresponding class information. If you don't do it, it's hard to find it, and it's going to cost a lot. It is run by calling the main () function.

Personal Summary:

1, Java compiler at compile time, if the entire Java file (compilation unit) does not have the public class (external Open Interface Class), The ClassLoader does not need to directly load all the bytecode files (. class files) generated by the compilation unit, so it is not necessary to look for the location of the compiled bytecode file. and the class name and file name are consistent in order to facilitate the virtual machine in the corresponding path to find the corresponding class corresponding to the bytecode file. Therefore, in a Java file without the public class, the file name is not associated with the class names.

2, if the compilation unit contains the public class, then the corresponding bytecode file of the class when it needs to be loaded by the class loader, it is necessary to let the ClassLoader know the location of the bytecode file, so make sure that the class and the Java file name consistent. At the same time, if there are two public classes in the same file, and a file can only have one name, so the name of the two public class can not be the same as the file name, which causes at least one of the public class at compile time compile does not pass, generating similar hints

3 Add one point: if the inner class of a public class exists, then the Otherclass&innerclass.class file is generated in order to identify the inner class.

The Java interpreter runs as follows: First, identify the environment variable classpath (which can be set by the operating system, and sometimes through the installer-to install Java on your machine or Java-based tools). Classpath contains one or more directories that are used as the root directory for finding. class files. Starting at the root, the interpreter gets the name of the package and replaces each period with a backslash to produce a path name from the classpath root (hence, the packages Foo.bar.baz becomes foo\bar\baz or Foo/bar/baz or other, It all depends on the operating system). The resulting path is connected to each of the different items in the classpath, where the interpreter looks for the. class file that is related to the class name you are creating (the interpreter also looks for some standard directories that involve the location of the Java interpreter).

--------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------

Another related article:

Idle all right, see a post on the internet asked why a Java source file can only have one public class?
Someone on the net answered: http://topic.csdn.net/t/20060528/22/4784755.html
, each compilation unit (file) can have only one public class. What this means is that each
A unit can have only one open interface, and this interface is represented by its public class.

I think this is a conclusion from software architecture design and security design. Or the designers of Java are considering this. Maybe it's really a spec, but I didn't find the information.

I don't know if I have this conversation. If you have a known colleague to give a source of information?

The experiment is as follows:
Test3.java source file:
Class Test1
{
int i = 1;


}

Class Test2
{
int i = 2;
public static void Main (string[] args)
{
System.out.println ("Main method");
}
}

C:/javatest>javac Test3.java

C:/javatest>java Test2
Main method

Note: Compile without error, note is running Test2 because there is no Test3.class file generated. Error if running TEST3

The class could not be found
C:/javatest>java Test3
Exception in thread "main" java.lang.NoClassDefFoundError:Test3
caused By:java.lang.ClassNotFoundException:Test3
At Java.net.urlclassloader$1.run (Unknown Source)
At java.security.AccessController.doPrivileged (Native Method)
At Java.net.URLClassLoader.findClass (Unknown Source)
At Java.lang.ClassLoader.loadClass (Unknown Source)
At Sun.misc.launcher$appclassloader.loadclass (Unknown Source)
At Java.lang.ClassLoader.loadClass (Unknown Source)
Could not find the main class:test3. Program would exit.
The reason for this error is simple: the class loader in the JVM cannot find the Test3.class

It also shows that the class containing main () is not necessarily public if it wants to run.

In the second edition of in-depth JVM, there is this sentence:
The Java Virtual machine instance runs a Java program by invoking the main () of a class, and the main () must be public
static void and receives an array of strings as arguments, any class that has such a main () can be used as a Java thread

The starting point of the sequence.
It is not said that the class owning the main () method must be a public class.


Test7.java source file:
Class Test5
{
int i = 1;


}

public class Test6
{
int i = 2;
public static void Main (string[] args)
{
System.out.println ("Main method");
}
}

If you run Test7.java error:
C:/javatest>javac Test7.java
Test7.java:8: Class Test6 is public and should be declared in a file named Test6.java
public class Test6
^1 Error
This shows that the file name must match the class name of the public class (if there is a public class in the file)

Here you can see if there are more than one public class, then the file name should be which public class? Obviously a Java source file

There can be only one public class.

So the summary is as follows: There can be at most one public class in a Java source file, and when there is a public class, the source file name must be

Must be consistent or not compile, if there is no public class in the source file, there is no consistency requirement in the file name and class.
The main () does not have to be placed in the public class to run the program.

The above is the conclusion through the experiment, the individual thinks to here already can, if must ask the end, may want to question the Java

The designer of the platform. Perhaps, people will say: This is the design of Java and the internal architecture of the JVM caused by the design, this is a rule

Fan, there is no reason why.

Summary there can be more than one class in a Java source file, but why is there only one public class? And when this class is decorated as public, why should the source file name be the same as the class name?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.