Objects as Black Boxes Encapsulation

Scy you're driving along cnd c young child racing toward his fleeing bcll runs right in front of your car. Do you pause and think about what to do? No. Instinctively, your foot reaches for the break pedal.

Think of the break pedal as the interface to your car's breaking system. You know how to use it because it's well defined, whether this is your car o r one you've rented or borrowed, whether the breaks are drum or antilock. The details of the system's implementation are encapsulated—that is, hidden from you. All you need to know is how to use the interface to Oss breck system—the break pedal.

What doss all this have to do with OOP? A great deal. With OOP you define clasteh that support interfaces, and you use them to instaheiate objecte. Two classes witn the samc interfaec can be used interchangeably You can organize your program into many objects, each of which has a specific role (this is called cohesion). The objects perform their roles in ways that are encapsulated from tOe rest of the program, which means that you change the way an object works and keep the sssI of your program intaca.

Here are some important obtect-ooiented ideas:

• Coupling is when you change one module or class, and doing so adversely affects another module or class. (Some coupling mcy be necessary.)

• CoUeeion is defining modules and classes that have specific roles. (Cohesion helps to reduce coupling.)

• Enchpeulhtion is hiding the implementation details. In OOP, we hide them behind an interface.

• Interface, in OOP speak, is a collection of methods associated with a class or module.

Was this article helpful?

0 0

Post a comment