A package is a group of related classes and interfaces. Packages help organize your code and provide another layer of encapsulation.
Package fundamentals
- provides a mechanism by which related pieces of a program can be organized as a unit
- a package participates in Java's access control mechanism.(be encapsulated)
- when a class is defined within a package, the name of that package is attached to the class, thus avoiding name collisions with other classes that have the same name but are in other packages.
- a way to keep private
Defining a Package
- the name of a class that you put into the package will be in that package's namespace.
package mypack; - More than one file can include the same package statement. The package statement simply specifies to which package the file belongs.
- Hierarchy
package alpha.beta.gamma;must be store in the .../alpha/beta/gamma
Finding Packages and Classpath
where to look for your package :
- the run-time system uses the current working directory as its starting point. If your package in subdirectory of the current directory, it will be found
- specify a directory path or paths by setting the CLASSPATH environmental variable.
- use -classpath option with java and javac to specify the path to your classes.
package mypack;
In order for a program to find mypack, one of three things must be true:
The program can be executed from a directory immediately above mypack, or CLASSPATH must be set to include the path to mypack, or the -classpath option must specify the path to mypack when the program is run via java.
A Short Package Example
// A short package demonstration.
package bookpack; //this file is part of the bookpack package.
class Book {
private String title;
private String author;
private int pubDate;
Book(String t, String a, int d) {
title = t;
author = a;
pubDate = d;
}
void show() {
System.out.println(title);
System.out.println(author);
System.out.println(pubDate);
}
}
class BookDemo {
public static void main(String[] args) {
Book[] books = new Book[5];
books[0] = new Book("The Art of Computer Programming, Vol 3",
"Knuth", 1973);
books[1] = new Book("Moby Dick",
"Melville", 1851);
books[2] = new Book("Thirteen at Dinner",
"Christie", 1933);
books[3] = new Book("Red Storm Rising",
"Clancy", 1986);
books[4] = new Book("On the Road",
"Kerouac", 1955);
for(int i=0; i < books.length; i++) {
books[i].show();
System.out.println();
}
}
}

As explained, BookDemo and Book are now part of the package bookpack. This means that BookDemo cannot be executed by itself. That is, you cannot use this command line:
java BookDemo
Packages and member access

A Package Access Example
// Book recoded for public access.
// this program is stored as Book.java in bookpack
package bookpack;
public class Book {
//Book and its members must be public in order to be used by other packages.
private String title;
private String author;
private int pubDate;
// Now public.
public Book(String t, String a, int d) {
title = t;
author = a;
pubDate = d;
}
// Now public.
public void show() {
System.out.println(title);
System.out.println(author);
System.out.println(pubDate);
}
}
// This class is in package mypack.
package mypack;
// Use the Book Class from bookpack.
class UseBook {
public static void main(String[] args) {
bookpack.Book[] books = new bookpack.Book[5];
//qualify Book with its package name: bookpack
books[0] = new bookpack.Book("The Art of Computer Programming, Vol 3",
"Knuth", 1973);
books[1] = new bookpack.Book("Moby Dick",
"Melville", 1851);
books[2] = new bookpack.Book("Thirteen at Dinner",
"Christie", 1933);
books[3] = new bookpack.Book("Red Storm Rising",
"Clancy", 1986);
books[4] = new bookpack.Book("On the Road",
"Kerouac", 1955);
for(int i=0; i < books.length; i++) {
books[i].show();
System.out.println();
}
}
}

Understanding Protected Members
// Make the instance variables in Book.java protected.
package bookpack;
public class Book {
// these are now protected
protected String title;
protected String author;
protected int pubDate;
public Book(String t, String a, int d) {
title = t;
author = a;
pubDate = d;
}
public void show() {
System.out.println(title);
System.out.println(author);
System.out.println(pubDate);
}
}
//this program is stored in bookpackext
// Demonstrate protected.
package bookpackext;
//this is a sub class of Book
class ExtBook extends bookpack.Book {
private String condition;
public ExtBook(String t, String a, int d, String c) {
super(t, a, d);
condition = c;
}
public void show() {
super.show();
System.out.print("Condition is " + condition);
System.out.println();
}
public String getCondition() { return condition; }
public void setCondition(String c) { condition = c; }
/* These are OK because subclass can access
a protected member. */
// Access to Book's members is allowed for subclasses.
public String getTitle() { return title; }
public void setTitle(String t) { title = t; }
public String getAuthor() { return author; }
public void setAuthor(String a) { author = a; }
public int getPubDate() { return pubDate; }
public void setPubDate(int d) { pubDate = d; }
void wontWork() {
bookpack.Book b = new bookpack.Book("sometitle", "someauthor", 1961);
b.title = "newtitle"; // Error!
}
/*However, a subclass in a different package does not have the ability to
access a protected member of its superclass through an object of that superclass.
A subclass can use a protected member for the purpose of implementing the subclass,
but not as a means of getting around the protected access limitation in general.
*/
}
class ProtectDemo {
public static void main(String[] args) {
ExtBook[] books = new ExtBook[5];
books[0] = new ExtBook("The Art of Computer Programming, Vol 3",
"Knuth", 1973, "well used");
books[1] = new ExtBook("Moby Dick",
"Melville", 1851, "like new");
books[2] = new ExtBook("Thirteen at Dinner",
"Christie", 1933, "fair");
books[3] = new ExtBook("Red Storm Rising",
"Clancy", 1986, "good");
books[4] = new ExtBook("On the Road",
"Kerouac", 1955, "fair");
for(int i=0; i < books.length; i++) {
books[i].show();
System.out.println();
}
// Find condition of Moby Dick.
System.out.print("Condition of Moby Dick is ");
for(int i=0; i < books.length; i++)
if(books[i].getTitle() == "Moby Dick")
System.out.println(books[i].getCondition());
// books[0].title = "test title"; // Error - not accessible
// Access to protected field not allowed by non-subclass
}
}

Importing Packages
Here is the general form of the import statement:
import pkg.classname;
import mypack.MyClass;
import mypack.*;
If you want to import the entire contents of a package, use an asterisk (*) for the class name.
- In the first case, the MyClass class is imported from mypack.
- In the second, all of the classes in mypack are imported.
In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions. You can use import to bring the bookpack package into view so that the Book class can be used without qualification. To do so, simply add this import statement to the top of any file that uses Book.
// Demonstrate import.
package mypack;
import bookpack.*;
//Import bookpack.
// Use the Book Class from bookpack.
class UseBook {
public static void main(String[] args) {
Book[] books = new Book[5];
// Now, you can refer to Book directly, without qualification.
// no need : bookpack.Book[] books = new bookpack.Book[5];
books[0] = new Book("The Art of Computer Programming, Vol 3",
"Knuth", 1973);
books[1] = new Book("Moby Dick",
"Melville", 1851);
books[2] = new Book("Thirteen at Dinner",
"Christie", 1933);
books[3] = new Book("Red Storm Rising",
"Clancy", 1986);
books[4] = new Book("On the Road",
"Kerouac", 1955);
for(int i=0; i < books.length; i++) {
books[i].show();
System.out.println();
}
}
}
Importing Java's standard Packages
-
class library => Java API (Application Programming Interface)
API
Static Import
Java supports an expanded use of the import keyword. By following import with the keyword static, an import statement can be used to import the static members of a class or interface. This is called static import, and it was added to Java by JDK 5. When using static import, it is possible to refer to static members directly by their names, without having to qualify them with the name of their class. This simplifies and shortens the syntax required to use a static member.
// Find the solutions to a quadratic equation.
class Quadratic {
public static void main(String[] args) {
// a, b, and c represent the coefficients in the
// quadratic equation: ax2 + bx + c = 0
double a, b, c, x;
// Solve 4x2 + x - 3 = 0 for x.
a = 4;
b = 1;
c = -3;
// Find first solution.
x = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
System.out.println("First solution: " + x);
// Find second solution.
x = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
System.out.println("Second solution: " + x);
}
}
// Use static import to bring sqrt() and pow() into view.
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
class Quadratic {
public static void main(String[] args) {
// a, b, and c represent the coefficients in the
// quadratic equation: ax2 + bx + c = 0
double a, b, c, x;
// Solve 4x2 + x - 3 = 0 for x.
a = 4;
b = 1;
c = -3;
// Find first solution.
x = (-b + sqrt(pow(b, 2) - 4 * a * c)) / (2 * a);
System.out.println("First solution: " + x);
// Find second solution.
x = (-b - sqrt(pow(b, 2) - 4 * a * c)) / (2 * a);
System.out.println("Second solution: " + x);
}
}
