5.15.2. Visibility

Think of a drink vending machine as an object. Its "data" consists of the cans of drinks that are loaded into it. Its methods are the things that it can do. For example, it can accept a coin through a slot, it can detect a button push that selects a kind of drink, it can give change and it can turn a motor to deliver a drink.

Some of the methods are intended to be invoked by someone who is outside of the object. A person inserts coins and pushes a button. But some methods must not be directly accessible to others. For example, if a person can directly request that a motor turn to deliver a drink, then the person can get drinks for free.

The same thing occurs in object-oriented computer programs. Some variables and methods are public, usable by other methods in other classes, and some are private, usable only in the current class.

You normally think of a private instance method or variable as private to the object. In reality, it is private to the class. Private instance variables and methods can be used by other objects of the same class.

The motivation for having private variables and methods is different for progams than for vending machines. Here are two big factors.

  1. A private method or variable is not intended to be used in other classes. By making a variable or method private, you ensure that it will not accidentally be used elsewhere. That makes an entire class of potential errors impossible to make.

  2. You know that a private method or variable cannot be used in any other class. That frees you to make changes to the private variables and methods in any way that you like, as long as the public methods and varaibles continue to work correctly. If you have a private method called work and you decide to replace it by a pair of methods called work1 and work2, doing that cannot negatively affect any other class.


Indicating visibility

Indicate that a given variable is public by writing public in front of it.

Indicate that a given variable is private by writing private in front of it.