Java Reference
In-Depth Information
By using access control, you can dictate how your class is used by other classes. Some
variables and methods in a class are of use only within the class itself and should be hid-
den from other classes. This process is called encapsulation: An object controls what the
outside world can know about it and how the outside world can interact with it.
Encapsulation is the process that prevents class variables from being read or modified by
other classes. The only way to use these variables is by calling methods of the class, if
they are available.
The Java language provides four levels of access control: public , private , protected ,
and a default level specified by using none of these access control modifiers.
Default Access
Variables and methods can be declared without any modifiers, as in the following
examples:
String version = “0.7a”;
boolean processOrder() {
return true;
}
A variable or method declared without any access control modifier is available to any
other class in the same package. The Java class library is organized into packages such as
javax.swing , which are windowing classes for use primarily in graphical user interface
programming, and java.util , a useful group of utility classes.
Any variable declared without a modifier can be read or changed by any other class in
the same package. Any method declared the same way can be called by any other class
in the same package. No other classes can access these elements in any way.
This level of access control doesn't control much access, so it's less useful when you
begin thinking about how you want a class to be used by other classes.
6
The preceding discussion raises the question about what package
your own classes have been in up to this point. As you see later
today, you can make your class a member of a package by using
the package declaration. If you don't use this approach, the class
is put into an unnamed package with all other classes that don't
belong to any other packages.
NOTE
Search WWH ::




Custom Search