current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
Call this file and put it in a directory called MyPack.
Next, compile the file. Make sure that the resulting .class file is also in the MyPack
directory. Then, try executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command.
(Alternatively, you can use one of the other two options described in the preceding section to
specify the path MyPack.)
As explained, AccountBalance is now part of the package MyPack. This means that it
cannot be executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.
Access Protection
In the preceding chapters, you learned about various aspects of Java's access control mechanism
and its access specifiers. For example, you already know that access to a private member of
a class is granted only to other members of that class. Packages add another dimension to
access control. As you will see, Java provides many levels of protection to allow fine-grained
control over the visibility of variables and methods within classes, subclasses, and packages.
Classes and packages are both means of encapsulating and containing the name space
and scope of variables and methods. Packages act as containers for classes and other
subordinate packages. Classes act as containers for data and code. The class is Java's
smallest unit of abstraction. Because of the interplay between classes and packages, Java
addresses four categories of visibility for class members:
Subclasses in the same package
Non-subclasses in the same package
Subclasses in different packages
Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways
to produce the many levels of access required by these categories. Table 9-1 sums up the
While Java's access control mechanism may seem complicated, we can simplify it as
follows. Anything declared public can be accessed from anywhere. Anything declared
private cannot be seen outside of its class. When a member does not have an explicit access
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks