ENCAPSULATION
A class’s public interface is the set of properties, methods, and events that are visible to code outside of the class. The class may also have private properties, methods, and events that it uses to do its job. For example, the Job class described in the previous section provides an AssignJob method. That method might call a private FindQualifiedEmployee function that looks through an employee database to find someone who has the skills and equipment necessary to do the job. That routine is not used outside of the class, so it can be declared private.
The class may also include properties and events hidden from code outside of the class. These hidden properties, methods, and events are not part of the class’s public interface.
The class encapsulates the programming abstraction that it represents (a Job in this ongoing example). Its public interface determines what is visible to the application outside of the class. It hides the ugly details of the class’s implementation from the rest of the world. Because the class hides its internals in this way, encapsulation is also sometimes called information hiding.
By hiding its internals from the outside world, a class prevents exterior code from messing around with those internals. It reduces the dependencies between different parts of the application, allowing only those dependencies that are explicitly permitted by its public interface.
Removing dependencies between different pieces of code makes the code easier to modify ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access