Index

Overview


We use Java packages is to organize code.

Let's do a demo of nested packages (sub-packages/dirs nested within the parent "shapes" package).

Say we have these these two directories:

\Work\Foo\shapes\model
\Work\Foo\shapes\test


Let's say "shapes" is the root-package.
Our package names are "model" and "test", and our two package paths are:


Circle.java



  • This file is in the "shapes\model" directory.
  • Notice the package statement matches the directory.
package model;

/**
Minimal Circle
*/
public class Circle {
	private int radius;
	public Circle(int aRadius) {
		this.radius = aRadius;
	}
	public String toString() {
		return "Circle with radius = " + this.radius;
	}
}

CircleTest.java



  • This file is in the "shapes\test" directory.
  • We want to use "Circle" so we import it using the package path
package test;

import model.Circle;

public class CircleTest {

	public static void main(String[] args) {
		CircleTest test = new CircleTest();
		test.test1();
		test.test2();
	}

	public void test1() {
		Circle circ = new Circle(3);
		System.out.println(circ.toString());
	}

	public void test2() {
		Circle circ = new Circle(10);
		System.out.println(circ.toString());
	}

}

Compiling


We need to tell Java where to start searching for the package path (which directory).


The "cp" or "classpath" switch/option tells javac (compiler) where to search for packages.
We can run this command from any directory
ECHO OFF

REM Place this script into your classpath directory
REM "." Means current directory (script is in classpath dir)
REM We could also replace "." with absolute path to our classpath dir

javac -cp "." "model\Circle.java"
javac -cp "." "test\CircleTest.java"

PAUSE

Running


The Java run command "java" is similar to "javac".


  • The "cp" or "classpath" switch/option tells java (runner) where to search for packages.
  • We give the full path to the runnable class including the package path
ECHO OFF

REM Place this script into your classpath directory
REM "." Means current directory (script is in classpath dir)
REM We could also replace "." with absolute path to our classpath dir

java -cp "." test.CircleTest

PAUSE

Source Code


Here is the source code for the "shapes" package.