Learn Java packages in 21 seconds
A package is a group of related Java classes.
How are they related?
They all share the same first name -- e.g., all classes in a package named "com.stinky.util" are named "com.stinky.util.Sorter", "com.stinky.util.FileInfo", and so on.
How else are they related?
Classes in the same package can access each other's protected members.
Yeah, it's kind of like friends in C++ -- you know, "only friends can access your private parts." In Java, classes can access the "protected" and "default" member functions and instance data of other classes in the same package (as well as the "public" members, naturally).
What's a "default" member?
One that doesn't have any of the following keywords: public, protected, or private.
How do I use a class that's in a package?
You just call it by its full name. For instance,
Won't my fingers get tired, typing the whole name out every time?
Yeah, especially because Java is a strongly typed language.
Ha-ha. Very funny.
Seriously, that's what the "import" keyword is for. If you say "import com.stinky.util.Sorter", then every time you type "Sorter", the compiler will understand that you mean com.stinky.util.Sorter. So you can do:
And I guess wildcards work with import.
Yes, the line "import com.stinky.util.*;" will import the names of all classes in the com.stinky.util package. (However, it does not work recursively, so it won't import the com.stinky.util.net.WackySocket class.)
So is import just like "#include"?
Not really. #include inserts the text of an entire header file and compiles it as if it were part of the original file. import just tells the compiler that when it sees "Sorter", it should replace it with "com.stinky.util.Sorter".
How do I put my own classes in a package?
Three things. One: put a line like "package com.stinky.util;" in the very top of your source file. Two: put the source file in a directory named util, in a directory named stinky, in a directory named com.
That's two things.
The third thing is, make sure the top-level package directory ("com" in my example) is inside a directory that's in your classpath.
What's my classpath?
You don't want to know.
Yes, I do.
It's a list of directories, stored in an environment variable named CLASSPATH, that Java searches every time it's looking for a source or class file. The trick is, the directories in the classpath don't actually contain the files. They contain the directories that contain the directories that contain the files.
To further confuse matters, the classpath may also contain the names of archive files, specifically ZIP or JAR files. In that case, Java pretends that these archives are actually directories -- directories that contain the files and subdirectories in the archive files.
Just make sure "." (dot) is in your classpath and follow The Rules (see main article).
Be careful out there.