Naming Packages

As you saw earlier name space conflicts arise if two pieces of code declare the same name. Java keeps track of what belongs to each package internally. Thus if Sun decides to put a Website class in java.lang in Java 2.0, it won't conflict with a Website class defined in an http package. Since they're in different packages Java can tell them apart. Just as you tell John Smith apart from John Jones by their last names, so too does Java tell two Website classes apart by their package names.

However this scheme breaks down if two different classes share the same package name as well as class name. In a world in which many different packages can be downloaded from many different sites, all landing in the user's CLASSPATH, it's not unthinkable that two different people might write packages called http with a class called Website.

To ensure that package names don't conflict with each other, Sun asks that you prefix all your packages with a reversed domain name. Thus if your domain name is poly.edu, your package names should begin with edu.poly. Within that domain you are responsible for making sure that no one else writes a package that conflicts with yours.

If you don't have a personal domain name, only an account with an Internet service provider, then add your username to this as well. For instance under this scheme the package prefix for foo@utopia.poly.edu would be edu.poly.utopia.foo.

This is primarily of interest to applet writers, not applet users. If you're surfing the net and you load one applet from MIT that has a http.Website class and another from Polytechnic that has a different http.Website class, Java can still tell them apart because before it runs any package it downloads off the net it prefixes everything with the site from which it got it. In other words it sees edu.poly.www.http.Website and edu.mit.www.http.Website. It's only when you download a package manually and install it in one directory in your CLASSPATH and install another package elsewhere in your CLASSPATH that real name conflicts can arise if packages aren't carefully prefixed with a domain or email address.


Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified September 11, 1997