Java Reference
In-Depth Information
B.3
Accessing variables with get and set
All variables and methods declared and defined in a class are accessible from within
that class. The modifiers private , public and protected control the access from
outside the class to variables and methods of the class. Sometimes one talks about
the visibility of variables and methods instead of access.
A variable or method that is declared private cannot be accessed from outside
the class. It is not visible outside of the class where it is defined. The private
modifier is the main tool to implement data encapsulation . Private variables are
encapsulated in their class and protected against misuse from the outside. Only
methods of their class can modify them. Private variables are also not visible in
derived classes.
A variable that is declared public can be accessed from outside the class. It
!
is visible outside of the class where it is defined. Public variables can be modified
by methods of other classes. This bears the risk that the modifications are illegal
and corrupt the data. The use of public variables should therefore be avoided as
much as possible.
A variable that is declared protected can be accessed from the class where it
is defined and all classes derived from it. One might say that it is private to those
classes and is invisible outside them.
In order to access private variables, the classes can provide set - and get -
methods. The get -methods are used to return the variable. The set -methods are
used to set the variable to a specific value. They can in addition check that the
new value is legal. For an example, assume that we defined a class for a geometric
component. The component has a width and a height which can be set from the
outside. We would like to make sure that the component does not become too
small. With an appropriate set -method we can guarantee this. In the listing below
we assume that the width is stored in an integer variable width . The method only
changes the value if it is at least 50. In addition, the method returns a boolean
value indicating whether the value has been changed.
public boolean setWidth( int w){
if (w<50){
return ( false );
}
else {
width = w;
return ( true );
}
}
B.4
Passing references
A frequently occurring problem is that one class wants to use methods from an-
other class. To do this it needs a reference to an instance of the other class. We
saw examples of this when a listener wanted to update a panel. In the following
we describe the mechanism used in this case.
Search WWH ::




Custom Search