Earlier in the course, many examples used public fields so you could focus on objects, references, methods, and program flow.
As classes become more important to the design of a program, unrestricted field access can become a problem.
Encapsulation is the idea of keeping a class's internal state under the control of the class.
Consider:
public class Player
{
public int jerseyNumber;
}Code outside the Player class can directly change the field:
player1.jerseyNumber = 7;That is simple, but it also means outside code can assign any value that the field type accepts.
Suppose the program requires a jersey number to be greater than zero.
With a public field, outside code can still write:
player1.jerseyNumber = -5;The assignment is type-compatible because -5 is an int.
But it may violate the rules of the program.
This reveals an important distinction:
valid C# value
≠
valid object stateAn object should not have to depend on every caller remembering all of its rules.
Instead, the class can control which state is directly accessible and which changes must go through class behavior.
Conceptually:
This creates a boundary around the internal representation of the object.
A useful way to think about a class is as having two views.
Outside view:
Encapsulation helps keep those two concerns separate.
Imagine a Player object that tracks whether the player is available for a match.
If every part of the program can directly change every field, the Player class has little control over its own state.
A safer design may restrict direct access and provide a class-defined way to update the state.
The exact implementation can vary, but the design question is the same:
When outside code reaches directly into many fields, that outside code becomes tightly connected to the class's internal structure.
If the class later changes how it stores information, many callers may also need to change.
Encapsulation reduces that dependency by encouraging callers to work through the class's intended public surface rather than relying on internal details.
The goal is not to make a class impossible to use.
A class still needs to expose the behavior or information that other parts of the program legitimately require.
The design question is:
The next page introduces the public and private access modifiers that C# uses to express that decision.
When a class controls access to its state, it becomes easier to:
Encapsulation means treating an object as more than a collection of publicly writable fields.
The class owns its state and should control how that state is exposed or changed.
The pages that follow show how access modifiers and class methods help create that boundary.