Wrapping Your Own Packages

Java does not limit you to using only the system supplied packages. You can write your own as well. You write packages just like you write any other Java program. Make sure you follow these rules:

  1. There must be no more than one public class per file.
  2. All files in the package must be named classname.java where classname is the name of the single public class in the file.
  3. At the very top of each file in the package, before any import statements, put the statement
package myPackage;

To use the package in other programs, compile the .java files as usual and then move the resulting .class files into the appropriate subdirectory of one of the directories referenced in your CLASSPATH environment variable. For instance if /home/elharo/classes is in your CLASSPATH and your package is called package1, then you would make a directory called package1 in /home/elharo/classes and then put all the .class files in the package in /home/elharo/classes/package1.

For example,

package com.macfaq.net;

import java.net.*;

public class URLSplitter {

  public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
      try {
        URL u = new URL(args[i]);
        System.out.println("Protocol: " + u.getProtocol());
        System.out.println("Host: " + u.getHost());
        System.out.println("Port: " + u.getPort());
        System.out.println("File: " + u.getFile());
        System.out.println("Ref: " + u.getRef());
      catch (MalformedURLException e) {
        System.err.println(args[i] + " is not a valid URL");



$ javac -d /home/elharo/classes URLSplitter.java

The -d flag to the compiler tells it to create the necessary directories such as elharo/net in the specified directory. In this example, URLSplitter.class is placed in /home/elharo/classes/com/macfaq/net. You can use the usual shell syntax such as . for the current directory or ~ for your home directory.

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999 Elliotte Rusty Harold
Last Modified October 21, 1999