PkgDemo - Shows how to make and use Java Packages

In Java, a package is a subdirectory of classes.  Just like the .java and .class files must be named the same as the Java class within them, so too packages must be named the same as the subdirectory containing them.

In the following example there is a package called "utilities" (a subdirectory called "utilities").  It contains a class called "MiscKit".  MiscKit is intended as a miscellaneous toolkit, a class with a number of static utility methods.

Back in the current directory (the directory which has the utilities subdirectory), there is a Java application PkgDemo.java.  This non-GUI program will import utils.MiscKit and use its static member utils.MiscKit.hello(), which simply prints out a short message to System.out.

If you need help using Windows command line, see our class resource Windows Shell, or find a cmd.exe tutorial on the Internet.

DOS session capture of package creation demo
Sample DOS session showing the contents of various directories








You can use the DOS command md or mkdir to create a new directory.



You can use any editor this way, as long as it can be found on PATH.























Notice how MistKit.java was automatically compiled when PkgDemo.java was.  javac will automatically re-compile MiscKit.java if it is newer than MiscKit.class, or if MiscKit.class is missing.




// Demonstration of Java packages.
// (C) 1999 by Wayne Pollock, Tampa FL USA.
// All Rights Reserved.

import utilities.MiscKit;  // or: import utilities.*;

public class PkgDemo
{
   public static void main ( String [] args )
   {
      MiscKit.hello();
   }
}

Download PkgDemo.java


// Demonstrates Java packages.
// (C) 1999 by Wayne Pollock, Tampa FL USA.
// All Rights Reserved.

package utilities;

public class MiscKit
{
   // A static method which prints "hello": 
   public static void hello ()
   {
      System.out.println( "Hello, World!" );
   }
}

Download MiscKit.java

(Put in a subdirectory called "utilities".)


How to deploy a package to the extensions directory:

This is a two step process.  First you must put your package into a jar (Java ARchive) file.  Then you must copy that jar file into the correct extensions directory.

C:\Temp>jar -cvf utilities.jar utilities
added manifest
adding: utilities/(in = 0) (out= 0)(stored 0%)
adding: utilities/MiscKit.class(in = 407) (out= 290)(deflated 28%)

C:\Temp>copy utilities.jar "\Program Files\Java\jre1.6.0\lib\ext"
        1 file(s) copied.

C:\Temp>copy utilities.jar C:\java\jre\lib\ext
        1 file(s) copied.

C:\Temp>