Java Reference
In-Depth Information
an organization. Or I could (and do) use some other string of names that make me relatively
sure that the package will be unique. Email names work just fine, or personal domains. It is
far more common for individuals to have network-unique names, so there is always a starting
prefix that you can use for your package names.
Every source file in Java declares a package, even those that try not to. If you don't have a
package declaration at the beginning of a file, the contents of that file are placed in the default
unnamed package. The unnamed package is a form of namespace limbo, where code written
by confused, obstinate, or lazy programmers is placed until they evolve to a higher life form.
There is no good reason to place anything that you do in the unnamed package, so just say no.
Items within a single package can refer to each other by name. From another package, one
way you can refer to an entity is by using the fully qualified name of the entity, which is the
package name of the package the entity is in, followed by a “.”, followed by the name of the
entity. So if my com.sun.foo.bar package contains a class by the name of baz , I can refer
to that class from outside the package using the name com.sun.foo.bar.baz . This is fine if I
only want to refer to the class baz once or twice, but if I want to refer to class baz more often,
this gets cumbersome.
The alternative is to import the name of baz into my current namespace. This is done,
not surprisingly, by using the import statement. An import statement takes the form of the
keyword import , followed by the fully qualified name that you want to import into the current
namespace, followed by a semicolon. Importing the name in such a way makes it visible in
the namespace of the source file, and also tells the compiler that it needs to refer (and perhaps
compile) the package from which the import comes. So if I want to refer to baz a number of
times in my source, I can include the statement:
import com.sun.foo.bar.baz;
and then I can simply use the name baz in my code. I could also import the entire namespace
by having the statement:
import com.sun.foo.bar.*;
This would make all of the names defined in the namespace com.sun.foo.bar visible to this
code. This more general form of the import statement is quite popular, but should be avoided
if you can. By importing more than you need, you are polluting the namespace of your own
code, and making it more likely that you will clash with some name that is defined in the other
Search WWH ::




Custom Search