4.5. The Power of Encapsulation
You learned earlier that encapsulation is the mechanism that bundles together the state information (fields) and behavior (methods) of an object. Now that you've gained some insights into public/private accessibility, encapsulation warrants a more in-depth discussion.
It's useful to think of an object as a "fortress" that "guards" data—namely, the values of all its fields. Rather than trying to march straight through the walls of a fortress, which typically results in death and destruction (!), we ideally would approach the guard at the gate to ask permission to enter. Generally speaking, the same is true for objects; we can't directly access the values of an object's privately declared fields without an object's ...
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