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.

242<br />

Polymorphism: Modifying Code without Changing Its Name<br />

By keeping the amount of code stored inside each object to a minimum,<br />

object-oriented <strong>programming</strong> makes it easy to understand how each object<br />

works. Through inheritance, OOP makes it easy to update one subprogram<br />

that’s reused in other objects.<br />

As a result, inheritance makes reusing objects (and their subprograms) practical<br />

and modifying those objects’ subprograms fast, simple, and easy.<br />

Inheritance offers the convenience of reusing code without the inconvenience<br />

of updating that code in multiple locations.<br />

Polymorphism: Modifying Code<br />

without Changing Its Name<br />

Besides reusing existing subprograms (without modifying them) and adding<br />

new subprograms to an object, you can also modify an inherited subprogram<br />

through polymorphism.<br />

Polymorphism lets you inherit a subprogram from another object and then<br />

replace the code in that subprogram with brand new code. So essentially all<br />

you’re really reusing is the original subprogram’s name, as shown in Figure 7-9.<br />

Object A<br />

Subprogram Move<br />

Code 1<br />

Code 2<br />

Figure 7-9:<br />

Polymorphism<br />

lets you<br />

reuse a<br />

subprogram<br />

name in<br />

another<br />

object.<br />

Object B<br />

Subprogram Move<br />

Code 30<br />

Code 31<br />

Code 32<br />

The purpose of polymorphism is to let multiple objects use the same<br />

descriptive subprogram name. Normally, two subprograms can’t share the<br />

same name. Otherwise, when you call a subprogram by name, the computer<br />

doesn’t know which subprogram you actually want to use.

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

Saved successfully!

Ooh no, something went wrong!