When we write a java program file having extension .java, it
is kept under a particular directory. After compilation, the class file is
created in the same directory. To execute the program we have to specify the
class filename only. If a package is included then the name of the package must
be a directory and after compiling the java file, the class files are stored
under that package directory. To run a class of a particular package the following
commands must be used.
Listing 3
java packagename.classname
However, this command must be given from the directory in
which the package directory is present. For our Firstappplication example, if
we are placing the Example package under C directory then we can set the
classpath as:
Listing 4
The above statement sets the classpath to point at two
places: .(dot) and C directory. Dot is used as an alias to represent the current
directory. Semicolon is used to separate the directory location in case class
files are placed at many locations.
As mentioned earlier, if we have placed our java file inside
Example directory (which is placed inside C directory), for compiling we need
to go to the Example directory and write the command as shown below.
Listing 5
C:\Example\javac Firstapplication.java
If we try to run the same by using java Firstapplication,
then we get an error because the Firstapplication program is now a part of the package
Example. For running the application we need to specify the fully qualified
class name. Let us take another example; we have a package called Hello
containing the file HelloWorld.java within Example package. Whenever we want to
reference the HelloWorld class, we have to use Example.Hello.HelloWorld as its
fully classified class name. For using the classes stored in a package, either
we can declare the fully classified class name as shown:
Listing 6
//for first package
Example.Firstapplication firstApplication = newExample.Firstapplication();
//for the subpackage
Example.Hello.HelloWorld helloWorld = new Example.Hello.HelloWorld();
or we can use the import statement:
Listing 7
import.Example.*; //import all the public classes inside Example package
import.Example.Hello.*; //import all the public classes inside Hello package
import.Example.Firstapplication; //import only Firstapplication inside Example
By using the first import statement we can use the public
classes present inside Example package but not the classes of Hello package.