Access or visibility rules determine whether a method or a
data variable can be accessed by another method in another class
or subclass.
We have used the public
modifier frequently in class definitions. It makes classes,
methods, or data available to any other method in any other
class or subclass.
Java provides for 4 access modifiers :
- public
- access by any other class anywhere.
- protected
- accessible by the package classes and any subclasses that
are in other packages .
- Default - (also known as "package private")
accessible to classes in the same package but not by classes
in other packages, even if these are subclasses.
- private
- accessible only within the class. Even methods in subclasses
in the same package do not have access.
Note that a java file can have only one public class.
These access rules allow one to control the degree of encapsulation
of your classes. For example, you may distribute your class
files to other users who can make subclasses of them. By making
some of your data and methods private,
you can prevent the subclass code from interfering with the
internal workings of your classes.
Also, if you distribute new versions of your classes at a later
point, you can change or eliminate these private attributes
and methods without worrying that these changes will affect
the subclasses.
As we mentioned earlier,
if you do not put your class into a package, it is placed into
the "default unnamed package". For simple demonstration programs
this usually suffices. However, with more serious programs you
should use packages since otherwise any other class in the unnamed
package has access to your class's fields and methods that are
not set to private.
Most recent update: Oct. 22, 2004