I'm using maven to build the project and compile failed because I put class Test2
in Test.java
,
but is it because of maven or simply because java itself doesn't support this?
BTW,how can I open a maven project with eclipse?
A public
class called ClassName
must (in most cases) be defined in a file called ClassName.java
.
Edit
Although this is not a requirement of the Java language, most (if not all) implementations of Java, the above mentioned relationship between the class name and file name must hold, or a compiler error will result.
(For more information, please refer to Jon Skeet's answer.)
The reason for this can be found by reading Section 7.2: Packages of The Java Language Specification, Third Edition.
In the section, it describes how the directory structure can be mapped to a fully-qualified class name in Java, which leads to a requirement that the .class
file which contains the bytecode for a class must reside in a path that resembles that of the fully-qualified class name.
The original answer which incorrectly stated that the naming scheme is a requirement has been edited.
The Java Language Specification itself doesn't actually require this - but it explicitly allows file-system-based implementations to do so, and most do.
From section 7.6:
When packages are stored in a file system (§7.2.1), 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).
This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.
When packages are stored in a database (§7.2.2), the host system must not impose such restrictions. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.
For practical purposes I think it's reasonable to basically assume that it's required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With