Wednesday, June 19, 2013

Java Packages


  • Packages are used to group related classes together.
  • The java source directory structure mirrors the package naming.
  • When creating package, the package statement appears as the first statement in source file.
  • The user of a class in a package must import the package.
  • Packages can be compressed into Jar file; to see contents of Jar file use  jar -tvf fileName.jar
  • Jar files may also include directories, subdirectories to represent class and package hierachy
  • If the package is stored inside a jar file, we have to include the jar file with its extension (.jar) in the CLASSPATH. However, if the package is a plain directory, we just put the name of directory into the CLASSPATH.
// search for packages from the current directory as wells as from myclass directory of C drive
set CLASSPATH=.;C:\myclasses;

// to access classes in a JAR file
set CLASSPATH=.;D:\JSDK2.0\lib\jsdk.jar;

Once in a package either use fully qualified class names (e.g. System.Awt.Font) or import the package (then we can simply reference Font).

import.util.Scanner;  // Import a particular class
import java.awt.*;   // Import all classes java.awt
import java.awt.event.*;
import java.javax.swing.*;