Before you start reading this, I highly recommend that you open the image below and refer to it from time to time.
http://img4.imageshack.us/img4/3820/packaging.png
NOTE: Chrome users might experience problems with the link above. In that case, use IE
I’m using Ivor Horton’s example of Point and Line class but with a few changes. The changes aren’t anything major; I have just excluded a few methods and added a couple of mine.
With that said, let’s get into the actual process of packaging up the two classes. Here is a summary of where things are located
Name Of My Package : Geometry
Location : D:\MyPackages
Name Of My Source File : TryGeometry.java
Location : D:\JavaSource
The ‘Geometry’ package is actually a folder by the name ‘Geometry’ that has both Line.java and Point.java source files in it. For the package to work, we need to convert these into .class files which, by default, will be stored in that very folder.
Step1: Navigate to WITHIN the Geometry folder. In other words, make it the current folder.
Step 2: To compile the classes in the package , you need to set the classpath. The classpath will be the full path to the *parent* of Geometry folder. In this case, D:\MyPackages.
Execute the command:
Code:
javac –classpath “D:\MyPackages” *.java
I know that since Line and Point are inter-related classes they will get compiled even if only Line.java is compiled but I preferred using wildcard operator.
Step 3: Navigate to the folder where your source file is located. In this case, D:\JavaSource.
Step 4: to compile the TryGeometry.java source file , you will have to provide the path to your package , compulsorily , as they are not a part of Java Standard Package or been made extension to Java Standard Package
Execute the command :
Code:
javac –classpath “D:\MyPackages” TryGeometry.java.
Again, classpath will be to the *parent* of the package
Step 5: To execute , you need to insert a period followed by semicolon and the package path in classpath.
Execute the command :
Code:
java –classpath “.;D:\MyPackages” TryGeometry
The period is necessary because without this , java looks for .class file of TryGeometry in the package’s folder.
I hope that sums it up :)