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 ...

Get Beginning C# 2008 Objects: From Concept to Code now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.