Java Reference
In-Depth Information
Package Declaration
The general syntax for a package declaration is
package <your-package-name>;
A package declaration starts with the keyword package followed with a user-supplied package name. One or
more whitespaces (spaces, tabs, new lines, carriage returns, tabs, and form-feeds) separate the keyword package
and the package name. A semicolon ( ; ) ends the package declaration. For example, the following is the package
declaration for a package named com.jdojo.intro :
package com.jdojo.intro;
Figure 2-2 shows the parts of a package declaration.
A keyword
A programmer-supplied package name
A semicolon is part of the Java
syntax to end a declaration
package com. jdojo. intro;
Figure 2-2. Parts of a package declaration in a Java program
The programmer supplies the package name. A package name may consist of one or more parts. In this example,
two parts are separated by a dot ( . ). This package name consists of three parts: com , jdojo , and intro . There is no
limit on the number of parts in a package name. However, if a package declaration appears in Java source code, it
must contain a package name, which must have at least one part. You can have maximum of one package declaration
in a Java source file (to be more specific, in a compilation unit). The following are some examples of valid package
declarations:
package intro;
package com.jdojo.intro.common;
package com.ksharan;
package com.jdojo.intro;
Why do we use a package declaration? A package is a logical repository for Java types (class, interface, and enum ).
In other words, it provides a logical grouping for related Java types. A package can be stored in a host-specific file
system, a database, or a network location. In a file system, each part of a package name denotes a directory on the host
system. For example, the package name com.jdojo.intro indicates the existence of a directory named com , which
contains a subdirectory jdojo , which contains a subdirectory intro . The directory intro will contain the compiled
Java code. If you are working on Windows, you can think of a directory structure com\jdojo\intro\<<Class File Name>>
whereas on UNIX-like operating systems (for example, Linux, Solaris, and Mac OS X), it will look like com/jdojo/
intro/<<Class File Name>> . A dot, which is used to separate parts in the package name, is treated as a
file-separator character on the host system. A back slash ( \ ) is the file-separator character on Windows, and a forward
slash ( / ) on UNIX-like operating system.
The package name specifies only the partial directory structure in which the compiled Java program (class files)
must exist. It does not specify the full path of the class files. In this example, the package declaration com.jdojo.intro
does not specify where the com directory will be placed. It may be placed under C:\ directory or C:\myprograms directory
or under any other directory in the file system.
 
Search WWH ::




Custom Search