Controlling variable use with access modifiers

To build on the class visibility controls, we have variable access modifiers. Here is a variable with the private access modifier being declared.

private int myInt;

For example, here is an instance of our Soldier class being declared, created and assigned. As you can see the access specified in this case is public.

public Soldier mySoldier = new Soldier();

Tip

Before you apply a modifier to a variable you must first consider the class visibility. If class a is not visible to class b, say because class a has default access and class b is in another package, then it doesn't make any difference what access modifiers you use on the variables in class a, class b can't see any of them anyway.

So, what can we surmise about encapsulation design so far? It makes sense to show a class to another class when necessary but only to expose the specific variables that are needed; not all of them.

Here is an explanation of the different variable access modifiers. They are more numerous and finely grained than the class access modifiers.

  • public: You guessed it, any class or method from any package can see this variable. Use public only when you are sure this is what you want.
  • protected: This is the next least restrictive after public. Protected variables can be seen by any class and any method if they are in the same package.
  • default: Default doesn't sound as restrictive as protected but it is more so. A variable has default access when no access is specified. The fact that default is restrictive perhaps implies we should be thinking on the side of hiding our variables more than we should be exposing them.

    Note

    At this point, we need to introduce a new concept. Do you remember we briefly discussed inheritance and how we can quickly take on the attributes of a class by using the extends keyword? Just for the record, default access variables are not visible to subclasses; that is, when we extend a class like we did with Activity, we cannot see it's default variables. We will look at inheritance in more detail later in the chapter.

  • private: Private variables can only be seen within the class they are declared. Including, like default access, they cannot be seen by subclasses (classes that inherit from the class in question).

Tip

The depth and complexity of access modification are not so much in the range of modifiers but rather in the smart ways we can combine them to achieve the worthy goals of encapsulation.

Variable access summary

A well-designed game will probably consist of one or more packages, each containing only default or default and public classes. Within these classes, variables will have carefully chosen and most likely varied access modifiers, chosen with a view to achieving our goal of encapsulation.

One more twist in all this access modification stuff before we get practical with it.