While writing source code, following are the rules of declaring package, import statement and class:
- There can be only one
public
class per source code file. It means, in one .java file, there can not be two or morepublic
class file. There should only be onepublic
class in a source code file. - You can declare multiple non
public
class in a single source code file. - If there is a
public
class in a source code file, then the name of the file should be same asclass
name. For example:
public class Foo { //your code }
This class should be saved as Foo.java
as the the source code has class which is public
.
- Comments can appear at the beginning or the end of file.
- If the class is a part of package, then
package
statement should be the first statement of the file.package
statement should come before anyimport
statement. import
statement should come afterpackage
statement and before class declaration. If there is nopackage
statement thenimport
statement should be the first statement in the source code.- If there are multiple non
public
classes in a source code file, the source code file can be saved as a different name that does not match with any of the class in the file.