Sunday, March 10, 2019
Object Oriented Programming in Different Languages
OOP with Microsoft optical elementary . winnings and Microsoft optic C Step by Step by robin redbreast A. Reynolds-Haertle Microsoft excite 2002 (393 scalawags) ISBN 0735615683 This intuitive, self-paced accomplishment title is designed to help you noble the basics of object-oriented broadcastming with visual staple fiber. final or ocular C. flurry of Contents OOP with Microsoft optic basal . electronic network and Microsoft ocular C . mesh Step by Step adit Chapter 1 Writing Your commencement ceremony Object-Oriented architectural plan Chapter 2 Creating form Instances with Constructors Chapter 3 Creating Fields and PropertiesChapter 4 Working with Methods Chapter 5 utilize Inheritance to take a crap Specialized furcatees Chapter 6 Designing Base kinsfolkes as Abstract Classes Chapter 7 Responding to Changes with Events and Exceptions Chapter 8 Putting It but To raiseher with Compvirtuosonts Chapter 9 Providing operate Using Interfaces Chapter 10 Using Classes Interchangeably Through pleomorphism Chapter 11 Using Sh atomic procedure 18d and Static Members Chapter 12 Overloading Operators with ocular C Chapter 13 Saving Instance Data Chapter 14 Reducing complexness by DesignAppendix chalk upitional Re reservoirs Index Height Gage List of Sidebars OOP with Microsoft visual sackonic . crystallise and Microsoft optic C . gelt Step by Step PUBLISHED BY Microsoft conjure up A Division of Microsoft confederation ace and entirely(a)(a) Microsoft modal encourage Redmond, Washington 98052-6399 Copyright 2002 by redbreast A. Reynolds-Haertle All rights reserved. No part of the contents of this contain whitethorn be reproduced or transmitted in every form or by whatsoever means with break through(p) the written permission of the publisher. depository library of Congress Cataloging-in- unexclusiveation Data Reynolds-Haertle, robin A. , 1959-OOP with Microsoft ocular Basic . brighten and Microsoft optic C Step by Step / Robin A. Reynolds-Haertle. p. cm. Includes bibliographical come toences and index. ISBN 0-7356-1568-3 1. Object-oriented computer programming ( com swaner science). 2. Microsoft ocular BASIC. 3. C ( reck superstarr program terminology) I. gentle. QA76. 64 . R495 2001 005. 2768dc21 2001052122 Printed and bound in the United States of America. 1 2 3 4 5 6 7 8 9 QWT 7 6 5 4 3 2 Distributed in merchantmanada by Penguin Books Canada Limited. A CIP catalogue record for this becharm as is available from the British program library.Microsoft Press platters atomic number 18 available through and through containsellers and distributors worldwide. For further study astir(predicate) international editions, penetrate your local Microsoft Corporation accountability or wrap up Microsoft Press International directly at fax (425) 936-7329. Visit our electronic network site at www. microsoft. com/mspress. Send comments to emailprotected com. IntelliSense, Microsoft , Microsoft Press, optic Basic, opthalmic C, optical Studio, and Windows atomic number 18 either registered trademarks or trademarks of Microsoft Corporation in the United States and/or opposite countries.Other result and comp all names mentioned here(predicate)in may be the trademarks of their treasureive owners. The modeling companies, organizations, products, domain names, e-mail addresses, logos, people, attitudes, and events depicted herein ar fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Acquisitions Editor Danielle Bird regard Editor Kathleen AtkinsTechnical Editor Jack Beaudry Body Part No. X08-42192 MICROSOFT authorise AGREEMENT Book Companion CD IMPORTANTREAD cautiouslyThis Microsoft expiry-User License Agreement (EULA) is a legal agreement between you (either an narrate or an entity) and Microsoft Corporation for the Microsoft product ide ntified above, which includes calculator parcel and may include associated media, printed veridicals, and on bend or electronic documentation (software product harvest). either fragment included deep down the packet reaping that is accompanied by a separate extirpate-User License Agreement sh whole told be governed by frequently(prenominal) agreement and non the name touch on forth down the stairs. By tacking, replicateing, or in the raw(prenominal)wise use the bundle intersection point, you agree to be bound by the impairment of this EULA. If you do non agree to the terms of this EULA, you are non true to install, copy, or separatewise wint the packet crossing you may, however, translate the software package crossing, along with all printed materials and otherwise items that orm a part of the Microsoft product that includes the data addressor software crossway, to the place you obtained them for a full refund. software program PRODUCT L ICENSE The software product PRODUCT is protected by United States secure laws and international copyright treaties, as well as other intellectual office laws and treaties. The bundle PRODUCT is licenced, not sold. 1. GRANT OF LICENSE. This EULA grants you the followers rights a. Software Product. You may install and go for one copy of the packet PRODUCT on a single computer.The primary drug substance absubstance abuser of the computer on which the software system PRODUCT is installed may make a second copy for his or her soap use on a portable computer. b. Storage/Network Use. You may as well store or install a copy of the SOFTWARE PRODUCT on a storage device, such as a network server, used solitary(prenominal) to install or run the SOFTWARE PRODUCT on your other computers over an internal network however, you es displaceial acquire and dedicate a license for distributively separate computer on which the SOFTWARE PRODUCT is installed or run from the storage device.A l icense for the SOFTWARE PRODUCT may not be shared or used concurrently on variant computers. c. License Pak. If you excite acquired this EULA in a Microsoft License Pak, you may make the number of spare copies of the computer software portion of the SOFTWARE PRODUCT authorized on the printed copy of this EULA, and you may use each copy in the manner undertake above. You are too entitled to make a corresponding number of secondary copies for portable computer use as specified above. . exemplar Code. Solely with respect to portions, if any, of the SOFTWARE PRODUCT that are identified within the SOFTWARE PRODUCT as sample code (the sample codification) i. Use and Modification. Microsoft grants you the right to use and modify the fountain code recital of the SAMPLE CODE, pop the questiond you comply with subsection (d)(iii) below. You may not disperse the SAMPLE CODE, or any special transformation of the SAMPLE CODE, in source code form. ii. Redistributable bucks.Provided you comply with subsection (d)(iii) below, Microsoft grants you a nonexclusive, royalty-free right to reproduce and broadcast the object code interpreting of the SAMPLE CODE and of any modified SAMPLE CODE, other than SAMPLE CODE, or any modified version thereof, designated as not redistributable in the allegeme file that forms a part of the SOFTWARE PRODUCT (the Non-Redistributable Sample Code). All SAMPLE CODE other than the Non-Redistributable Sample Code is collectively referred to as the REDISTRIBUTABLES. iii. Re diffusion Requirements.If you redistribute the REDISTRIBUTABLES, you agree to (i) distribute the REDISTRIBUTABLES in object code form only in uniting with and as a part of your software application product (ii) not use Microsofts name, logo, or trademarks to market your software application product (iii) include a valid copyright notice on your software application product (iv) indemnify, hold harmless, and defend Microsoft from and against any claims or lawsuits, including attorneys fees, that arise or result from the use or statistical distribution of your software application product and (v) not permit further distribution of the REDISTR IBUTABLES by your end user. Contact Microsoft for the applicable royalties due and other licensing terms for all other uses and/or distribution of the REDISTRIBUTABLES. 2. DESCRIPTION OF OTHER RIGHTS AND LIMITATIONS. Limitations on Reverse Engineering, Decompilation, and Disassembly. You may not reverse engineer, decompile, or disassemble the SOFTWARE PRODUCT, except and only to the outcome that such activity is expressly permitted by applicable law notwithstanding this limitation. Separation of Components. The SOFTWARE PRODUCT is licensed as a single product.Its component parts may not be separated for use on more than one computer. Rental. You may not rent, lease, or lend the SOFTWARE PRODUCT. Support Services. Microsoft may, but is not obligated to, add you with condense services related to the SOFTWARE PRODUCT (Support Services). Use of Support Services is governed by the Microsoft policies and programs scratch out in the user manual, in online documentation, and/or in other Microsoft-provided materials. Any supplemental software code provided to you as part of the Support Services shall be considered part of the SOFTWARE PRODUCT and subject to the terms and conditions of this EULA.With respect to technical schooling you provide to Microsoft as part of the Support Services, Microsoft may use such information for its business purposes, including for product comport and organic evolution. Microsoft depart not utilize such technical information in a form that personally identifies you. Software Transfer. You may permanently transfer all of your rights under this EULA, provided you stay on no copies, you transfer all of the SOFTWARE PRODUCT (including all component parts, the media and printed materials, any upgrades, this EULA, and, if applicable, the Certificate of Au pastticity), and the recipient agrees to the terms of this EULA. Termination.Without diagonal to any other rights, Microsoft may terminate this EULA if you fail to comply with the terms and conditions of this EULA. In such event, you must destroy all copies of the SOFTWARE PRODUCT and all of its component parts. 3. COPYRIGHT. All title and copyrights in and to the SOFTWARE PRODUCT (including but not limited to any images, photographs, animations, video, audio, music, text edition edition, SAMPLE CODE, REDISTRIBUTABLES, and app allows incorporated into the SOFTWARE PRODUCT) and any copies of the SOFTWARE PRODUCT are owned by Microsoft or its suppliers. The SOFTWARE PRODUCT is protected by copyright laws and international accord provisions. Therefore, ou must treat the SOFTWARE PRODUCT like any other copyrighted material except that you may install the SOFTWARE PRODUCT on a single computer provided you keep the original solely for natural coveringup or archival purposes. Yo u may not copy the printed materials attach to the SOFTWARE PRODUCT. 4. U. S. GOVERNMENT RESTRICTED RIGHTS. The SOFTWARE PRODUCT and documentation are provided with RESTRICTED RIGHTS. Use, duplication, or disclosure by the Government is subject to restrictions as make out forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252. 27-7013 or subparagraphs (c)(1) and (2) of the Commercial Computer SoftwareRestricted Rights at 48 CFR 52. 227-19, as applicable. Manu concomitanturer is Microsoft Corporation/One Microsoft Way/Redmond, WA 98052-6399. 5. EXPORT RESTRICTIONS. You agree that you depart not trade or re-export the SOFTWARE PRODUCT, any part thereof, or any process or service that is the direct product of the SOFTWARE PRODUCT (the prior collectively referred to as the Restricted Components), to any country, person, entity, or end user subject to U. S. export restrictions. You specifically agree not to export or re-export any of the Restricted Components (i) to any country to which the U. S. as embargoed or dependant the export of goods or services, which currently include, but are not take aimfully limited to, Cuba, Iran, Iraq, Libya, North Korea, Sudan, and Syria, or to any national of any such country, wherever located, who intends to transmit or transport the Restricted Components back to such country (ii) to any end user who you know or acquire reason to know will utilize the Restricted Components in the design, development, or production of nuclear, chemical, or biological weapons or (iii) to any end user who has been prohibited from participating in U. S. export trans action mechanisms by any federal agency of the U. S. government. You warrant and map out that neither the BXA nor any other U. S. ederal agency has suspended, revoked, or denied your export privileges. DISCLAIMER OF stock warrant NO WARRANTIES OR CONDITIONS. MICROSOFT EXPRESSLY DISCLAIMS ANY WARRANTY OR CONDITION FOR THE SOFTWAR E PRODUCT. THE SOFTWARE PRODUCT AND ANY RELATED DOCUMENTATION are PROVIDED AS IS WITHOUT WARRANTY OR CONDITION OF ANY KIND, EITHE R EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY, seaworthiness FOR A PARTICULAR PURPOSE, OR NONINFRINGEMENT. THE ENTIRE RISK ARISING OUT OF apply OR PERFORMANCE OF THE SOFTWARE PRODUCT REMAINS WITH YOU. LIMITATION OF LIABILITY.TO THE uttermost EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL MICROSOFT OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES or so(prenominal) (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR inability TO USE THE SOFTWARE PRODUCT OR THE supplying OF OR visitation TO PROVIDE hold in SERVICES, EVEN IF MICROSOFT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY CASE, MICROSOFTS ENTIRE LIABILITY U NDER ANY PROVISION OF THIS EULA SHALL BE LIMITED TO THE GREATER OF THE AMOUNT ACTUALLY PAID BY YOU FOR THE SOFTWARE PRODUCT OR US$5. 00 PROVIDED, HOWEVER, IF YOU HAVE ENTERED INTO A MICROSOFT SUPPORT SERVICES AGREEMENT, MICROSOFTS ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOVERNED BY THE TERMS OF THAT AGREEMENT.BECAUSE SOME STATES AND JURISDICTIONS DO NOT ALLOW THE excision OR LIMITATION OF LIABILITY, THE ABOVE LIMITATION MAY NOT cave in TO YOU. MISCELLANEOUS This EULA is governed by the laws of the State of Washington USA, except and only to the extent that applicable law mandates governing law of a different jurisdiction. Should you contribute any questions concerning this EULA, or if you desire to contact Microsoft for any reason, please contact the Microsoft subsidiary serving your country, or bring out Microsoft Sales Information revolve around/One Microsoft Way/Redmond, WA 98052- 6399. PN 097-0002296 For Bruce Youre still the one.About the Author Robin A. Reyno lds-Haertle Robins interest in computing began when she taught herself to program in C to fulfill a programming oral communication requirement for her masters degree in biomathematics at the University of Washington. Fascinated by the subject, Robin attended as more computer science separatees as her account would permit, and took a position as a programmer with the University of Washington subsequently on graduation. Robin spent several years in the biotechnology industry, opus data applications in various database management systems, C, and Microsoft visual Basic.Not content to on the get-up-and-go get computer science and software technology books, she then act and effd a masters degree in software engineering at Seattle University. During these years, Robin presented training sessions on software engineering topics to her peers. later on so many years in the severaliseroom, Robin cherished to try teaching, and jumped at the opportunity to teach object- oriented programming with visual Basic for the University of Washington Outreach program. Here she discovered she loved writing instructional materials and sample labors for her students. This led Robin to her current position as a programmer/writer at Microsoft, writing conceptual documentation for visual Basic and Microsoft ocular C.When not at the computer, Robin is arduous to make peace with her abandoned husband and sons. After she plump outs this book, they discover forth to Moms attention to Cub Scouts, Boy Scouts, hiking, and watching BattleBots. After catching up with the family, Robin hopes to sew a few quilts. Acknowledgments first-year Id like to thank the team at Microsoft Press that turned my writing into a book. Without Jack Beaudry, the technical editor, I neer would contain gotten any sleep. His meticulous reviews saved me time and saved readers from much frustration. Kathleen Atkins, the be sick editor, kept everything running smoothly and improved my text consi derably.Credit is besides due to Danielle Bird, acquisitons editor Rebecca McKay (Becka), manuscript editor Cheryl Penner and Rebecca Wendling (Becky), copy editors Gina Cassill, compositor and Michael Kloepfer, electronic artist. I also exigency to thank my colleagues at Microsoft who be givenened sympathetically to my complaints active deadlines and beta software. Editors Roger Haight and Meredith Waring do me a better writer. Mike Pope reminded me to put the reader ahead of being clever. Megan Shult and Ann Morris, my managers, were supportive even when writing consumed all my aft(prenominal)-hours energy. Much of what I flavour outed about . NET came from the material written by my team members Jina Chan, Seth Grossman, Steve Hoag, Steve Stein, and Matt Stoecker. And thank you to Diana Rain, my office mate.Id also like to thank Ruth McBride, my longtime manager, and my teachers at Seattle University. I appreciate their patience with my often experimental approaches to th eir assignments over the years. I also do to mention the friends that still call to check on me, even though I havent called them in months. Jennifer Wirt, Lisa Wiken, molly Potteiger, and Julie Brinkley have been true friends. This book would never have been written without the support of my husband, Bruce. He sodding(a)ly ran my life for the seven months I was writing this book. I worked and wrote he did everything else. My friends are still laughing about how he RSVPs for me.Lastly, I thank my sons for fairish being there and for being proud of me. Introduction Microsoft Visual Basic developers have long clamored for complete objectoriented language support. Microsoft Visual Basic . NET supports all the features of an object- oriented language. In addition, the entire Microsoft . NET Framework, which includes the development support for Microsoft Windows applications, Web applications, Web services, graphics, and data access, is designed match to object-oriented principles. Developers who have a firm grasp of object-oriented principles will be the strongest . NET developers.Also modernistic to developers is C, a C-based language that gives developers a language excerption for developing with the . NET Framework. Some C, Java, and C++ development will drive to C to take advantage of . NETs features. Visual Basic programmers looking to chance upon a C language office also move to C. Visual Basic . NET and C any(prenominal)(prenominal) support object-oriented development with the . NET Framework. No matter what language you claim for development, being able to read code in either language will double your access to Microsoft Visual Studio documentation, . NET books, snip articles, and other developer resources. outline RequirementsYoull adopt the pursuit computer hardware and software to complete the workouts in this book Microsoft Visual Studio . NET victor edition. The Visual Studio . NET software isnt included with this book. You must get it one after another and install it before you pot complete the crops in this book. A computer capable of running Microsoft Visual Studio . NET. The side by side(p) hardware configuration is recommended by the Microsoft Visual Studio . NET Web site, at http//msdn. microsoft. com/vstudio/nextgen/ Computer/Processor PC with a Pentium II come apart processor, 450 megahertz (MHz) Pentium III curriculum processor, 600 MHz recommendedOperating System Microsoft Windows 2000, Server or captain Microsoft Windows XP Home or Professional Microsoft Windows NT 4. 0 Server Memory Windows 2000 Professional, 96 megabytes (MB) of tug 128 MB recommended Windows 2000 Server, 192 MB of RAM 256 MB recommended Windows XP Professional, 128 MB of RAM 160 Recommended Hard Disk 500 MB on System propose and 3. 0 gigabyte (GB) on installation drive Drive CD-ROM drive Display VGA or higherre result manage Computer/Processor Input Device Microsoft Mouse or compatible pointing device Finding Your Best Starting Point This book is designed to teach you the fundamentals of object-oriented programming.You atomic number 50 use this book if you have a basic knowledge of Visual Basic 6, Visual Basic . NET, Visual C, or other Windows programming language. The cyphers in this book impound you butt end already perform the following t expects Create a new Windows use project, build it, and run it. number Windows Forms take holds to a Windows Form. Create a order to respond to the clack event of a yetton control. Create a elemental order (called a gunman or buy the farm in Visual Basic . NET). Declare and use variables. For an introduction to Visual Basic . NET, read Microsoft Visual Basic . NET Step by Step by Michael Halvorson (Microsoft Press, 2002).For an introduction to Visual C , read Microsoft Visual C . NET Step by Step by fanny Sharp and Jon Jagger (Microsoft Press, 2002). Use the following table to go through your best scratch point in this book. If you are Ne w To object- oriented programming Migrating From Visual Basic 6 Switching From another object- oriented programming ensue these travel score the practice files as exposit in the following section, Installing and Using the exercise Files Work through the chapters sequentially for a complete introduction to object-oriented programming. Chapters 1 through 7, 9, and 11 trim down on the mechanics of object- riented programming, while the other chapters cover the concepts in more depth. Install the practice files as described in Installing and Using the Practice Files on the next page. Work through the chapters sequentially for a complete introduction to object- oriented programming with Visual Basic .NET. Chapters 1 through 7, 9, and 11 concentrate on the mechanics of object- oriented programming, while the other chapters cover the concepts in more depth. Install the practice files as described in Installingand Using the Practice Files. If you are New language. Referencing The bo ok after on the job(p) through the exercises Follow these steps Complete Chapter 1 to learn the basic yntax of properties and methods. Read the diligent credit entry sections at the end of the chapters for information about specific club constructs. Use the index or the Table of Contents to find information about particular subjects. Read the Quick Reference at the end of each chapter to find a picture review of the sentence structure and techniques presented in the chapter. Installing and Using the Practice Files The gent CD inwardly the back cover of this book contains the practice files that youll use as you perform the exercises in the book. For example, when youre learning to shit row events, youll use a bitmap file named Train. bmp.By exploitation the practice files, you wont waste time creating objects that arent relevant to the exercise. Instead, you washstand concentrate on learning object-oriented programming with Visual Basic . NET and Visual C . NET. The file s and the step-by-step instructions in the lessons also let you learn by doing, which is an easy and effective way to acquire and remember new skills. Important Install the practice files Before you break the seal on the OOP with Microsoft Visual Basic . NET and Microsoft Visual C Step by Step companion CD package, be sure that this book matches your version of the software.This book is designed for use with Microsoft Visual Studio . NET Professional Edition for the Windows operating systems. To find out what software youre running, you whoremonger check the product package or you can scar the software, and then move About Microsoft Development Environment in the Help placard at the top of the screen. Follow these steps to install the practice files on your computers hard disk so that you can use them with the exercises in this book. 1. Remove the companion CD from the package inside the back cover of this book and insert the CD in your CD-ROM drive. 2. Double-click the My Compu ter movie on the Desktop.Tip On some computers, the startup program might run automatically when you close the CD-ROM drive. In this case, skip steps 2 through 5 and follow the instructions on the screen. 3. Double-click the icon for your CD-ROM drive. 4. Double-click StartCD. exe 5. break down Install Sample Code. The setup program window appears with the recommended options pre take uped for you. For best results in use the practice files with this book, accept these pre portion outed settings. 6. When the files have been installed, lead the CD from your CD- ROM drive and replace it in the package inside the back cover of the book.A folder called OOPVBCS has been framed on your hard disk, and the practice files have been placed in that folder. Using the Practice Files Each lesson in this book explains when and how to use any practice files for that lesson. The practice files contain the complete source listings for all the applications pissd in this book, as well as any res ources, such as bitmaps and databases, that youll charter to complete the exercises. For those of you who like to know all the details, heres a list of the Visual Basic and Visual C projects on the practice disk Project Chapter 1 ReadBooks Chapter 2 ReadMoreBooks Chapter 3 CodeAnalysis CodeAnalysis2 Chapter 4DeckOfCards Chapter 5 TheBank ARoundButton Chapter 6 ABetterBank ABetterLibrary Variations commentary This simple program renders the basics of creating, instantiating, and victimization a sieve. This program expands on the ReadBooks program and adds constructors. These two applications demonstrate different approaches to using conformation properties, and the interaction of crystalize properties and the DataGrid control. This application explores categorise methods by using dynamic creation of Windows Forms controls and drag-and-drop operations. This simple application demonstrates the basics of variance hereditary pattern. This small project shows how easy it is to de rive rom a Windows Forms control and redefine its drawing. This adaptation of Chapter 5s TheBank application uses an abstract class as a base class. This improvement on Chapter 1s ReadBooks application uses a strongly exampled collection. This application contains code snippets demonstrating variations on inheritance. Chapter 7 TrainGame ThrowSystemException PersonList Project Chapter 8 GamesLibrary Memory Chapter 9 MoveIt Points Chapter 10 PatternMaker Chapter 11 BetterCard SortablePoint Singleton Chapter 12 VectorAlgebra Chapter 13 serialise DataSetExercise Chapter 14 This application introduces delegates, events, and user-drawn controls in the context of a simple game.This small program throws a system exception and recovers by using exception handling. This application creates and throws a custom application exception. Description The GamesLibrary project creates a component library containing objects used to develop the simple Memory card game This application covers the basic s of creating and accomplishing an interface. The Points project contains objects that practice the IComparable, IFormattable, and IEnumerable interfaces. Moving beyond the basics of inheritance, the PatternMaker program makes extensive use of inheritance and polymorphism. This improvement on the Card class from Chapter 4 uses static methods to liminate the projects dependency on file locations. The SortablePoint application from Chapter 10 is made more flexible through static properties. Static palm are used to follow up the Singleton design pattern. The mathematical concept of vectors is used to demonstrate the description and use of operator overloading in Visual C. The Serialize application demonstrates the use of binary and XML serialization of data. This very simple ADO. NET application reads data from an Access database. PatternMaker Uninstall the practice files This example uses the PatternMaker exercise from Chapter 10 to demonstrate the way to make design changes afte r the i nitial development of an application.If you are using the Windows XP Professional operating system, follow these steps to attain the practice files from your computer. If you are using a different version of Windows, refer to your Windows Help documentation for removing programs. 1. Click Start, and then click hold up Panel. 2. In Control Panel, click make sense Or Remove Programs. 3. In the add on Or Remove Programs window, click OOP Visual Basic And C . NET Code in the Currently Installed Programs list. 4. Click Change/Remove. The Confirm File Deletion dialog appears. 5. Click Yes to delete the practice files. 6. Click finis to close the annex Or Remove Programs window. 7. Close Control Panel.Conventions and Features in this Book This book uses conventions designed to make the information more open and easier to follow. The book also includes features that contribute to a deeper understanding of the material. Conventions Each exercise is a serial usualation of tas ks. Each task is presented as a series of numbered steps. If a task has only one step, the step is guided by a round bullet. Notes labeled tip provide more information for completing a step successfully. Notes labeled important alert you to information you need to check before continuing. The book uses typographic styles to help organize the information presented. The following table describes the styles used. Style Code Italics Used for Code that you eccentric person in Method argument or parameter Event process Field Fully Qualified notice Keyword Method Property observe Example Visual Basic frequent Class Book block up Class // Visual C common class Book aBook showPage_Click m_shelf SomeBook. schoolbook mankind, macrocosm, If, if earnPage listOfBooks Roman Other Features Boolean set Class name Control type Data type Event Form stoolspace Parameter type Property True, true, False, false Book, Library, Train ListBox, textbookBox suck, reap, whole number, int C lick Form1 ReadBooks String, string, Integer, int NameShaded sidebars throughout the book provide more in-depth information about the exercise. The sidebars might contain debugging tips, design tips, or topics you might wish to explore further. Each chapter ends with a Quick Reference section. The Quick Reference provides a brief review of the syntax and techniques presented in the chapter. Corrections, Comments, and Help Every effort has been made to ensure the accuracy of this book and the contents of the practice files on the companion CD. Microsoft Press provides plantions and extra content for its books through the serviceman gigantic Web at http//www. microsoft. com/mspress/support/If you have lines, comments, or ideas regarding this book or the companion CD, please position them to Microsoft Press. Send e-mail to emailprotected com Or send postal mail to Microsoft Press Attn Step by Step Series Editor One Microsoft Way Redmond, WA 98052-6399 disport note that support for the Visual Studio . NET software product itself is not offered through the preceding address. For help using Visual Studio . NET, visit http//support. microsoft. com. Visit the Microsoft Press World Wide Web Site You are also invited to visit the Microsoft Press World Wide Web site at http//www. microsoft. com/mspress/Youll find descriptions for the complete line of Microsoft Press books, information about ordering titles, notice of special features and events, additional content for Microsoft Press books, and much more. You can also find out the la establish in Visual Studio . NET software developments and parole from Microsoft Corporation at http//msdn. microsoft. com/vstudio/nextgen/ Check it out Chapter 1 Writing Your First Object-Oriented Program Overview ESTIMATED TIME 2 hr. 30 min. In this chapter, youll learn how to answer which classes to implement in your program. Create a class with cases, properties, and methods. Use a class in an application. Use Microsoft Vis ual Studio . NET tools to create a class translation. Classes are the building blocks of object-oriented programs. Object-oriented program design is compulsive by the objects in the problem you need to solve. If your goal is to automate class registration, you might create classes for the instructor, student, and class schedule objects. Objects also have properties that describe them and their behavior. These are implemented as properties and methods of a class. Just as an instructor has a name, so does the Instructor class have a Name topographic point.To assign a student to a class, youd need to find an open section in the schedule. So your ClassSchedule class might implement a FindOpenSection method. The method would likely check the variable, called a field, in the class in which youve stored information about sections. In this chapter, youll learn how to depict the objects in your problem domain and their properties and behaviors (methods). Using this analysis, youll design and implement the classes using property and method programming constructs. Youll then declare and initialize the variables of the classes youve coded.Finally, youll implement the solution to your problem by calling the properties and methods of the class variables. Reading Books Your First Object-Oriented Program Your task in this chapter is to implement a program that displays large text files in page- size plot of lands. Typically, your task begins with a precondition, perhaps complete, perhaps not. The specification for Chapter 1 follows You have downloaded on your computer the text of several books. You requisite to be able to select a book and read one particular page at a time. You also want to be able to set the continuance of a page. Youve already decided which user interface you want to use its shown hereAs you look at the user interface, you can see that you need to add some controls to a Windows form a ListBox, a Rich textbookBox, two NumericUpDown controls, and som e labels. How will you store the texts of the books? How will you fill the list? How will you retrieve the correct page of the book that you want to read? You can use object-oriented programming to answer these questions. Designing the Classe s Before you can implement your classes, you must decide which classes you need. First you look for the objects in the problem. Having found the objects, you then look for properties, which are characteristics or qualities that belong to the object, and methods, which are behaviors of the object.You can choose from many shipway to design the classes in an application. The approach presented here begins with a textual analysis of the problem. The nouns are selected as candidates for classes, while verbs become candidates for the methods. In the hightail it of the analysis, youll eliminate many of the nouns as candidates, and you might discover classes that arent among the nouns in the specification. After you localise the objects, properties, and methods that belong to your classes, you can then write the class specification that youll use in the implementation. Find the classes . Read the problem argument, and find all the nouns. You have downloaded on your computer the text of several books. You want to be able to select a book and read one particular page at a time. You also want to be able to set the duration of a page. 2. Eliminate candidates. Reasons to eliminate a candidate include The class based on the noun would have only properties or only methods. The class based on the noun wouldnt be relevant to the problem. The class based on the noun wouldnt represent one object.You can eliminate the irrelevant candidates computer and time. Length (of a page) is precisely an integer survey and wouldnt generate enough behavior to characterise as a class. The alike is true of text in this examplethe only thing to be done with it is to display a piece of it, a page. By the same reasoning, page is also not a class. T hat leaves book and books. Books is just the plural of book , so you are left(a) only with book as a potential class. But you arent finished yet. 3. Search for missing candidates. Consider this specification, The dealer deals four separate to each player. Theres no mention of a prettify of cards, although deck is a likely class in that problem. Remember eliminating books? some other class does, in fact, represent the properties and behavior of a group of books. You can call this class Library. The library concept is different from the book concept. A book has a title and text and can be read. A library contains many books, which can be checked out and go pasted. left wing with the Book and Library classes, you can now search for properties and methods. Find the methods and properties 1. Read the problem statement, and find all the verbs. You can leave out the share verbs, such as is, was, and have.As in the case of the nouns, textual analysis of verbs is just the starting poi nt for finding the methods. You have downloaded on your computer the text of several books. You want to be able toselect a book and read one particular page at a time. You also want to be able to set the length of a page. 2. Consider each verb. Is it a method, or does it indicate a method? Is it relevant to the problem? Downloaded and want are clearly irrelevant to the problem. Select is an operation of the Library class. In a real library, this action would correspond to finding a book on the shelf and checking it out. So the Library has a handicap method.Theres also a hidden property here because a book needs a title. Read is an operation of the Book class. This method gets you to read one particular page, so it can be named depositPage. The verb set indicates that a property needs to be changed, and that property is the length of a page, PageLength. 3. The same nouns that you eliminated as classes might in fact be properties of those classes. text edition, length (of a page), and page were eliminated as classes. A book does need text, so Text becomes a property of Book. You discovered that PageLength is a property in considering the verb set.Page represents one section of the text and represents the result of the GetPage operation, so it isnt a property. 4. Look for missing properties and methods. If youre going to check books out of the library, you need a way to add books to the library and return the checked-out books. A CheckIn method will handle this. Testing the Class Design Reread the problem, and determine whether your classes, with their properties and methods, provide the functionality necessary to solve the problem. You have downloaded on your computer the text of several books. Do you have a way of storing and organizing several books?Yes, you can create one Book for each book and one Library to store them all. You want to be able to select a book and read one particular page at a time. Can you select one book and read one page? Yes, books c an be selected by their titles, and the GetPage method retrieves one page. You also want to be able to set the length of a page. Can you set the length of a page? Yes, the Book class has a PageLength property. The results are shown in the following table. The methods are shown as they might be declared in Visual Basic. Class Book Properties Integer PageLengt h Methods GetPage (pageNumber As Integer) As String Class Library Creating the Book Class PropertiesString Text String rubric Methods CheckIn (aBook As Book) CheckOut(title As String) As Book The following exercise covers the basics of class implementation using the Book class as an example. To implement the Library class, youll use some of the development tools provided by the Microsoft Visual Studio . NET integrated development environment (IDE). Create the book class 1. In the IDE, click the File menu, point to New, and then click Project. The New Project dialog box opens. 2. Select Visual Basic Projects or Visual C Projects in the Project Types tree, click Windows Application in the Templates list. 3. visualise ReadBooks in the Name box, and click OK. 4. Display the theme explorer by selecting Solution Explorer on the View menu. Click the ReadBooks project in the Solution Explorer. 12. On the Project menu, click work Class. The Add New Item dialog box appears, as shown here 13. Enter either Book. vb or Book. cs in the Name box, depending on the language you are using. Note that the class name begins with a capital garner and is singular. 14. Click Open. The IDE adds a file to your project. The file includes the basic definition of a class, as shown in the following two screen shots.The Visual Basic class contains the minimum for a class declaration. Heres the syntax for declaring a class in Visual Basic Class ClassName End Class In this case, the class is named Book. The IDE adds the everyday modifier thats shown to indicate that the class can be used throughout the project. The Visual C class co ntains the class declaration as well as a constructor. Heres the syntax for declaring a class in C class ClassName A constructor contains code to initialize the palm of a class and perform other class initialization functions. In C, it has the same name as the class. A constructor isnt required.Ill talk more about constructors in Chapter 2, Creating Class Instances with Constructors. Add the Text and PageLength fields A field is a variable declared in a class block. Fields can be any . NET data type, such as Integer or Boolean . NET class, such as TextBox or ListBox or any class that you have created. 1. Locate the beginning of the class definition. In Visual Basic, the class definition begins immediately after the line that shows the class name. In Visual C, the class definition begins after the opening curly brace of the class. 2. Add the following code inside the class to create Text and PageLength fields. 3. Visual BasicPublic Text As String = Public PageLength As Integer = 10 // Visual C mankind string Text = p in the public eye(predicate) int PageLength = 10 Tip By convention, the initial letters of names of public members (fields, properties, methods, and events) of a class are capitalized (Textfield) or are intercapitalized (PageLength field). According to the code, you have specified initial values for the fields the empty string for Text and 10 for PageLength. A basic tenet of object-oriented programming is that an object should abide by a consistent state. That means that the state of the object (the values of its fields) should represent a usable state.If you didnt initialize the fields, values would default to for the Text field and 0 for the PageLength field. If those were acceptable values for a book, you could leave them uninitialized. But because compilers and their default values change, you can prevent maintenance problems by initializing the fields. Your lymph node code (the code that uses a Book object) is able to read and write to any field declared with the public keyword (Public in Visual Basic and public in Visual C). Providing direct access to the class data is a violation of the object-oriented principle of information hiding, which stipulates that the leaf node has no knowledge of the underlying data structure of an object.In the next section, youll learn how to seize the client code to get and set the entitle of the Book without freehanded away details about the implementation. Add the form of address property A property is a programming construct that allows your code to get and set a value. Typically, the code in the property constructor will get and set the value of a private field in the class. In client code, a public field and a property are used in the same wayfor example, SomeBook. Text and SomeBook. Title. 1. Add the following code to the Book class after the Text and PageLength declarations. 2. Private m_title As String Visual Basic private string m_title // Visual CThis code creates a private field in the Book class. thickening code doesnt have access to this property. Tip Private fields of a class are declared using the m_ prefix to identify them as member data. Private field names arent capitalized. 3. Add the following code to the Book class, after the m_title declaration. 4. Visual Basic 5. Public Property Title() As String 6. Get 7. government issue m_title 8. End Get 9. Set(ByVal value As String) 10. m_title = value 11. End SetEnd Property 12. // Visual C 13. public string Title 14. get 15. return m_title 16. 17. set 18. m_title = value 19. These syntax blocks define class properties.The Title property appears in the IntelliSense drop-down list just like any other property, such as the old(prenominal) TextBox. Text or Form. Backcolor. The property block allows you to control access to the property. You can add validation code to the Set block to ensure that only reasonable values are assigned to the underlying m_title field. Note Please notice an important difference between fields and properties. A place is reserved in memory for fields. They contain the actual data of the class. Properties provide access to the data but are not data themselves. In this book, I use the word set to mean changing a property. I use the word get to mean retrieving the value of a property.The Get and Set blocks of a property can be called getters and setters, or accessors . The property block is more flexible than youve seen here. Properties can be public or private, read/write, read-only, or write-only. In Visual Basic, the property statements can even take a parameter. By the way, I cover properties in detail inChapter 2, but I need to talk about them at least a little bit in this chapter. A fiddling Bit About Properties We can use the word properties, in a general object-oriented sense, to mean the descriptive information about an object. We can also use properties to mean the particular syntactic construct provided by Visual Basic and C.Th e particular meaning of the word can be determined by context. Use properties to validate class data and disguise class implementation. You have to make a strong case for using public fields in a class. The addition of a property to a class to control access to the underlying data requires nominal effort. The benefit of this practice is that you can easily add validation or change the implementation if you need to without affecting clients already using your objects. Add the GetPage method Add the GetPage method to the class definition after the field declarations. Visual BasicPublic blend in GetPage(ByVal pageNumber As Integer) As String dismal start As Integer = (pageNumber -1) * PageLength If (start Text. Length) And (start = 0) Then If (start + PageLength) Text. Length Then Return Text. Substring(start, PageLength) Else Return Text. Substring(start, Text. Length start) End If Else Return End IfEnd Function // Visual C public string GetPage(int pageNumber) int start = (pageNumber 1) * PageLength if ((start Text. Length) && (start = 0)) if ((start + PageLength) Text. Length) return Text.Substring(start, PageLength) else return Text. Substring(start, Text. Length start) else return In Chapter 3, Fields and Properties, youll see how we can replace the GetPage method with a construct known as an indexer in Visual C or with a default Item method in Visual Basic. The complete class definitions for our project are shown here Visual Basic Public Class Book Public Text As String = Public PageLength As Integer = 10 Private m_title As String Public Property Title() As String Get Return m_title End Get Set(ByVal Value As String) m_title = Value End Set End PropertyPublic Function GetPage(ByVal pageNumber As Integer) As String Dim start As Integer = (pageNumber 1) * PageLength If (start Text. Length) And (start = 0) Then If (start + PageLength) Text. Length Then Return Text. Substring(start, PageLength) Else Return Text. Substring(start, Tex t. Length start) End If Else Return End If End FunctionEnd Class // Visual Cusing Systemnamespace ReadBooks /// /// Summary description for Book. /// public class Book public string Text = public int PageLength = 10 private string m_title public Book() // // TODO Add constructor logic here // public string Title get return m_title set m_title = value ublic string GetPage(int pageNumber) int start = (pageNumber 1) * PageLength if ((start Text. Length) && (start = 0)) if ((start + PageLength) Text. Length) return Text. Substring(start, PageLength) else return Text. Substring(start, Text. Length start) else return Fields, properties, methods, and constructors can appear in any order in a class definition. Good organization benefits emerging readers of your code.Heres a common organization and, in fact, the one I used in this book Field declarations Constructors Properties Methods Using the Book Class in an Application Youve just finished implementing t he Book class. The class definition is just a template for an object. To put data in the fields and properties, you have to create an antecedent of the class in memory this action is known as instantiation. When you create an obiter dictum, a section of memory is set aside to hold the fields of the object. If you create another instance of the class, another section of memory is set aside for its fields. You arent going to implement the full solution yet.First you need to write some code to test your class. Youll create two instances of the Book class in the ReadBooks project, and youll display the quarter page of each book. (These will be very short books. ) Youll create a cookbook and a book of fairy tales, so youll need to create two separate instances of the Book class. Instead of creating a heart interface, youll write just enough code to see whether your class is working as you expected. Test Drivers A short program to test a class is called a driver. Its a good idea to ex ercise your class a bit with a driver before adding the class to a larger program.Use the driver to test your class without the interference of other code in the program. Create an instance of Book 1. In the Solution Explorer, double-click Form1 to open it in the Windows form designer. If Form1 is opened in the code editor, select View, Designer. 2. Drag a button from the Toolbox onto Form1. If the Toolbox isnt visible, select View, Toolbox. 3. Right -click the button, and click Properties on the shortcut menu. In the Properties window, set the Name property of the button to showPage and set the Text property to Show Page. The button on the Windows form is created from the Button class.Name and Text are properties of the Button class. So we can talk about getting and setting these properties. Form1 is a class as well, and the button you just created is a field of the Form1 class. 4. Double-click the button to create the Click event method. 5. Add the following code in bold face to the Click event to create a book of fairy tales. 6. Visual Basic 7. Private Sub showPage_Click(ByVal sender As System. Object, _ 8. ByVal e As System. EventArgs) Handles showPage. Click 9. Dim fairyTales As Book 10. fairyTales = New Book() 11. End Sub 12. // Visual C 13. rivate void showPage_Click(object sender, System. EventArgs e) 14. Book fairyTales 15. fairyTales = new Book() 16. Add the following code to set the Text, PageLength, and Title properties immediately after the code you entered in step 5 17. Visual Basic 18. fairyTales. Text = Once upon a time there was a bear. 19. fairyTales. PageLength = 8fairyTales. Title = Fairy Tales 20. // Visual C 21. fairyTales. Text = Once upon a time there was a bear. 22. fairyTales. PageLength = 8 fairyTales. Title = Fairy TalesWhen the instance of Book is created, its fields contain the values specified in the class definition. The Text field is an empty string, the page length is 10, and the title is blank. Notice that it makes no difference in the client code whether you use a field or a property. 23. Add the following code after the fairyTales code to create another instance of the Book class. (This instance will be a recipe book. ) 24. Visual Basic 25. Dim cookies As Book = New Book() 26. cookies. Text = coffee bean chip cookies are the most delicious co okies. 27. ookies. PageLength = 8 28. cookies. Title = Cookie Recipes 29. // Visual C 30. Book cookies = new Book() 31. cookies. Text = cocoa chip cookies are the most delicious co okies. 32. cookies. PageLength = 8 cookies. Title = Cookie Recipes In this case, you used a different syntax for declaring and initializing a variable of the Book class. Visual Basic and Visual C allow declaration and initialization in the same statement. Declaring and initializing in the same statement has the following advantages Programmers are less likely to forget to initialize the variable. When a class defines a constructor with parameters, the fields can be initial ized at the same time. (Youll create constructors with parameters in Chapter 3. ) Use an instance of the Book class 1. Add the following code after the cookies code to display some of the text of the two books. In later chapters, youll learn other ways to return the text of a particular page in the book. 2. Visual Basic 3. Dim page As Integer = 3 4. Dim musical composition As String 5. report = Page & page. ToString() & ControlChars. CrLf _ 6. & fairyTales. Title & & fairyTales. GetPage(page) _ 7. ControlChars. CrLf _ 8. & Cookies & cookies. GetPage(page) 9. MessageBox. Show(report) 10. report = Titles + fairyTales. Title & and & cookies. Title 11. MessageBox. Show(report) 12. // Visual C 13. int page = 3 14. string report 15. report = Page + page. ToString() + 16. + fairyTales. Title + + fairyTales. GetPage(page) + 17. + cookies. Title + + cookies. GetPage(page) 18. MessageBox. Show(report) 19. report = Titles + fairyTales. Title + and + cookies. Title MessageB ox. Show(report)This bit of code demonstrates that there are two separate instances of the Book class. We can refer to these instances using the variables fairyTales and cookies . The object-oriented concept that permits each instance to be referred to separately is known as identity. Youll see in later chapters that the identity principle doesnt mean that you have to create a variable for each instance. Creating so many variables is unwieldy if you need hundreds of instances of a class. Identity does mean that you can refer to each instance separately when you need to.Notice that when you created an instance of Book, the fields of fairyTales were changed and the GetPage method was called. Later on we retrieved the value of the Title property. The value of Title was unchanged after the GetPage method was called. The fact that the value was unchanged demonstrates the concept of object state, the idea that the fields retain their values between method calls. Compare the way the GetPag e method kit and caboodle with a method that has variable declarations. After the GetPage method ends, the variables go out of scope and their values are lost to the application. 20. Press F5 to run the code. Click the Show Page button.The results are shown here Click OK, and the book titles are displayed in a message box as shown here Click OK, and then close the application. Youve now created a class, Book, and two instances of it. Your code sent a message to the Book class through the GetPage method to ask for the third page of the text. In the next sections, youll implement another class, Library. This time, however, youll let some of the IDE tools do some of the syntactic work for you. Using the Class View The IDE provides a Class View that displays a tree view of the class structure of the project, namespaces, and classes.The Class View can share the same window as the Solution Explorer. On the View menu, click Class View to open the Class View. The expanded Class View is sho wn below for Visual Basic and Visual C, respectively. The highest- train node represents the project, ReadBooks. The next level of nodes represents the namespaces in the project. A project can contain several namespaces in this case, theres only one. The project namespace contains two classes the class that we created, Book, and the class for the Windows form, Form1. The Book class contains two public fields, PageLength and Text, epresented by blue blocks, and one private field, m_ti
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.