OO Concepts   «Prev  Next»
Lesson 4 Encapsulation
Objective Describe the uses and benefits of encapsulation.

Describe Uses and Benefits of Encapsulation

As you saw earlier, objects (which are instances of classes) combine both data (also called attributes, variables, and state) with behavior (also called methods, functions, and operations). An object holds information, and can do things with that information on request. The things it can do are the responsibilities of the class. Once you decide that a particular responsibility is assigned to a particular class, you can't change that. Doing so would break other code that is relying on a method's existence and on what parameters it takes. But you can change the inside of your class as much as you like, and the compiler guarantees you will not break any code outside your class by doing so. You'll see more on that later. The inside of your class is generally the information it keeps. OOP keeps related information together, and keeps the methods that work with that information together. That makes your programming much simpler, and allows you to enforce business rules easily, because values can be changed together rather than one at a time. The outside of your class is also called its interface. It's the set of things your class promises to do. Changing your interface risks breaking other code, so once you havfe started to build a system, your interfaces should all be determined and unchangeable.

Encapsulation refers to three things:
  1. The idea of keeping both methods and variables together in a single clump or object
  2. Preventing code outside the object from accessing the inside of the object directly
  3. Creating an outside, or interface, that your class presents to the outside world and that does notchange
Encapsulation frees programmers from having to think about how the inside of a class works. You probably know a way to subtract two dates, but if there's a Date class in your system, you do not need to care: You need to know only that the Date class knows how to subtract one date from another. You need to know how to get the two dates to the Date subtract method and how and where to locate the result. The mechanism is no longer your concern. Other benefits of encapsulation are the ease with which programmers can enforce business rules and the way that changes in your class affect only your class and not the ones around it. You'll see examples of this as the course progresses.