11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

202Part III: Introduction to Classes To protect the internals of the class from outside functions. Suppose, forexample, that you have a plan to build a software microwave (or whatever),provide it with a simple interface to the outside world, and thenput a box around it to keep others from messing with the insides. Theprotected keyword is that box. To make the class responsible for maintaining its internal state. It’s notfair to ask the class to be responsible if others can reach in and manipulateits internals (any more than it’s fair to ask a microwave designer tobe responsible for the consequences of my mucking with a microwave’sinternal wiring). To limit the interface of the class to the outside world. It’s easier tofigure out and use a class that has a limited interface (the public members).Protected members are hidden from the user and need not belearned. The interface becomes the class; this is called abstraction (seeChapter 11 for more on abstraction). To reduce the level of interconnection between the class and other code.By limiting interconnection, you can more easily replace one class withanother or use the class in other programs.Now, I know what you functional types out there are saying: “You don’t needsome fancy feature to do all that. Just make a rule that says certain membersare publicly accessible, and others are not.”Although that is true in theory, it doesn’t work. People start out with all kindsof good intentions, but as long as the language doesn’t at least discouragedirect access of protected members, these good intentions get crushed underthe pressure to get the product out the door.Discovering how protected members workAdding the keyword public to a class makes subsequent members public,which means that they are accessible by non-member functions. Adding thekeyword protected makes subsequent members of the class protected,which means they are not accessible by non-members of the class. You canswitch between public and protected as often as you like.Suppose you have a class named Student. In this example, the followingcapabilities are all that a fully functional, upstanding Student needs (noticethe absence of spendMoney() and drinkBeer() — this is a highly stylizedstudent):addCourse(inthours, float grade) — adds a coursegrade() — returns the current grade point averagehours() — returns the number of hours earned toward graduation

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

Saved successfully!

Ooh no, something went wrong!