Organizing Classes using Packages

  1. To put a class into a package, you must place a line:

    
        package PackageName;   
    
    
    at the start of the Java program file.

  2. Example:

    Example: put the "Sort" class in package "mylib.util"
    
       package mylib.util;
    
       public class Sort // Sort class is now in package "mylib.util"
       {
    
          public static void sortThem(Compare obj[])
          {
             int        N = obj.length;   // Number of objects in array
             boolean    Done;
             int        i, k;
             Compare Help;   // Help variable for swapping
    
             Done = false;
             k = 1;
             while (! Done)
             {  Done = true;
    
                for (i = 0; i < (N - 1); i++)
                {
                   if ( obj[i].compareWith(obj[i+1]) > 0 )
                   {  // Wrong order, swap obj[i] & obj[i+1]
                      Help     = obj[i];
                      obj[i]   = obj[i+1];
                      obj[i+1] = Help;
                      Done = false;
                   }
                }
                k = k + 1;
             }
          }
       }
    
    

  3. Since Sort makes use of the interface Compare, it is appropriate to put Compare in the same package:

    Example: putting the Compare interface in the mylib.util package
    
        package mylib.util;
    
        public interface Compare
        {
           int compareWith(Object other);   
        }
    
    

  4. Classes in package mylib.util must be stored in the subdirectory ..../mylib/util

    Furthermore, the directory that contains ..../mylib must be included in the Java Class Path variable.

  5. The Java Class Path variable in UNIX is called CLASSPATH variable

    Use this UNIX command to update your CLASSPATH:

    
           export CLASSPATH=$CLASSPATH:DIRECTORY_PATH_OF_YOUR_LIBRARY   
    
    

  6. Example:

    Say you want to make a Java library in a directory named "Java" in your home directory.

  7. How to use your new package: