Access control
When a class of objects is defined,
it is not the case that we wish all the methods or variables of an object
of the class to be available to other objects in the software system. A
general design rule for classes is that they should be self-contained,
and control access to its variables and methods
There is little point in creating careful
get
and set methods, if we do not prevent the direct access of variables
by other objects.
Java provides several of levels of
access to the variables and methods defined in a class. We shall investigate
the access control provided by the following keywords:
You may, as an optional extension of your
reading, wish to look into a third keyword related to access:
Those variables and methods we wish to
hide from other objects should be declared as private.
Those variables and methods we wish other objects to have access to should
be declared as public.
For example, a MyCircle
object may be defined as follows:
class
MyCircle
{
//
private variables
private
int x;
private
int y;
private
int radius;
//... etc.
// public
methods
public int getX(){ return x; }
public void setX( int newX ) {x = newX; }
//... etc.
}
This MyCircle class has only private variables,
and only public methods ?this arrangement is quite common:
class MyCircle
|
|
Variables
|
Methods
|
Private
|
int x
|
|
Private
|
int y
|
|
Private
|
int radius
|
|
Public
|
|
int
getX() |
Public
|
|
void
setX( int newX ) |
Since all the variables are private, this
means another object cannot get access to them directly. So in order for
another object to create changes in a MyCircle object it must send messages
corresponding to the MyCircle object's public methods.
The protocol of an object is
made up of its public methods.
The default is that, unless specified
otherwise, a variable is not public.
Were a program to attempt to access
a private variable, Java would respond that the variable is not accessible.
This is demonstrated by the applet below, which creates a MyCircle object
and then tries to send a message to retrieve the value of a private variable
(radius):
//AcessApplet.java
//<APPLET
code = "AccessApplet.class" width=275 height=200></APPLET>
import
java.applet.Applet;
import
java.awt.*;
public
class AccessApplet extends Applet
{
public
void paint (Graphics g)
{
MyCircle
circle1 = new MyCircle();
circle1.setX(20);
g.drawString("Circle
X position is: " + circle1.getX(), 20, 20);
g.drawString("Circle1
radius is: " + circle.radius, 20, 20);
}
}
Note that classes
themselves, as well as variable and methods, can have their access defined.
Thus a public
class must
be defined in a file with the same name as the class, an is one that can
be used by other instances of other classes. Classes can be private,
and only accessible to some other class defined in the same file.
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|