Article
Object Oriented Concepts in Java – Part 2
Access Control Modifiers
As we have just seen, a class can be made public to allow code outside of its package to make use of it. Class members, which include properties and methods, can be similarly modified to control access to them. Like classes, members have a default access setting that restricts access to code within the same package. Consider the following sample declarations:
int numNuts = 0;
boolean pickNut(int numberToPick) {
...
}
Even if the class is declared public, the value of the above numNuts property (assuming it is declared as the property of an Object class) may only be accessed or modified by code in the same package. Similarly, the pickNut method shown above may only be invoked by code in the same package as the class.
As with classes, properties and methods may be declared public:
public int numNuts = 0;
public boolean pickNut(int numberToPick) {
...
}
Any code (from any class in any package) can access and modify a public property value or invoke a public method.
Properties and methods have two additional access settings that classes do not have. The first is private:
private int numNuts = 0;
private boolean pickNut(int numberToPick) {
...
}
Only code in the same class can access private properties and methods. If you want to store information in an object that is only useful to the object itself or other objects of the same class, or if you want to restrict access to the information (as we'll see in the next section, this is part of good class design!), then you should use a private property for it. Likewise, methods that perform internal calculations or are otherwise not useful to other classes should be declared private.
The final access setting that methods and properties may take is protected:
protected int numNuts = 0;
protected boolean pickNut(int numberToPick) {
...
}
The protected mode is very similar to the default mode, in that it refuses access to code outside of the class' package, but it introduces one exception: subclasses of the current class (i.e. classes that extend this class) may also access protected members.
Distinguishing the situations in which each access control setting is appropriate takes a little experience. It's tempting at first to just declare everything public to save yourself the trouble of worrying when something is accessible and when it isn't. While this will certainly work, it is definitely not in the spirit of object oriented programming. Code that you plan to reuse or distribute, especially, will benefit from being assigned the most restrictive access control settings that are appropriate. One reason for this is illustrated in the following section.