Controlling class use with access modifiers

The designer of the class controls what can be seen and manipulated by any program that uses their class. Let's look at the access modifier you have probably already noticed before the class keyword like this:

public class Soldier{
   //Implementation goes here
}

There are two main access modifiers for classes in the context we have discussed so far. Let's briefly look at each in turn:

  • public. This is straightforward. A class declared as public can be "seen" by all other classes.
  • default. A class has default access when no access modifier is specified. This will make it public but only to classes in the same package and inaccessible to all others.

So now we can make a start at this encapsulation thing. But even at a glance, the access modifiers described are not very fine grained. We seem to be limited to:

  • Completely locking down to anything outside of the package (default)
  • or a complete free-for-all (public)

The benefits here are easily taken advantage of, however. The idea would be to design a package that fulfills a set of tasks. Then all the complex inner workings of the package, the stuff that shouldn't be messed with by anybody but our package, should be default access (only accessible to classes within the package). We can then make available a careful selection of public classes that can be used by others (or other distinct parts of our program).

Class access in a nutshell

A well-designed game will probably consist of one or more packages, each containing only default or default and public classes.

In addition to class level privacy controls, Java gives us programmers more fine-grained controls, but to use these controls we have to look into variables with a little more detail.