Witscale Test Center

8.1 Java source file > 8.1.2 Declaration rules for package and import statements


8.1.2 Declaration rules for package and import statements

The Java source file is structured to have three types of top-level declarations, the package declaration, import statements and class declarations. None of them has to be present in the source file. However, if they are present, they must appear in the following order: 

§         The package declaration must come first…

§         …followed by the import statements

§         …followed by the class definitions.

Comments and white spaces can appear before, after or in between these declarations. If you have the package and import statements, then they are applicable to all the classes declared in that java source file. Listing 8.1 shows the contents of a java source file with two top-level classes.

 


We know that a java source file can have multiple top-level classes. The source file in the listing has two top-level classes, Test and Helper. We also know that there can be only one public top-level class. In the listing, it is the Test class. Since this source file has a top-level public class, the name of the source file and the name of the top-level public class must be the same. Therefore, the listing 8.1 must reside in file named Test.java. In Java, a compilation of any source file creates a .class file for every class declared in it. Since Test.java has two class declarations, two class files will be created ( Test.class and Helper.class) after its compilation.

The package declaration in Test.java is applicable to both the classes Test and Helper. In other words, they both belong to the same package. There are also two import statements in the listing. The first import statement imports the java.util.Date class. Therefore both the classes, Test and Helper can refer to java.util.Date as simply Date. The second import statement imports the entire java.io package. Therefore, both of them can reference any class from java.io package by specifying only its name instead of the fully qualified name.

Now you know how a java source file is structured and the simple rules enforcing that structure. But, defining class definitions in a java source file does not make it executable after compilation. You cannot run the Test or Helper classes as Java application unless they have a special  main method defined.