Public and private members
Not everything inside a class should be reachable from outside. Access modifiers draw that line.
The two you will use most
- public. Other code can call it. This is the class's promise to the rest of the program.
- private. Only the class itself can use it. This is the class's own business.
C#
public class Counter
{
private int total = 0;
public void AddOne()
{
total = total + 1;
}
public int Current()
{
return total;
}
}Why hide anything
A private field cannot be changed by careless code elsewhere. The class stays in control of its own values, which makes bugs easier to find because there are fewer places they can start.
Default to private. Make something public only when another part of the program genuinely needs it. You can always open access later; closing it after others depend on it is much harder.
A cleaner way to expose a value is a property, covered later in this track.