Visibility of Variables and Methods
One of the most important aspects of object-oriented design is data hiding, or encapsulation. By treating an object in some respects as a “black box” and ignoring the details of its implementation, we can write stronger, simpler code with components that can be easily reused.
Basic Access Modifiers
By default, the variables and methods of a class are accessible to members of the class itself and to other classes in the same package. To borrow from C++ terminology, classes in the same package are friendly . We’ll call this the default level of visibility. As you’ll see as we go on, the default visibility lies in the middle of the range of restrictiveness that can be specified.
The modifiers public
and private, on
the other hand, define the extremes. As we mentioned earlier, methods
and variables declared as private are accessible
only within their class. At the other end of the spectrum, members
declared as public are accessible from any class
in any package, provided the class itself can be seen. (The class
that contains the methods must be public to be
seen outside of its package, as we discussed previously.) The
public members of a class should define its most
general functionality—what the black box is supposed to do.
Figure 6.7 illustrates the four simplest
levels of visibility, continuing the example from the previous
section. Public members in TextArea are accessible from anywhere. Private members are not visible from outside the class. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access