Java Reference
In-Depth Information
Figure 3.1 illustrates a class declaration for an
IntCell
object.
1
The decla-
ration consists of two parts:
public
and
private
.
Public
members represent the
portion that is visible to the user of the object. Since we expect to hide data,
generally only methods and constants would be placed in the
public
section.
In our example, we have methods that read from and write to the
IntCell
object. The
private
section contains the data; this is invisible to the user of the
object. The
storedValue
member must be accessed through the publicly visible
routines
read
and
write
; it cannot be accessed directly by
main
. Another way of
viewing this is shown in Figure 3.2.
Public members
are visible to non-
class routines; pri-
vate members are
not.
Figure 3.3 shows how
IntCell
objects are used. Since
read
and
write
are
members of the
IntCell
class, they are accessed by using the dot member
operator. The
storedValue
member could also be accessed by using the dot
member operator, but since it is
private
, the access at line 14 would be illegal
if it were not commented out.
Members that are
declared
private
are not visible to
nonclass routines.
Here is a summary of the terminology. The class defines
members
, which
may be either
fields
(data) or
methods
(functions). The methods can act on the
fields and may call other methods. The visibility modifier
public
means that the
member is accessible to anyone via the dot operator. The visibility modifier
private
means that the member is accessible only by other methods of this class.
A
field
is a member
that stores data; a
method
is a mem-
ber that performs
an action.
figure 3.1
A complete
declaration of an
IntCell
class
1
// IntCell class
2
// int read( ) --> Returns the stored value
3
// void write( int x ) --> x is stored
4
5
public class IntCell
6
{
7
// Public methods
8
public int read( ) { return storedValue; }
9
public void write( int x ) { storedValue = x; }
10
11
// Private internal data representation
12
private int storedValue;
13
}
figure 3.2
IntCell
members:
read
and
write
are
accessible, but
storedValue
is hidden.
read
write
storedValue
1. Public classes must be placed in files of the same name. Thus
IntCell
must be in file
IntCell.java
. We will discuss the meaning of
public
at line 5 when we talk about packages.
Search WWH ::
Custom Search