Java Reference
In-Depth Information
Placement of classes
A class named C (say) is placed in its own file, named . Thus, class
Employee is placed in file . All the files that you use in a pro-
gram should be placed in the same directory on your hard drive. It is a good prac-
tice to have a different directory for each program. Get in the habit of creating a
new directory for the .java files whenever you start on a new Java project.
Importing predefined classes
A class C may need to reference classes that are predefined in packages (see
Chap. 11) that come with the Java system. To be able to reference any class that
is defined in a package, say package java.util , place the following import
statement before the class definition in file :
import java.util.*;
To import just one class of the package, say Date , use this import statement:
import java.util.Date;
Any number of import statements may be placed before the class definition
in the file. The order in which they occur does not matter, and a class may be
imported several times.
The principal of information hiding
The principle of information hiding is:
3-6.4, 3-6.5
Principal of information hiding . Do not give someone access to
information that they do not need to know.
In some situations, information hiding is a bad principal. For example, some
governments use it, with their own definition of “need”, to suppress information
and keep people in the dark, leading to corruption and even suppression of their
people. To protect against this, some countries have passed “freedom of infor-
mation” acts, which attempt to limit what can be kept from the public.
In programming, the principal of information hiding can be useful. Limiting
what can be seen in a particular place can help the reader understand parts of the
program better, and it can help make later changes in the program easier.
Java has several mechanisms to help in hiding information. The one that
concerns us here is the use of access modifiers public or private in declarations
of components of a class. The presence of public means that the component
may be accessed from any part of the program that has access to the class.
Modifier private restricts access to the class in which the declaration appears.
In Fig. 3.1, the methods are public. The three fields are private, which is indicat-
ed in the instance of Employee in Fig. 3.2 by graying out the fields.
Generally, we make fields of a class private so that a user of an instance can-
not access them directly. Instead, the user accesses using methods of the class,
Search WWH ::

Custom Search