Java Reference
In-Depth Information
org.cadenhead.rss requires an org folder, a cadenhead folder inside org , and an rss
folder inside cadenhead . The classes in the package then are stored in the rss folder.
Adding a Class to a Package
The final step to putting a class inside a package is to add a statement to the class file
above any import declarations that are being used. The package declaration is used
along with the name of the package, as in the following:
package org.cadenhead.rss;
The package declaration must be the first line of code in your source file, after any com-
ments or blank lines and before any import declarations.
Packages and Class Access Control
Earlier today, you learned about access control modifiers for methods and variables. You
also can control access to classes.
Classes have the default access control if no modifier is specified, which means that the
class is available to all other classes in the same package but is not visible or available
outside that package. It cannot be imported or referred to by name; classes with package
protection are hidden inside the package in which they are contained.
To allow a class to be visible and importable outside your package, you can give it public
protection by adding the public modifier to its definition:
public class Visible {
// ...
}
Classes declared as public can be accessed by other classes outside the package.
Note that when you use an import statement with an asterisk, you import only the public
classes inside that package. Private classes remain hidden and can be used only by the
other classes in that package.
6
Why would you want to hide a class inside a package? For the same reasons that you
want to hide variables and methods inside a class: so that you can have utility classes and
behavior that are useful only to your implementation or so that you can limit the inter-
face of your program to minimize the effect of larger changes. As you design your
classes, take the whole package into consideration and decide which classes you want to
declare public and which you want to be hidden.
Creating a good package consists of defining a small, clean set of public classes and
methods for other classes to use and then implementing them by using any number of
hidden support classes. You see another use for private classes later today.
Search WWH ::




Custom Search