Sams Teach Yourself C in 21 Days

(singke) #1
Object-Oriented Programming Languages 635

BD1


As you can see, the calculate_circle_area()routine is a black box. You don’t need to
know how it works in order to use it. All you need to know is what parameters it takes
and what value you’ll get in return. The following code might be a part of the calcu-
late_circle_area()routine:
...
...
PI = 3.14;
area = PI * r * r;
...
...
This is not a complete listing. Notice that this routine simply sets PIequal to 3.14in line


  1. In line 4, this value is used to calculate the area. Because this value is encapsulated,
    you can actually make a change to the value of PI and not affect any of the programs that
    call this routine. You could change PI to 3.14159in line 3 and all the programs that call
    this routine will still work. You might be thinking that regular C functions can be used to
    encapsulate functionality in this way, and you are correct. However the encapsulation
    possible with an object-oriented language goes even further.


Encapsulating Your Data
In addition to encapsulating functionality, you can also encapsulate data. Consider the
circle routine mentioned earlier. To store information about a circle, all you need to know
is the center point and the radius. As you learned in the earlier discussion, a user might
ask that you draw a circle by using three points that are located on the circle, or he might
ask that you draw it by using the center point and one point on the circle. Within your
black box, you can store the center point and the radius. You don’t have to tell the user
that you are storing the radius or the center point; however, you might end up using these
pieces of data when you implement functionality for your routines. Regardless of what
information users provide, you’ll be able to use the circle routine by keeping track of just
the radius and the center point. For example, a function to determine a circle’s area,cal-
culate_circle_area(), can use the radius and center point rather than any other data
without telling the user.

FIGUREB1.2
Encapsulation provides
black box functionality.
Center
and
Area

Area

Area = Calculate_circle_area(center_x, center_y, radius);

Calculate_circle_area( )

36 448201x-Bonus1 8/13/02 11:18 AM Page 635

Free download pdf