15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

238<br />

Sharing Code with Inheritance<br />

Protecting code from other programmers<br />

Objects isolate data from other parts of the program, but objects can also<br />

isolate subprograms from other programmers.<br />

Without objects, someone might write a useful subprogram that everyone<br />

else working on the program can use. One programmer might find that subprogram<br />

perfect whereas a second programmer might find that subprogram<br />

doesn’t quite do what he wants it to do, so he goes into the subprogram and<br />

changes the code.<br />

These changes wreck the subprogram <strong>for</strong> the first programmer, who now has<br />

to go back and fix the changes made by the second programmer. These<br />

changes make the subprogram work good <strong>for</strong> the first programmer, but now<br />

wreck the subprogram <strong>for</strong> the second programmer, and so on in an endless<br />

cycle.<br />

The problem is that the more people you have working on the same program,<br />

the more likely someone might accidentally modify one part of a<br />

program without notifying the other programmers. Even one change in a program<br />

can affect another part of that same program, so object-oriented <strong>programming</strong><br />

defines distinct boundaries that keep programmers from<br />

modifying code stored in objects created by someone else.<br />

When creating an object-oriented program, every programmer is given control<br />

of certain objects and no one is supposed to modify the code in any<br />

objects but his own.<br />

Objects let you physically store the source code <strong>for</strong> your entire object in a<br />

separate file, called a class file or just a class. At this point, a class is no different<br />

than storing a group of related subprograms in a separate file and<br />

keeping other programmers from modifying that separate file. However, the<br />

difference becomes more apparent when you want to reuse code.<br />

Encapsulation serves two purposes:<br />

✦ Protects data from being changed by other parts of a program<br />

✦ Protects subprograms from being changed by other programmers<br />

Sharing Code with Inheritance<br />

After programmers write some useful subprograms, they often store those<br />

subprograms in separate files <strong>for</strong> other programmers to use. However, no<br />

one is supposed to modify these subprograms.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!