Object-OrientedProgramming andDesign Using Java (Third Edition) Object-OrientedProgrammingand Design UsingJava(ThirdEdition) Course Edition: 1.0 ACKNOWLEDGMENTS Project Team Content Developer: Aparna Venkatesan and Sivanarul S Content Manager: Srisai V. K. Graphic Designer: Rajaram S Project Manager: Balakumar R Media Instructional Designer: Aparna Venkatesan and Sivanarul S Content Editor: Gopalakrishnan V Materials Editor: Hannah Pauline Technical Reviewer: Arunkumar J Project Technical Support: Mike Toscano NOTICES DISCLAIMER: While Element K Corporation takes care to ensure the accuracy and quality of these materials, we cannot guarantee their accuracy, and all materials are provided without any warranty whatsoever, including, but not limited to, the implied warranties of merchantability or tness for a particular purpose. The name used in the data les for this course is that of a ctitious company. Any resemblance to current or future companies is purely coincidental. We do not believe we have used anyones name in creating this course, but if we have, please notify us and we will change the name in the next revision of the course. Element K is an independent provider of integrated training solutions for individuals, businesses, educational institutions, and government agencies. Use of screenshots, photographs of another entitys products, or another entitys product name or service in this book is for editorial purposes only. No such use should be construed to imply sponsorship or endorsement of the book by, nor any afliation of such entity with Element K. This courseware may contain links to sites on the Internet that are owned and operated by third parties (the External Sites). Element K is not responsible for the availability of, or the content located on or through, any External Site. Please contact Element K if you have any concerns regarding such links or External Sites. TRADEMARK NOTICES: Element K and the Element K logo are trademarks of Element K Corporation and its afliates. Java is a registered trademark of Sun Micrososystems, Inc., in the U.S. and other countries; the other Sun Micrososystems, Inc., products and services discussed or described may be trademarks of Sun Micrososystems, Inc. All other product names and services used throughout this course may be common law or registered trademarks of their respective proprietors. Internet Explorer is a registered trademark of Microsoft Corporation in the U.S. and other countries; the other Microsoft products and services discussed or described may be trademarks of Microsoft Corporation. All other product names and services used throughout this course may be common law or registered trademarks of their respective proprietors. Copyright 2008 2008 Element K Corporation. All rights reserved. Screenshots used for illustrative purposes are the property of the software proprietor. This publication, or any part thereof, may not be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, storage in an information retrieval system, or otherwise, without express written permission of Element K, 500 Canal View Boulevard, Rochester, NY 14623, (585) 240-7500, (800) 478-7788. Element K Coursewares World Wide Web site is located at www.elementkcourseware.com. This book conveys no rights in the software or other products about which it was written; all use or licensing of such software or other products is the responsibility of the user according to terms and conditions of the owner. Do not make illegal copies of books or software. If you believe that this book, related materials, or any other Element K materials are being reproduced or transmitted without permission, please call (800) 478-7788. Object-Oriented Programming and Design Using Java (Third Edition) ii Part Number: NH85969 (IGEE) OBJECT-ORIENTED PROGRAMMING AND DESIGN USING JAVA (THIRD EDITION) LESSON 1- IDENTIFYING THE KEY PHASES IN SOFTWARE PRODUCT DEVELOPMENT A. Identify theAspects of aGoodProject Plan . . . . . . . . . . . . . . . . . . . . . . . . . 2 Phases inSoftwareDevelopment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Project Plans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Guidelines for DevelopingaProject Plan . . . . . . . . . . . . . . . . . . . . . . . . . 4 B. Identify theElements in SoftwareRequirements Specications . . . . . . . . . 7 TheSoftwareRequirements Specications Document . . . . . . . . . . . . . . 7 TheRequirements of aSoftwareProject . . . . . . . . . . . . . . . . . . . . . . . . . . 8 UseCases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 C. DeterminetheSteps Involvedin DesigningaClass Structure. . . . . . . . . . . 12 Classes andObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Class StructureDesign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Attributes of aClass Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 D. ExaminetheCodingProcess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 TheCodingProcess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 LESSON 2- EXPLORING SOFTWARE DESIGN METHODOLOGIES AND TOOLS A. Identify theCharacteristics of SoftwareDesign Methodologies. . . . . . . . . 22 SoftwareDesignMethodologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Elements of SoftwareDesignMethodologies . . . . . . . . . . . . . . . . . . . . . . 22 B. ExaminetheDifferent Types of UML Diagrams. . . . . . . . . . . . . . . . . . . . . . . . 24 Notations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 TheUniedModelingLanguage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 UniedModelingLanguageDiagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 CONTENTS Contents iii LESSON 3- DESCRIBING THE CHARACTERISTICS AND BENEFITS OF OBJECT-ORIENTED PROGRAMMING A. ExaminetheDifferent Approaches toProblem-Set Analysis . . . . . . . . . . . 34 ProgrammingProblemSets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Approaches toAnalysis. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 TheAlgorithmicApproach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 TheObject-OrientedApproach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Comparisonof theTwoApproaches toAnalysis . . . . . . . . . . . . . . . . . . . 36 B. DescribetheEvolution of Object-OrientedProgrammingLanguages . . . 39 Generations of ProgrammingLanguages . . . . . . . . . . . . . . . . . . . . . . . . 39 Object-OrientedProgrammingLanguages. . . . . . . . . . . . . . . . . . . . . . . 41 Object-BasedProgramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 C. Identify theBenets of Object-OrientedProgramming . . . . . . . . . . . . . . . 43 Benets of Object-OrientedProgramming. . . . . . . . . . . . . . . . . . . . . . . . 43 LESSON 4- IDENTIFYING THE ELEMENTS OF OBJECT-ORIENTED PROGRAMMING A. DeneObject Relationships andAttributes . . . . . . . . . . . . . . . . . . . . . . . . . 48 Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Classicationof Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Abstraction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Approaches toAbstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 InformationHiding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Modularity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 JavaPackages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 B. Identify theRelationshipBetween Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Subclasses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Levels of Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 CONTENTS Object-Oriented Programming and Design Using Java (Third Edition) iv C. Implement MultipleForms of theSameProcedure . . . . . . . . . . . . . . . . . . . 86 Polymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Types of Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 MethodOverload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 MethodOverride. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 LESSON 5- DETERMINING THE USE OF OBJECT-ORIENTED PROGRAMMING IN WINDOWED APPLICATIONS A. ExploretheStructureandWorkingof aWindowedApplication. . . . . . . . . 98 EvolutionStages inApplicationDevelopment. . . . . . . . . . . . . . . . . . . . . 98 Applicationof OOPs inWindowedApplications . . . . . . . . . . . . . . . . . . . 100 TheWorkingof aWindowedApplication . . . . . . . . . . . . . . . . . . . . . . . . . 100 B. ExaminetheUseof Frameworks in Developingan Application . . . . . . . . . 104 Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Class Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 LESSON 6- EXAMINING APPLICATION DEVELOPMENT FOR THE INTERNET A. ExaminetheWebCommunication Process . . . . . . . . . . . . . . . . . . . . . . . . . 108 WebApplications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 WebElements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 StaticandDynamicWebPages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 TheWebCommunicationProcess. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 B. ExaminetheTechnologies Involvedin WebCommunication . . . . . . . . . . 111 Server-SideObjects andTechnologies . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Client-SideObjects andTechnologies . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 WebCommunicationinDynamicPages . . . . . . . . . . . . . . . . . . . . . . . . . 117 CONTENTS Contents v C. Identify WebObjects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 TheBrowser Document Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 TheProcess of DisplayingaWebPage . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 CGI Executables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Server Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 TheJavaRuntimeEnvironment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 JavaClasses andObjects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 TheJavaDevelopment Kit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 D. CreateaWeb-basedApplication UsingJava . . . . . . . . . . . . . . . . . . . . . . . 125 Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 LifeCycleof anApplet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 LESSON LABS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 GLOSSARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 CONTENTS Object-Oriented Programming and Design Using Java (Third Edition) vi ABOUT THIS COURSE You have probably written software code that focuses on the procedures of a system. You may now need to write code that focuses on the properties of the objects involved in the system rather than the procedures. In this course, you will examine the concepts underlying the object- oriented programming model. Applications developed with focus on the procedures carried out within a system require numerous changes in coding when small changes occur in procedures. By shifting the focus of the program from the procedures to the entities of the system and their interactions, you can create code, which will be less inuenced by changes in system procedures. CourseDescription Target Student The target student is interested in learning general object-oriented programming concepts. This course provides a foundation for students desiring to go on and learn one or more object- oriented programming languages. CoursePrerequisites To ensure your success, we recommend you rst take the following New Horizons courses or have equivalent knowledge: Introduction to Programming using Java HowtoUseThis Book As aLearningGuide Each lesson covers one broad topic or set of related topics. Lessons are arranged in order of increasing prociency with Object-Oriented Programming and Design Using Java; skills you acquire in one lesson are used and developed in subsequent lessons. For this reason, you should work through the lessons in sequence. INTRODUCTION Introduction vii We organized each lesson into results-oriented topics. Topics include all the relevant and sup- porting information you need to master Object-Oriented Programming and Design Using Java, and activities allow you to apply this information to practical hands-on examples. You get to try out each new skill on a specially prepared sample le. This saves you typing time and allows you to concentrate on the skill at hand. Through the use of sample les, hands-on activities, illustrations that give you feedback at crucial steps, and supporting back- ground information, this book provides you with the foundation and structure to learn Object- Oriented Programming and Design Using Java quickly and easily. As aReviewTool Any method of instruction is only as effective as the time and effort you are willing to invest in it. In addition, some of the information that you learn in class may not be important to you immediately, but it may become important later on. For this reason, we encourage you to spend some time reviewing the topics and activities after the course. For additional challenge when reviewing activities, try the What You Do column before looking at the How You Do It column. As aReference The organization and layout of the book make it easy to use as a learning tool and as an after- class reference. You can use this book as a rst source for denitions of terms, background information on given topics, and summaries of procedures. CourseObjectives In this course, you will examine the principles of object-oriented programming and design. You will: identify the key phases in software product development. explore software design methodologies and tools. describe the characteristics and benets of object-oriented programming. identify the elements of object-oriented programming. determine the use of object-oriented programming in windowed applications. examine application development for the Internet. CourseRequirements Hardware ClassroomComputers On each students machine, you need the following hardware: Intel
Pentium
1 GHz or higher processor.
512 megabytes (MB) of RAM or more. INTRODUCTION Object-Oriented Programming and Design Using Java (Third Edition) viii 10 gigabytes (GB) of available hard-disk space or more. CD-ROM drive or DVD-ROM drive. Sound card. Headphones or speakers to hear sound effects. Color monitor with a 16-bit or greater video card. Monitor with 1024 x 768 resolution. A mouse or other pointing device. Internet connection. Display system to project the instructors computer screen. Software Microsoft
Windows
XP Professional with Service Pack 2 or Microsoft
Windows Vista
Business Edition. Microsoft
Internet Explorer
6.0 or its later versions.
WinZip or a similar compression/extraction utility. A source code editor, Notepad++ 5.0 or above. Java SE Development Kit (JDK) 6 Update 7. Class Setup Install Windows XP Professional 1. Install Windows XP Professional on the C drive using the following parameters: a. Accept the license agreement. b. Create a 4 GB partition on the C drive. c. Format the C partition to NTFS. d. Select the appropriate regional and language settings. e. Enter the appropriate name and organization for your environment. f. Enter the product key. g. For each student computer, congure the settings: 1. Name of computer: Computer# (where # is a unique integer representing the student computer) 2. Administrator password: password 3. Select your time zone. 4. Select the Typical network conguration. 2. Download and install Windows Internet Explorer 7. Microsoft
Internet Explorer 7 can be
downloaded at http://www.microsoft.com/windows/downloads/ie/getitnow.mspx?wt_ svl=20510a&mg_id=20510b. 3. Download and install any updates from Microsoft Update. INTRODUCTION Introduction ix CreateaDownloads Folder You will download all of the required software into the various folders that you create in this procedure. 1. Create a Downloads folder on the Desktop. 2. Inside the Downloads folder, create two new folders with the following names: Notepad++ JDK DownloadandInstall Notepad++ Download and install Notepad++ 5.0.3: 1. In Internet Explorer 7, in the address bar, type http://notepad-plus.sourceforge.net/uk/ site.htm and press Enter. 2. Click the Download link. 3. Under the Binary les heading, click the Download Notepad++ executable les link. 4. In the SourceForge.net: Files window, if necessary, expand npp 5.0.3 bin. 5. Click the npp.5.03. Installer.exe link. 6. If you experience problems with the download, click the this direct link link. 7. In the File Download Security Warning dialog box, click Run. 8. In the Internet Explorer-Security Warning dialog box, click Run. 9. Save this executable le to the Notepad++ folder you had created. 10. In Windows Explorer, on the desktop, navigate to the Downloads\Notepad++ folder. 11. Double-click the npp.5.0.3.Installer.exe le. 12. In the Installer Language dialog box, verify if English is selected and click OK. 13. In the Notepad++v5.0.3 setup dialog box, click Next. 14. In the License Agreement dialog box, click I Agree. 15. In the Choose Install Location dialog box, click Browse. 16. In the Browse For Folder dialog box, click Make New Folder, name the new folder Notepad++ and then click OK. 17. Click Next. 18. In the Choose Components dialog box, check the As default html viewer check box. 19. Click Install. 20. Click Finish. 21. Close the change.log le and then close the Notepad++ application. Install Java
SE Development Kit 6 Update7
1. In Internet Explorer, navigate to http://java.sun.com/javase/downloads/index.jsp 2. Click the Previous Releases link. 3. Click the Archived Releases link. 4. From the JDK/JRE - 6 drop-down list, select 6 Update 7 and click Go. 5. Click the Download JDK link. INTRODUCTION Object-Oriented Programming and Design Using Java (Third Edition) x 6. From the Platform drop-down list, select Windows. 7. Click the jdk-6u7-windows-i586-p.exe link. At the time this course was written, the JDK (jdk-6u7-windows-i586-p.exe le) was available for download using the above given procedure. 8. In the Internet Explorer-Security Warning dialog box, click Save. 9. Save this executable le to the JDK folder you had created. 10. In Windows Explorer, on the desktop, navigate to the Downloads\JDK folder. 11. Double-click the jdk-6u7-windows-i586-p.exe le. 12. In the Java(TM) SE Development Kit 6 Update 7 - License Wizard, click Accept. 13. On the License Agreement page, click Accept. 14. On the Custom Setup page, click Next to install the Java(TM) SE Runtime Environment. 15. On the Custom Setup page, click Next to install Default Java for browsers. 16. On the Java(TM) SE Development Kit 6 Update 7 - Complete Wizard, click Finish to complete the wizard. Set Environment Variables BeforeCompilingthe File For Microsoft Windows XP: 1. Choose StartControl Panel. 2. In the Control Panel window, select System. 3. In the System Properties dialog box, select the Advanced tab. 4. On the Advanced tab, click Environment Variables. 5. In the Environment Variables dialog box, in the System variables section, in the Variable column, select Path. 6. Click Edit. 7. In the Edit System Variable dialog box, in the Variable value text box, place the cursor at the end of the existing text, and type ;C:\Program Files\ Java\jdk1.6.0_07\bin to set the path to the location of the javac.exe le. 8. Click OK. 9. In the Environment Variables dialog box, click OK. 10. In the System Properties dialog box, click OK. 11. Close the Control Panel. For Microsoft Windows Vista: 1. Choose ComputerSystem properties. 2. In the left pane, in the Tasks list, select Advanced system settings. 3. In the User Account Control dialog box, click Continue. 4. In the System Properties dialog box, choose Environment Variables. 5. In the Environment Variables dialog box, in the System variables section, in the Variable column, select Path. 6. Click Edit. INTRODUCTION Introduction xi 7. In the Edit System Variable dialog box, in the Variable value text box, place the cursor at the end of the existing text, and type ;C:\Program Files\ Java\jdk1.6.0_07\bin to set the path to the location of the javac.exe le. 8. Click OK. 9. In the Environment Variables dialog box, click OK. 10. In the System Properties dialog box, click OK. Display FileExtensions Display the le extensions of your documents. 1. Choose StartAll ProgramsAccessoriesWindows Explorer. 2. In Windows Explorer, choose ToolsFolder Options. 3. Select the View tab and uncheck the Hide extensions for known le types check box. Initial Class Setup 1. On the course CD-ROM, run the 085969dd.exe self-extracting le located within. This will install a folder named 085969Data on your C drive. This folder contains all the data les that you will use to complete this course. List of Additional Files Printed with each activity is a list of les students open to complete that activity. Many activi- ties also require additional les that students do not open, but are needed to support the le(s) students are working with. These supporting les are included with the student data les on the course CD-ROM or data disk. Do not delete these les. INTRODUCTION Object-Oriented Programming and Design Using Java (Third Edition) xii Identifying the Key Phases in Software Product Development In this lesson, you will identify the key phases in software product development. You will: Identify the aspects of a good project plan. Identify the elements in software requirements specications. Determine the steps involved in designing a class structure. Examine the coding process. Lesson Time 1 hour(s) LESSON 1 LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 1 Introduction As a programmer, before you start work on the coding aspect of your project, you need to clearly dene the scope and requirements of a project and draw a clear plan on how to go about achieving them. In this lesson, you will identify the key phases in software product development. Suppose you would like to own a home. Before you plunge into the search for your dream home, you must have a denite strategy for buying it. Your strategy might include to check for nances including the budget, look for best mortgage plans, select a real estate agent, shop for a home, make an offer, negotiate terms, and nally sign the papers. Similarly, when you are developing a software application, you need to identify its key phases and provide a structured framework for the development process. This strategic planning of your project will help you remove any obstacles and create a road map to achieving your objective. TOPIC A Identify the Aspects of a Good Project Plan Before writing code for software, it is important that you know the objective of your tasks and the way the project has progressed. To achieve this, you need to know how the software devel- opment phase is executed as a series of steps, which emphasizes the need for good planning. In this topic, you will identify the aspects of a good project plan. Before you go for a vacation, you will organize your tour itinerary which consists of the places to see, hotel accommodation, and any other travel arrangements. If you dont have a proper tour plan, then you might be facing much difficulty. Similarly, delivering customer require- ments on time is a prime requisite in software product development. Formulation and strict adherence to a good project plan will help you manage your resources and time better. If the plan is not adhered to, then there is a possibility of your losing a valuable customer. Phases in Software Development The software development process is a framework based on which any software product is developed. There are several software development models available, each following different approaches to completing the activities and tasks involved. One such approach to software development is the iterative model, which is the famous Software Development Life Cycle (SDLC) process. It is an iterative process consisting of six phases: 1. During the analysis phase, you will study the feasibility and scope of the project. 2. In the design phase, you will develop a project plan before planning the ow of work. 3. In the coding phase, you will write program code based on the accepted design before building the required technical architecture and databases. 4. In the testing phase, you will check whether the developed software application is work- ing as intended. 5. During the integration phase, you will make the developed software available on the mar- ket. Phases in Software Development LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 2 6. In the maintenance and extension phase, you will provide troubleshooting and help desk services to support system users. Project Plans Denition: A project plan is a formal document that contains a generic description about the project; about various sub-tasks and activities involved; about the sequence with which these tasks have to be performed as well as their dependencies with other tasks; about the resources involved; about the estimated start and completion dates; and about the costs involved. This document is accepted and used by management to track the cur- rent phase of the project, the level of completion achieved, and as a record of decisions made with respect to the project. A project plan can be very detailed in its description, or it can be just a summary. It is always best to start with a project plan. Careful planning can mean the difference between a good product that ships on time and a faulty product that is released much later than expected. Project Plans LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 3 Example: Project Plan Details During the initial stages of creating a project plan, you will have to start out with some of the details missing. For instance, you cannot probably assign completion mile- stones and delivery dates until youve at least identied software requirements. Until you know what youre building, its simply not possible to reliably assign delivery dates without severely compromising other aspects of the project. Many good books, software, and templates have been developed to assist in the process of creating a project plan. You can adapt them to meet your needs, and it is usually much quicker to begin with existing tools than to develop them from scratch. Guidelines for Developing a Project Plan Many sound methodologies have been developed as guidelines for developing a project plan. It is always a good idea to get introduced to the sorts of issues that the methodologies address, and to start using a general framework for thinking in an object-oriented way when you embark on a software project. Guidelines: The methodology must identify certain aspects of a project plan in order to make it successful. This includes determining information such as: What are the objectives of the plan or what is the problem or a value addition being addressed by the project? How can these objectives be measured? What are the steps involved in this project? What are the important deliverables of the project and when should they be deliv- ered? Who should have input into the project plan? Who should own the project plan? Who should have access to the project plan? What are the responsibilities of the people who are involved in the plan? How are the people involved in the plan organized? LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 4 What is the estimated project completion date or the timeline? When will the milestones of the project be completed? Example: Sally Brown, a project manager with Our Global Company is assigned the task of pre- paring the project plan for an assignment that involves digitizing the community information of Chermont City. Before she prepares the schedule, she must identify the steps involved in digitizing the community information, the milestones for the project, the resources involved, and the budget for the project. She must also identify the objects of the plan, if there are any product deliverables that have to be met, and when they should be delivered to the client. Based on the information, Sally has to create the project plan which would help Our Global Companys management in tracking the project. Figure 1-1: A sample project plan created to track the digitizing project. LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 5 ACTIVITY 1-1 Framing Project Schedules Scenario: You have been assigned the task of preparing a project schedule for an assignment that involves the building of an information website for the tourism department of Chermont City. Before preparing the schedule, you would like to test your knowledge of identifying the vari- ous aspects of the project plan. 1. In which phase do you check a projects feasibility and scope? a) Analysis b) Design c) Coding d) Testing 2. True or False? You can assign delivery dates in your plan only after knowing what needs to be built. True False 3. True or False? You will be able to draft a complete plan only after the software requirements are in place. True False LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 6 TOPIC B Identify the Elements in Software Requirements Specications You examined the features of a good project plan. However, a complete project plan can be developed only after the software requirements specications are in place. In this topic, you will identify the elements in software requirements specications. The software requirements specications document translates the requirements of the customer into a language that is well understood by the programmer. Because it directly relates to the nal product outcome, preparing a requirements specications document free of ambiguity is essential to develop software that meets customer requirements. The Software Requirements Specications Document Before any design or coding begins, it is necessary to identify what will be required of the program. This process typically involves nding out what the customer or eventual user of the program needs to be able to do. It produces documents with names such as software require- ments specications (srs) or software specications. A software requirements specications document is a document that contains a comprehensive description of the functionality to be incorporated into the software based on customer require- ments. It will contain information about what the software will do; how it will interact with other programs and users in real-world situations; performance aspects such as its speed and response time, its reliability, maintainability, and security information; and design constraints. A good software specications document will help reduce the effort put in by developers and minimize the development cost. This document will act as a base between you and your client in understanding one anothers requirements at any given point in time and as a reference for any contracts signed. The term software requirements specications is also known as functional requirements, user requirements, or software specications. Benets of Software Requirements Specications A properly dened software requirements specications document will act as a basis between yourself and the client in clearly establishing the requirements about what exactly the proposed software will do? Based on the accepted requirements or any changes proposed by your client, you can derive a contract or an agreement between each other. Carefully reviewing each requirement both by you and your client will help in clearing out any misunderstandings, omissions, and inconsistencies in the document. This will considerably help reduce development time. Based on the requirements, you will be able to provide the estimated cost of the product and the time frame within which it can be shipped off to the client. It can also help you gain new users or cus- tomers to the product and will serve as a base for future renements and enhancements. LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 7 Documenting Software Requirements Specications The recommended scope, depth, and form of a software requirements specications document are sometimes the cause of endless debate among software development teams. Some organizations favor the use of words over diagrams, and others favor dia- grams over words. Many software development organizations have set forth extensive rules, guidelines, and templates to facilitate a uniform approach to creating such docu- ments. Much has been written about the subject of writing software requirements specications. If your organization is struggling with dening standards for software requirements specications, you would be well advised to base your companys own standards on one of the many existing sets of templates and guidelines. The Requirements of a Software Project Typically, software requirements specications identify the general aspects of a software project and dene the requirements for the project. Refer to the table for a description of each such general aspect. General Aspect Description Product functions Describe the major functions that the program must perform. User descriptions Describe the major types of users who will be using the program, and how they will be using the program, including which product functions they will use. Operating environment Describes the environment in which the program will operate, including operating systems, hardware that must be supported, and other software with which the program must be compatible. User interface requirements Describe user interface requirements, such as a specic look and feel that needs to be imple- mented, display hardware constraints, and so forth. Software interface requirements Describe other systems that the program must interface with, and dene (or point to other docu- ments that dene) the interface itself. Design and implementation constraints Describe any factors that programmers should be aware of as limitations, such as technologies that must be used or avoided, languages or tools that must be used for development, and so forth. Assumptions and dependencies Describe additional factors that programmers should be aware of as limitations or enablers, such as existing software that the program must inter- face with, dependent software systems that are slated for replacement, and so forth. Performance requirements Describe the performance standards that must be met, if any. Business rules Describe how the software functionality relates to rules of the business or organization that will be using this software. For example, only the attend- ing physician can release the patient from the hospital. LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 8 Use Cases A use case is a description of a type of user accessing a software tool to accomplish a particu- lar task. It is a combination of a user and a particular event, such as a customer using an automated teller machine to withdraw cash. By considering each of the potential users of a program, in each of the various tasks they need to perform, it is possible to identify the types of objects and interactions that need to be implemented. It is very important to work through enough use cases to substantially identify all subtle interactions between potential users. Use cases can be implemented through diagrams, tables, or other forms of notationwhatever works best for the design team. Figure 1-2: Generic and sample use cases. Test Cases A test case is a description of various scenarios that will be constructed and analyzed to iden- tify whether a program runs correctly as designed. Designing test cases in the preliminary stages has several advantages. First, it means that software quality assurance will not be treated as an afterthought at the end of the projectit will be treated as an important part of the design process. Furthermore, as developers design and implement software, it provides a sanity check to make sure that the project is going to live up to its requirements. At each iteration of the development process, tests can be conducted to ensure that no new bugs have been added as new features are introduced. Use Cases Test Cases LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 9 Figure 1-3: Three sample scenarios constructed to identify whether the sample pro- gram runs as designed. How to Identify the Elements in Software Requirements Specications Before plunging yourself and your team into writing code for your software, you must rst reach an agreement with your client about all requirements and weed out any inconsistencies that may arise. A complete and properly dened software specications document will help you achieve this goal. Guidelines: Some of the guidelines that must be kept in mind before creating a software require- ments specications document are: Take time and effort to understand customer specications in order to document the requirements about the software that is going to be developed. Instead of having large diagrams detailing the aspects of the software, use tables and charts where possible. Your client may not be experienced enough to under- stand all that technical information. Get other people and not the actual developer of the software to work on the specications to get different views about the requirements. Be clear and concise in stating what the proposed software is expected to do. Do not be vague about the requirements. If you do not understand the requirements, do not hesitate to clarify the same with the client. Otherwise, vague descriptions might pose possible dangers to you in the future. If some of the requirements are simple to understand between you and the client, do not complicate the same by over-documenting the features. Keep your software requirements specications up to date. Always test the requirements document based on the test cases written for the same. Example: Benjamin Roberts, a product manager with Our Global Company, is assigned the task of writing the software specications document for the loan processing system his company is going to develop. He has had various discussions with the client about the proposed application, and has documented the purpose and an outline of the applica- tion. As part of the requirements, he has attached various reports and charts LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 10 documenting the advantages of the new application. In the document, he has men- tioned the possible time frame within which the application has to be developed; other specications such as hardware and network requirements and security information are also provided. Finally, he has given possible real-life scenarios and test ideas for reviewing the application. DISCOVERY ACTIVITY 1-2 Preparing Software Requirements Specications for Our Global Company Scenario: Our Global Company has decided to automate its loan department. You have been asked to dene the requirements of the project to prepare a project feasibility report. Before you prepare the requirements of the project, you would like to test your knowledge on preparing the soft- ware requirements specications document. 1. Identify the sections that form part of the software requirements specifications docu- ment. a) Operating environment b) Software interface requirements c) Product functions d) Business rules e) Allocation of project resources 2. True or False? Test cases are a description of the various scenarios that will be con- structed and analyzed to identify whether a program runs correctly as designed. True False 3. True or False? Use cases provide a means of identifying the functionality that software must support. True False LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 11 TOPIC C Determine the Steps Involved in Designing a Class Structure You identied the requirements of the software product. However, before you start writing the code for your project, you need to design the various classes that are involved. In this topic, you will determine the steps involved in designing a class structure. A book contains a set of chapters that dene the scope of discussion based on the knowledge to be imparted. Similarly, your software project might consist of a set of classes that dene the scope of software development based on the customers requirements. Classes and Objects Denition: A class is a template used to create objects and an object is an instance of a class. A class contains the attributes and behaviors that are common to similar objects. For example, the template of a registration form used to register for a course can be con- sidered a class with attributes such as the student name, course name, and semester. Objects are the printouts of the form taken using the template. The attribute values of the student name, course name, and semester vary for different objects. A behavior is something exhibited by an object, such as when processing, modifying, or canceling a course registration. Characteristics of a class are also known as attributes, or properties. Behaviors of a class are also known as methods. Example: Classes and Objects LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 12 Class Structure Design The process of designing a class structure involves a set of sequential steps to come up with a robust design structure for classes, so they stand the test of time and change. The table describes each phase in designing a class structure. Design Phase Description Iterative analysis and design This phase helps you design objects of the system with the help of good design methodologies through an iterative process. In this phase, you sketch out diagrams of the class structure and then rene your diagrams through successive passes until you believe youve got a workable solution. The design process gives the entire team an oppor- tunity to buy into the design. Class sketching This phase involves effort being driven to deter- mine class attributes. You then test the class structure against use cases to determine whether the structure is as simple as possible while still covering all possible scenarios; it has room for feature enhancements over time without requiring major redesign; and it does work as intended. It is helpful to document the class structure using a software design program that uses a standard nota- tion or object-oriented modeling methodology such as Unied Modeling Language (UML), Booch, OMT, and OOSE. Depending on the nature of the software tool, the size of the development team, and other factors, it might even make sense to develop the rst-pass of the class structure right in the software tool, rather than starting on paper. Class Structure Design LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 13 Design Phase Description Class update This phase helps you make changes to existing class structures as more functionality gets added to the application. You might discover some elements that you did not anticipate during the initial design phase. As the development team begins to assemble objects and code interactions, other modications might be called for. Even after the software ships, it might be necessary to modify the classes that youve designed. Often, even the most thorough design methodolo- gies do not produce a perfect class structure in the initial design phase. Certainly the goal is to pro- duce the best possible design during the design phase, but as you progress through the project (and sometimes even after the software ships), it is nec- essary to go back to the drawing board and modify the classes that youve designed. For example, new features in successive versions of software might call for modications. Furthermore, you might reuse the classes you create for one software project within another. As you reuse classes, you might discover the need for additional functionality that you didnt plan for. The Iterative Analysis and Design Phase Good design methodologies enable you to design a class structure using some sort of an iterative process in which you keep trying until you get it right, much like the way a painter creates a picture. It is unlikely that a complete class structure will just pop into your head and that you can start coding. More likely, you will come up with a general idea of which objects are involved, and you will somehow sketch out diagrams of the class structure. Although jokes abound regarding the drawbacks of designing by a committee, a small development team working together on an iterative design can often produce a much better design than one person working alone. Certainly the various viewpoints make it less likely that certain details will be overlooked. LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 14 Usage of Tools for the Design Phase You can use high-tech tools for this design phase, such as modeling software, that enable you to use the computer to diagram and analyze class structures. Alternatively, you can use low-technology tools, such as index cards, a white board, or ip chart sheets. While some high-technology tools really do provide useful capabilities that help automate the analysis and design process, the important part is that the tools you use enable you to make a lot of changes and easily play What If? to come up with the best design. You should provide adequate time to think through several iterations of the design before you start coding. On the other hand, you should not get hung up on try- ing to anticipate everything. When you begin coding, youll know if any modications to your class structure are needed. Sketching Out a Class Structure As you analyze the class structure, youll want to consider the following questions over the design for each class. What will you name the class? Which classes descend from other classes? What major properties and methods will the class contain? What other classes will this class interact with? Attributes of a Class Structure There are certain attributes that you need to examine when analyzing a class structure. Refer to the table for a description of each such attribute. Attribute Description Class name Class names should be meaningful and clearly sig- nify the range of information that is represented by the class. As you modify and improve the class structure, it might be necessary to modify class names that youve come up with so that they are consistent with the changes you make. Relationships to other classes Class design includes design of child classes so that they inherit attributes in a way that makes sense and is not awkward. Functionality of the class Class functionality improvisation will invite changes to the class design by changing the rela- tionships of existing classes and child classes. If a single class becomes extremely complex, you might need to create several smaller classes instead. Collaboration Class mergers are usually advised when a lot of collaboration takes place between any two classes. If one class has a few interactions with other classes, it could be that it is too big and all- encompassing. When in doubt, keep objects small and specic. LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 15 ACTIVITY 1-3 Designing Class Structures for Payment Process Automation Scenario: Your client, Our Global Company has approached you with software requirements specica- tions of a project in order to automate their payment processing system. You now need to design class structures that can be used to create a model based on the specications listed. Before you start working on the design of class structures, you would like to test your knowl- edge on designing them. 1. Identify the attributes of the class structure design. a) Class relationship b) Class functionality c) Class implementations d) Collaboration 2. True or False? Class mergers are usually done when a lot of collaboration happens between classes. True False TOPIC D Examine the Coding Process Once the class structure has been designed and approved, it is time to begin the coding pro- cess. As with all other aspects of the software design and development process, there are many different approaches for accomplishing this task. In this topic, you will examine the coding process. In the manufacturing industry, new components are added to a product as it moves along an assembly line. This ensures that all products are uniform and of the highest quality. Similarly, the software coding process adopts a phased approach where specic functionality is added at various stages of development. This would ensure that the nal product meets customer requirements. The Coding Process As with the design process, the coding process is typically iterative. It consists of the follow- ing stages: The Coding Process LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 16 1. First, an application framework that provides an overview of the general user interface or communication mechanism to be used in the product is developed. 2. After that, specic chunks of functionality are added to the framework fairly methodically. These specic functions might depend on other functions. Analyzing such dependencies can help to determine the order in which specic classes or functionality should be imple- mented. 3. Once the functionality is implemented, the nal software polishing occurs, which includes the quality assurance process that enables software to ship to customers free of bugs. The Application Framework Design Regardless of the approach used, the application framework design phase of develop- ment is a sort of trial by re where you get to test the design of the class structure. For the various project stakeholders, this part of the process is very exciting, because this enables them to see, for the rst time, a working model of the software. Many development teams nd that this part of the process actually takes less time than the design phase because much more is known about the project, and fewer face-to-face meetings are needed to iron out details. With large projects, knowing where to begin the coding process can be a bit like pick- ing oneself up by ones bootstraps. Typically, it starts with the application framework development. It provides the general user interfacesuch things as the main applica- tion window, menus, and so forth, if its a typical software application. In the case of device drivers, web applications, and other projects that involve communication between various pieces of software (potentially running on different networked com- puters), the general communication mechanism might be implemented and tested. Dialog boxes and other secondary user interface features might be provided, but they would lack specic functionality at this point. (For example, it might be possible to display or close a dialog box, but none of the buttons or other items within the dialog box would be functional.) LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 17 The application framework provides a place to hang features as they are developed in successive iterations. It also provides an opportunity for stakeholders to view the gen- eral application design as early as possible in the development process. If major changes are needed, its best to address them early on, before too much development and testing has been done. Valuable insights can be gained from having a largely non- functional prototype of the application available for stakeholders to poke and prod. Implementation of Features The addition of new features to the application framework can introduce some sequencing dilemmas. For example, a reporting feature that prints the contents of a database could probably not easily be tested until the database itself is present and working. Analyzing such sequencing dilemmas can help determine the order in which specic classes or functionality should be implemented. You should not only identify each iteration that will be developed, but also identify what classes or functionality will be implemented in that iteration. Each iteration should represent a version of the program that can be methodically tested against a use case. By relating each iteration to the support of a specic use case, you minimize the problem of having to wade through a complex sea of side effects. (Was the bug intro- duced when we added the printing capability, or when we added the database query feature?) In most cases, bug-chasing can be localized to the area of code that was modied when adding specic functionality. To keep things orderly, its best to advance in small, specic steps. Regarding time-sensitive projects, it might be possible to implement important or baseline features rst. Should problems be encountered that cause delays, this will make it possible for the product to be released without some of the less important fea- tures, which could be implemented in the subsequent versions of software. Quality Control and Product Improvement Polishing of software can also refer to the process by which good software keeps get- ting better based on the feedback of users. It is not uncommon for software applications and operating systems that made their debut more than a decade ago to be in version 8 or 9, with many incremental versions (for example, 8.2a) in between. (For some reason, many software products are renamed before their version numbers reach double digitsalthough there are a few exceptions to this rule.) Of course, one of the motivations for software companies to continually release new versions of software is to persuade existing customers to spend more money to get the newest and best, but often, new versions actually are new and improved. Software is improved by listening to the feedback of usersnot only to identify new features that are desired, but also to identify current features that are broken or buggy. LESSON 1 Object-Oriented Programming and Design Using Java (Third Edition) 18 ACTIVITY 1-4 Developing Applications for the Quality Control Department Scenario: The quality control department of Our Global Company has decided to implement an applica- tion to measure the quality metrics in the organization. They have approached you with the software specications. Before you start working on developing the application, you would like to test your knowledge of the coding process. 1. True or False? Building an application framework involves the development of a gen- eral user interface for software. True False 2. True or False? The final polishing of software is done to remove bugs before shipping it to the customer. True False Lesson1Follow-up In this lesson, you identied the key phases in software product development. You will now be able to adopt a structured approach to development by implementing these phases in your projects. 1. What are the various phases of software design in your organization? Answers will vary but may depend on the type of organization. If it is a small or medium sized company, some of the phases such as analysis and design might be merged. If it is a big company, then depending on the size of the project, they might carry out all the phases. 2. In what phase of development are changes to software requirements specifications most expensive? What are the implications of this? Answers will vary depending on the type of products or the projects that your organiza- tion is involved in. Some of the implications of making changes to the software requirements specifications can be increase in the cost of the project, rework for the development team to include the changes made, and last and the least favored implication would be delay in the ship- ment of the final product to the client. LESSON 1 Lesson 1: Identifying the Key Phases in Software Product Development 19 Object-Oriented Programming and Design Using Java (Third Edition) 20 NOTES Exploring Software Design Methodologies and Tools In this lesson, you will explore software design methodologies and tools. You will: Identify the characteristics of software design methodologies. Examine the different types of UML diagrams. Lesson Time 45 minutes LESSON 2 LESSON 2 Lesson 2: Exploring Software Design Methodologies and Tools 21 Introduction You examined the various phases in software design. You may now need to design software. In this lesson, you will explore the methodologies and tools used to design software. Decades ago, programmers across the world used white boards to represent class structures and the relationship among them. This method, however, had a major disadvantage to information sharing. Therefore, new computer aided design methods were created to facilitate easier col- laboration among programmers. Given a set of requirements, software design can now be accomplished with the help of these tools in very little time, thus aiding projects that have tight schedules. TOPIC A Identify the Characteristics of Software Design Methodologies You examined the design of class structures. Before you get started with the actual design of classes, you have to identify the architectural view and the low-level component structure of these classes. To identify these component structures and the views, you may now need to use standard methodologies that will ensure uniformity in the understanding of programmers when designing class structures. In this topic, you will identify the characteristics of software design methodologies. Given a set of requirements, there are many different methods of designing software. It is important that you know the characteristics and benets of these methods in order to choose the one that best suits your needs. Software Design Methodologies Many tools and methodologies are available today that enable a programmer to prototype or model software design before coding the nal software. Over many years of trial and error, programmers have come up with efficient and effective approaches to designing objects. These approaches have now come to be known as software design methodologies and are specic to a given requirement. Some examples of software design methodologies include top-down/ bottom-up design, structured design, Object-Oriented Design (OOD), and Object-Oriented Analysis (OOA). Elements of Software Design Methodologies Software design methodologies provide a consistent approach to abstraction, which is the pro- cess of designing objects to represent programming problem sets. They dene three basic elements. Refer to the table for a description of each of the elements. Element Description Processes A set of prescribed steps for modeling and con- structing software. LESSON 2 Object-Oriented Programming and Design Using Java (Third Edition) 22 Element Description Notations A language of graphic symbols or text markup for representing software systems and subsystems. Heuristics A set of rules to promote methodical software design. Some programmers typically might follow some rules of thumb or basically apply their com- mon sense to arrive at the best possible solution in designing the software. Some of these rules might be written as part of the software design process followed by your organization. Other rules might be unwritten which might have originated through many trial and error and been followed by your peers and senior programmers in the organization. ACTIVITY 2-1 Managing Customer Information for OGC Advertising Inc. Scenario: An advertising company, OGC Advertising Inc., has approached you with a project to develop software to manage customer information. The assignment requires that you have a sound knowledge of software design methodologies and tools. Before you start work on the assign- ment, you would like to test your knowledge on the various software design methodologies and tools. 1. True or False? Software design methodologies define heuristics, processes, and nota- tions. True False 2. True or False? Specific approaches to designing objects are termed as software design methodologies. True False LESSON 2 Lesson 2: Exploring Software Design Methodologies and Tools 23 TOPIC B Examine the Different Types of UML Diagrams You examined software design methodologies. To implement software design methodologies, you require a special set of tools. In this topic, you will examine the tools designed for this purpose. A picture is worth a thousand words. By representing class structures pictorially, you can ensure that they are easily comprehended by programmers around the world. This would also help avoid misinterpretation of class structures. Notations Denition: Notations are a highly developed specialized language that enable object-oriented pro- grammers to communicate precisely with one another. They not only provide a framework for thinking through problem sets programmers encounter but also act as a means of analyzing and documenting all software design decisions. They represent information in a way that is tangible and meaningful to human beings, while allowing a computer program to easily represent and manipulate the information. Example: Imagine that your company has bagged a contract to create an online shopping portal for Our Global Company. In this scenario, your problem set will be to design the online portal in such a way that it helps your client Our Global Company to gain more customers, and get more exposure to its products. You must design a framework and a strategy that will analyze the given problem set in order to nd a suitable solution to match your clients needs. The Unied Modeling Language The Unied Modeling Language (UML) is a popular notational system that provides different types of diagrams for modeling software. Each type of diagram is designed to efficiently and effectively represent specic attributes of software design. The various types of diagrams are useful for representing many sorts of information about a software system. For this reason, not every diagram type is used in every project. Notations LESSON 2 Object-Oriented Programming and Design Using Java (Third Edition) 24 Evolution of UML As approaches to software design have evolved over the years, so have the notations used in the design process. The leading notation today is the Unied Modeling Lan- guage (UML). It is built upon earlier notation systems, such as Booch, Object Modeling Technique (OMT), and Object-Oriented Software Engineering (OOSE). It was developed by Rational Software Corporations Grady Booch, Jim Rumbaugh, and Ivar Jacobson, with its rst public draft released in October, 1995 as version 0.8. UML continues to evolve. Distinction Among UML Diagrams One distinction that can be made about the different UML diagrams is whether they are good for representing workow or for representing the systems changes in state over time; or whether they are good for representing structural details while ignoring the aspect of changes over time. While the former is known as dynamic diagrams, the latter is known as static diagrams. Furthermore, some diagrams focus on aspects of design from the human perspective (the needs of users and business processes), whereas others focus more on computers and technology (where the software will reside, what types of software modules will be involved in the nished product, and so forth). Unied Modeling Language Diagrams Using a combination of UML diagram types, you can design and document software from sev- eral perspectives, in order to provide a detailed representation of a software system and all of its potential users. The table provides a description of each of the UML diagram types. UML Diagram Type Description Use case Diagrams This diagram represents software from a users perspective. They model business processes: the tasks that users (represented by actors) must be able to accomplish using the software. Use case diagrams can be very complex, and are sometimes depicted through text only. When you create use case diagrams, you are essentially dening the user interface at a very high level. You are determining such things as: Which users (people or agents such as external software that interfaces with the system as a user) need to interact with the system. What specic types of users need to be able to do (what services the system needs to provide). What specic types of users should be limited from doing (for example, access rights based on user types). LESSON 2 Lesson 2: Exploring Software Design Methodologies and Tools 25 UML Diagram Type Description Sequence Diagrams This diagram represents messaging within a systemthe types of communication and interac- tions that occur among objects. Thus, it plays a useful role in helping to specically dene what occurs in a given use case. In the sequence diagram, objects are represented along one dimension of a graph, with time repre- sented along another. Messages between objects are represented by arrows labeled with the name of the interaction or message. Because it shows object relationships over a timeline, the sequence diagram is useful for analyzing and documenting complex tasks that are time dependent or require synchronization of some sort between two or more processes. Communication Diagrams This diagram represents the interactions that occur among different objects within a system. In this regard, their purpose is similar to the sequence diagram. However, the communication diagram focuses more on objects than does the sequence diagram, showing various interactions associated with each object. The communication diagram is more effective at providing a procedural perspective than the sequence diagram, and is useful for analyzing the effects upon a particular object in the various inter- actions in which it is involved. Class Diagrams This diagram represents the structure of classes used within the system, identifying each classs attributes, operations, and relationships to other classes. Class diagrams can be depicted with increasing levels of detail: showing the overall hierarchy of classes (Conceptual view), the classes with their interfaces (Specication view), and all details (Implementation view, including hidden attributes and behaviors of each class). Class diagrams are static. In other words, they do not represent the interactions that occur among various classes over time or in different scenarios. However, they provide a useful way to document the existence of classes, their interfaces, and rela- tionships to other classes. Object Diagrams This diagram represents the logical relationships of objects within the system, and provide a way to trace the execution of specic scenarios. In an object diagram, objects are represented as instances of a class. In other words, they show the detailed state of an instantiated class at a particular point in time. Like class diagrams, object diagrams are static. LESSON 2 Object-Oriented Programming and Design Using Java (Third Edition) 26 UML Diagram Type Description State Machine Diagrams This diagram represents the various events that cause an object to change from one state to another, and the actions that result from the change in state. The state machine diagram is useful for analyzing external events to which an object must respond. Activity Diagrams This diagram represents a business workow model, as well as the ow of algorithms imple- mented through a specic class or method. Whereas state machine diagrams are well suited for analyzing and documenting external events (for example, responses to somewhat random user actions), activity diagrams are especially useful for representing the more sequential routines that are hidden inside a program, which are typically pro- cedural or linear in nature. Component Diagrams This diagram shows the dependencies of one soft- ware component upon another. Different components might exist at different stages of development. For example, some components (such as source code les) might be compiled, with the resulting executable code being combined into a single le. Other components, such as dynamically linked libraries (DLLs), device driv- ers, Java class les, or external JavaScript (JS) les might remain as separate les in the nal product. Package Diagrams This diagram shows how software will be broken up into modules (such as EXEs and DLLs), and how various modules depend on each other to work. Deployment Diagrams This diagram shows how various elements of the system will be congured when the program is nally installed and running. Various network com- puters or other networked devices (called nodes), network connections, databases, and other compo- nents needed in the nal implementation are represented in this diagram. LESSON 2 Lesson 2: Exploring Software Design Methodologies and Tools 27 UML Diagram Type Description Composite Structure Diagrams This diagram describes the functioning of the sys- tem by displaying the interaction among classes, interfaces, and components. Composite structure diagrams are similar to class diagrams except that they are used to depict runtime instances, indicat- ing the objects and their roles in the collaboration. On the other hand, a class diagram is used to explore the static view of a class. Interaction Overview Diagrams This diagram depicts the collaboration between interaction diagrams such as sequence diagrams, communication diagrams, timing diagrams, and other interaction overview diagrams to show the ow of control in the system. Interaction overview diagrams are similar to activity diagrams. How- ever, interaction overview diagrams introduce two new elementsinteraction occurrences and interac- tion elements. Timing Diagrams This diagram is a behavioral representation of dif- ferent objects of a system in a given time window. Apart from providing a change in the state of objects, it depicts the interaction among them in a given time scale. UML Diagram Categories The 13 diagrams of UML can be categorized into two categories: Structure and Behav- ior diagrams. Class, Component, Object, Deployment, Composite Structure, and Package diagrams are grouped under structure diagrams. Activity, Use Case, State Machine, Communication, Interaction Overview, Timing, and Sequence diagrams are grouped under behavior diagrams. Communication, Interaction Overview, Timing, and Sequence diagrams are also known as interaction diagrams, a subset of the behavior diagrams. LESSON 2 Object-Oriented Programming and Design Using Java (Third Edition) 28 UML Tools There are various kinds of UML tools available which would help you implement the class structures and the design of your proposed software application. Some of these UML tools are available for free and others for a fee. Some prominent UML software tools which help you design the various diagrams based on your needs are Microsoft Visio, Eclipse, Rational Software Modeler, Poseidon for UML, Enterprise Architect, Visual Paradigm for UML, UML Pad, and so on. Based on your companys nancial position and buying power, you might be using either the free/open source versions of the UML tools, or you might use the paid/licensed versions of some of the famous UML tools available. LESSON 2 Lesson 2: Exploring Software Design Methodologies and Tools 29 ACTIVITY 2-2 Designing a Web Application for OGC Insurance Scenario: An insurance company, OGC Insurance, has decided to launch a website for all its customers across the country. As a programmer, you have been assigned the mammoth task of designing and coding the web application for the company. Before you start work on designing the web application, you would like to test your knowledge on the various UML diagrams you need to use. 1. Suppose you were developing a complex web application that involved components of a web server, as well as client-side components. Which type of diagram would best depict what components would need to be installed in the final application, and where they would be installed? a) Component diagram b) Deployment diagram c) Composite diagram d) Package diagram 2. While developing a complex web application involving components of the web server and the client, which type of diagram would best depict the dependence of the various components on the installed system? a) Class diagram b) State machine diagram c) Object diagram d) Package diagram 3. Suppose you need to diagram all the processes between order placement on a website and delivery of the final product to the customer. Which UML diagram will you use? a) Package diagram b) Activity diagram c) Component diagram d) Deployment diagram 4. Suppose you are designing a complex object that can respond to different events. Which diagram would you use to help analyze and document those events? a) State machine diagram b) Communication diagram c) Class diagram d) Object diagram LESSON 2 Object-Oriented Programming and Design Using Java (Third Edition) 30 Lesson2Follow-up In this lesson, you explored software design methodologies and tools. You will now be able to use these tools to facilitate collaboration when designing software in your organization. 1. If you were to prepare a visual representation of a library management system, which UML diagrams would you use? Why? Answers will vary but will depend upon the type of details required. If you would like to represent the borrowers perspective, you might use a communication, a sequence, or a use case diagram. If the representation is for a programmer, you might use class/object diagrams, activity, and state machine diagrams. If you want to know how the system has to be installed on the client system, you might go in for deployment diagrams. 2. Which software tool does your organization use to design the models for the various projects? Why? Answers will vary but may depend on the size of the organization and its financial status. Based on that, you might use the freely available UML tools or go for a highly sophisti- cated licensed version of the UML tools developed by bigger software organizations. LESSON 2 Lesson 2: Exploring Software Design Methodologies and Tools 31 Object-Oriented Programming and Design Using Java (Third Edition) 32 NOTES Describing the Characteristics and Benets of Object-Oriented Programming In this lesson, you will describe the characteristics and benets of object-oriented program- ming. You will: Examine the different approaches to problem-set analysis. Describe the evolution of object-oriented programming. Identify the benets of object-oriented programming. Lesson Time 1 hour(s) LESSON 3 LESSON 3 Lesson 3: Describing the Characteristics and Benets of Object-Oriented Programming 33 Introduction You are familiar with the fundamentals of computer programming. Before you go ahead and take advantage of the power of object-oriented programming, you need to understand its fea- tures and the benets it offers over other programming models. In this lesson, you will examine the object-oriented programming model as an evolving substitute for all programming styles. You will be able to harness the power of a tool only when you have a complete understanding of its features and benets. Similarly, examining the features and benets of object-oriented programming will help you to use the object model as a solution to all your programming needs. TOPIC A Examine the Different Approaches to Problem-Set Analysis Sometimes you may be required to develop software code for a given system. A systematic approach to software design will require you to study the system being automated and furnish the requirements. In this topic, you will examine the two common approaches to problem-set analysis. The success of any software project depends on the in-depth analysis of the system that is being automated. This knowledge serves as a blueprint in terms of the tasks that need to be executed and the resources that need to be allotted for the software project. Programming Problem Sets The most challenging tasks for a software developer are those that occur before any actual coding begins. These tasks consist of analyzing a real-world situation, or in the case of com- puter games, simulations and other such programsa virtual-world problem set of some sort and then determining the best way to represent and manipulate that problem set within a computer or a network of computers. Sample Problem Sets Consider, for a moment, how you might analyze and solve the following programming problem sets: An accounting system for a small business or nonprot organization. A three-dimensional maze (such as the multiplayer games Doom and Quake), in which various players must hunt down each other before getting hunted down themselves. A website that enables customers to select and buy books online. A software driver that enables a computer to communicate with a specic model of printer. To generate the best design for these problem sets, you need to determine: How to go about designing the program? LESSON 3 Object-Oriented Programming and Design Using Java (Third Edition) 34 Where to begin? What sorts of information (data) are involved? What kinds of processing (procedures or subroutines) would be involved? For any problem set, there are probably as many ways to analyze and solve the prob- lem as there are people and technologies to do that. Approaches to Analysis There are two commonly used approaches to problem-set analysis. You can break down a problem set either algorithmically or procedurally, according to the sequence or procedure of events that must occur. Alternatively, you can break down a problem set using an object- oriented approachlooking at the various entities in the system, and the manner in which they interact with one another. The Algorithmic Approach The algorithmic approach focuses on the functionality of a program. It begins with a general task that needs to be performed at the top and breaks the topmost task into subsequent levels of more specic subtasks as it works toward the bottom. Therefore, it is also known as the top-down approach. The various boxes in the tree correspond to various routines and subrou- tines that need to be programmed. An Example of the Algorithmic Approach Consider an account transaction in an ATM (Automatic Teller Machine). If an algorith- mic approach is applied to this problem set, each account transaction is broken down into a series of tasks. Suppose a user chooses to withdraw an amount, the system will prompt for the withdrawal amount. Then it would ask him to verify the amount entered. After verication, the amount will be dispensed to the user and the transaction completed. Each of these tasks is treated as a subtask which needs to be programmed. The Procedure-Oriented Approach Algorithmic or procedural methods for software design were developed in the late 1960s to address problems with the general state of software development at that time. Because the new approaches provided a structured approach to programming (versus the chaotic hack-and-run approach used by some programmers), you may also hear algorithmic or procedural approaches to programming called structured programming. The Algorithmic Approach LESSON 3 Lesson 3: Describing the Characteristics and Benets of Object-Oriented Programming 35 Likewise, because the algorithmic approach focuses on the procedures to accomplish a task, it is also sometimes called a procedural approach. Because the algorithmic approach focuses on the procedures to accomplish a task and the functionality of the program, it is also known by many names such as: Functional decomposition Algorithmic decomposition Structured programming Top-down programming Procedural programming Many programmers use this approach today to produce quality softwareespecially smaller programs or software modules. The Object-Oriented Approach The object-oriented approach views the problem set as a collection of independent objects that work together to accomplish a set of tasks. Through careful analysis and design, software objects can be developed to have a usefulness beyond the program for which they were origi- nally created. For instance, a window object developed to represent an application window under Windows, X Windows, or the Mac OS can be reused by the programmer in almost every other application program. An Example of the Object-Oriented Approach Consider an account transaction in an ATM. If an object-oriented approach is applied to this problem set, every transaction is viewed as an object. The other objects involved in each transaction are the user, the transaction amount, and the receipt gener- ated. Comparison of the Two Approaches to Analysis Both the object-oriented and algorithmic approaches attempt to solve a problem by breaking it down into smaller chunks. The algorithmic approach focuses on the procedures of the system, whereas the object-oriented approach focuses on the objects involved in the system. With the algorithmic approach, data is thought of as a separate entity and represented separately from the procedures that operate on it. With the object-oriented approach, data and procedures are both embedded within an object to which they directly pertain. The Object-Oriented Approach LESSON 3 Object-Oriented Programming and Design Using Java (Third Edition) 36 Data and Procedures Computer programs involve pairing of data and procedures. With the algorithmic approach, you can create data structures to hold various values that will, in turn, be operated on by procedures. A procedural program might establish a large block of data structures that contain diverse data such as the account number, street address, and cur- rent transaction type. A mainline procedure might then display a menu to the user. As users select menu choices, various other procedures are called upon to manipulate val- ues stored within the various data structures. With the object-oriented approach, the object might have properties such as the name and list of accounts of a particular customer. These properties hold the data related to a specic customer. Similarly, a customer object might have methods such as Display a List of Customers Accounts and Change Address. These methods are procedures related to the customer object. Another attribute that is often associated with object- oriented programs is the event-driven design. Objects can have certain events associated with them, such as when the mouse button was clicked or the object was about to be hidden. Objects can be programmed to respond to such events. In win- dowed environments (such as Windows, X Windows, Macintosh, and others), the event-driven design is used almost exclusively. Graphical Depiction of Object-Oriented and Algorithmic Approaches The following gure depicts the object-oriented and algorithmic approaches graphi- cally. Data and Procedures LESSON 3 Lesson 3: Describing the Characteristics and Benets of Object-Oriented Programming 37 ACTIVITY 3-1 Automating the City Library Scenario: Your company has secured a major project to automate your city library. You have been assigned the job of analyzing the problem set for this project. 1. As a first step in the problem-set analysis, you have identified the constituent entities of the library management system. What will be the next step? a) Identify the processes carried out in the library. b) Identify the job designations in the library. c) Examine the frequency at which books are borrowed and returned. d) Identify the manner in which books are classified. 2. True or False? You will use the object-oriented approach to study the constituents of the library management system and the manner in which these constituents interact with each other. True False 3. True or False? As books are the primary entities of a library management system, you will use a book object that will contain data and procedures related to the book entity. True False LESSON 3 Object-Oriented Programming and Design Using Java (Third Edition) 38 TOPIC B Describe the Evolution of Object- Oriented Programming Languages You examined the object-oriented approach to problem-set analysis. However, in order to com- pletely harness the power of the object-oriented approach, you need to examine the shortcomings of other programming models. In this topic, you will discuss the evolution of the object model. Back in time, programming was never easy. Apart from providing input to the program, pro- grammers also had to take care of providing directions to hardware for processing the data and displaying the results. The advent of the object-oriented model has made programming easier today by hiding hardware implementation details from the programmer and by allowing the entire processing to be done by the computer itself. Generations of Programming Languages Programming has progressed from being hardware-oriented to being object-oriented. You can classify programming languages into generations based on their general design and features. The following table describes the languages used in different generations. Generation Description First-Generation Languages The rst-generation programming languages forced the programmer to focus on how hardware of a particular computer worked, in addition to focusing on the problem that needed to be solved. A pro- gram written for one machine (computer) would not likely run on a different type of machine. The memory locations (registers) would be different, and even the instructions would be different from machine to machine. Programmers had to directly speak the machine language of computers. Rather than saying add 3+5, for example, a programmer would have to code a sequence of commands to put the value 3 in one memory location, the value 5 in another, and then issue the command to add the two memory locations, storing the result in a different memory location. Programming with rst- generation languages involves stuffing a lot of numeric opcodes or machine language instructions and values into the computer. LESSON 3 Lesson 3: Describing the Characteristics and Benets of Object-Oriented Programming 39 Generation Description Second-Generation Languages The second-generation programming languages, also known as assembly languages, provided pro- grammers with a tool, called an assembler, that performs much of the vital coding work, such as guring out memory offsets and the numeric value for a specic instruction. Assemblers typically pro- vide macros, which enable programmers to automatically insert chunks of code into their pro- gram by simply invoking the name of that code chunk. An assembly language programmer enters com- mands that are more friendly, such as: add value1 value2. Elsewhere in the program, the programmer would dene the values of value1 and value2. Third-Generation Languages The third-generation programming languages pro- vide commands or instructions that do not directly correspond to the low level of hardware instruc- tions (like machine and assembly languages), but rather focus on the high level of tasks that humans need to accomplish. These high-level instructions written by the programmer cannot be executed directly on the computer. The programmer uses a special program, called a compiler, to translate the generic command into a set of machine-language instructions that perform the tasks necessary on a specic type of computer. The le generated by the compiler is called an executable program because it can be executed directly on the com- puter. Third-generation languages focus on tasks such as displaying output on a screen, adding two num- bers, or asking a user to enter a number value or a string of text. For example, a command to display text on the screen in a high-level language might be as simple as: Print "Hello, world!". BASIC, C, and C++ are examples of third- generation languages. Fourth-Generation Languages The fourth-generation programming languages (or 4GLs) are high-level languages that attempt to abstract the functionality of the computer even further. 4GLs enable programmers to write pro- grams using commands that are similar to human languages. 4GLs have made their greatest impact on database programming. Using a 4GL, a programmer can access specic database information using commands such as FIND ALL RECORDS WHERE MODEL_YEAR IS "1964". The Structured Query Language (also called SQL, which is pronounced as either Ess Queue Eell or sequel) is a fourth-generation language. LESSON 3 Object-Oriented Programming and Design Using Java (Third Edition) 40 Generation Description Fifth-Generation Languages The fth-generation programming languages (or 5GL) are programming languages that attempt to solve problems using the conditions given to the program. The programmer need not write an algo- rithm to solve the problem. These languages are prominently used in articial intelligence research and in academic institutions. Object-Oriented Programming Languages Denition: Object-oriented programming languages are languages that provide the programmer with some means to dene and use objects. The denitions of these objects include properties, methods, and event handlers. The software program thus created provides specic functionality by designing an environment in which these objects interact with the user, various other agentssuch as the operating systemand the other programs running on the same computer or on the other computers that are connected across a network. Example: Examples of Object-Oriented Programming Languages Object-oriented languages certainly make it easier for a programmer to employ prin- ciples of object-oriented programming. Some object-oriented languages, such as Java, actually make it difficult to program any way but as object-oriented, because they deliberately lack features that encourage procedural programming. Although many object-oriented programming languages are available today, Java and C++ are probably the most commonly used. Visual Basic is also quite popular, which, with each new version, is increasingly becoming object-oriented. LESSON 3 Lesson 3: Describing the Characteristics and Benets of Object-Oriented Programming 41 Object-Based Programming Denition: Object-based programming languages are languages that provide the programmer with the facility to use predened objects. Object-based programming allows you to group data with the functions that work on that data. Object-based languages do not support inheritance. A few examples of object-based languages include Visual Basic, Javascript, and Perl. All object-oriented languages are also object-based languages but the reverse does not hold true. Example: ACTIVITY 3-2 Converting Program Code to the Object Model Scenario: OGC Inc. has decided to assign a team of its programmers to a new project that requires the conversion of old program code written in the last few decades into an object-oriented pro- gramming language. As part of the process, the company has decided to assess the basic understanding of its programmers on programming languages. 1. Which generation of programming languages uses a special program called assembler? a) First b) Second c) Third d) Fourth 2. True or False? All object-based languages are also object-oriented languages. True False LESSON 3 Object-Oriented Programming and Design Using Java (Third Edition) 42 TOPIC C Identify the Benets of Object- Oriented Programming You examined the evolution of the object model. However, before you deploy the object model, you need to examine the probability of object-oriented programming being a suitable solution for all your programming needs. In this topic, you will identify the benets of object- oriented programming. Migration to new technologies in organizations is usually done after a careful analysis and study of the consequences of implementing the technologies. The new technology should over- come the shortcomings of and provide a method of interfacing with the existing technology. As a rule of thumb, the suitability of the technology is directly related to the number of benets it offers to the end consumer. Benets of Object-Oriented Programming To take full advantage of object-oriented programming, you need to be aware of its benets. The following table lists the benets of object-oriented programming. Benet Description Reusability of code Provides the ability to easily reuse portions of code in different programs, saving time in analysis, design, development, testing, and debugging. Component-based approach Provides an extended ability to buy portions of existing and tested code, to enable a component- based approach to development. Reduced cost of development Provides the added benet of reduced total cost of project implementation owing to reduced develop- ment time. Ease of work delegation Provides the ability to easily divide large program- ming projects among a team of developers. Modularity Provides the ability to divide and conquer pro- gramming tasks that are too large to be solved in one quick pass. Improved quality of debugging and testing Provides greater quality of testing and debugging owing to higher modularity of the program. Interfacing with existing objects Provides a method of interfacing with different types of existing objects while hiding the complex- ity of differences that exist behind the scenes. LESSON 3 Lesson 3: Describing the Characteristics and Benets of Object-Oriented Programming 43 Transition to Object-Oriented Programming Programmers who grew up with languages such as BASIC, COBOL, and C sometimes nd the transition to object-oriented programming difficult. When circumstances force them to use object-oriented languages and development tools such as C++ and Visual Basic, they might ignore the object-oriented features of those programs and use a pro- cedural or unstructured approach. It is not only important to learn to use object-oriented or object-based development tools, but also to use them in an object-oriented way. Some languages (such as SmallTalk and Java) make it difficult not to use an object-oriented programming approach. Nonetheless, even with these languages, it is still necessary for programmers to develop an object-oriented mindset to take full advantage of the benets they offer. ACTIVITY 3-3 Implementing the Object Model Scenario: Your organization has decided to move all its existing program applications into the object- oriented domain. As part of the process, it decides to assess the understanding of its programmers on the benets of this new venture. 1. What is the benefit of object-oriented programming languages? a) Increased development costs. b) Less prone to errors. c) It offers a component-based approach to development. d) Code cannot be reused. 2. True or False? In object-oriented programming, you cannot reuse code. True False Lesson3Follow-up In this lesson, you examined the various approaches to problem-set analysis. You also identi- ed the features and benets that make the object-oriented model a more preferred programming style. 1. Under what circumstances will you opt for the algorithmic approach to problem-set analysis? Answers will vary but may include problem sets like creating a calculator that can per- form all types of arithmetic calculations. LESSON 3 Object-Oriented Programming and Design Using Java (Third Edition) 44 2. For what type of problem sets will you use the object-oriented programming model? Answers will vary but may include problem sets like developing a software application that would enable you to create documents using it. LESSON 3 Lesson 3: Describing the Characteristics and Benets of Object-Oriented Programming 45 Object-Oriented Programming and Design Using Java (Third Edition) 46 NOTES Identifying the Elements of Object-Oriented Programming In this lesson, you will identify the elements of object-oriented programming. You will: Dene object relationships and attributes. Identify the relationship between classes. Implement multiple forms of the same procedure. Lesson Time 2 hour(s) LESSON 4 LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 47 Introduction Before you get to apply the object-oriented programming model in your programs, you need to familiarize yourself with the constituents of object-oriented programming. In this lesson, you will identify the elements of object-oriented programming. You wont be able to assemble a computer unless you are familiar with its basic components. Likewise, knowledge about the building blocks of object-oriented programming will help you build a successful model. TOPIC A Dene Object Relationships and Attributes You have examined the object-oriented approach to software designing. However, before you go ahead and design software, you need to dene the properties of objects and set relationships between them in order to constitute the design. In this topic, you will dene object relation- ships and attributes. You might have prepared chocolates at home by using a mold. The mold acts as a frame or model that helps you prepare chocolates of uniform size and shape. Similarly, a class acts as a mold for the objects that you create and use in your programming code. Also, you know that in any industry, the nal quality of a product depends on the individual properties of the raw materials that go into it. Objects are the raw materials of object-oriented programming. Their individual properties and interactions with other objects are contributing factors to the successful design of object-oriented programming. Classes Denition: A class is a container element that denes a template containing elds and methods. It begins with the keyword class and contains attributes and methods within braces to delimit its start and end. A class denition typically has a name indicative of its use. Example: Let us consider a car object. To create a template of this car object, we need to rst identify data that describes properties and methods that in turn describe the actions of the car object. Some of the properties can be Speed, Color, amount of fuel remain- ing, and so on. Similarly, some of the methods can be Accelerate( ), ChangeGear( ), Brake( ), and SetChoke( ). Combine the properties and methods into one single class and we can derive many desired car objects based on the class. Classes LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 48 Fields are also referred to as instance variables. Most in-built classes have their names initial capped. This is also good practice to follow for user- dened classes. To compile a program, you have to specify the le name; and to execute it, you have to specify the class name. It is good practice to match the le name with the class name to avoid confusion while compiling and executing the program. Objects Denition: An object is a component of a program that is created from a class to hold unique data values. It is a self-contained item declared from a class as an instance of that class. It shares features with the class and also with all members dened within that class. It contains related actions to perform a task and it may use other objects to perform an action. Objects LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 49 Example: Instantiating a Class This code uses Java to dene and create two instances of a class: 1. // The following lines define a class 2. class Person { 3. String name; 4. int age; 5. String hairColor; 6. String eyeColor; 7. String currentLocation; 8. } 9. 10. class NewPerson { 11. public static void main(String args[]) { 12. 13. // The following lines instantiate objects from a class 14. Person Dean = new Person(); 15. Person Remi = new Person(); 16. 17. // The following lines set properties of objects 18. Dean.name = "Dean Moriarty"; 19. Dean.currentLocation = "Denver"; 20. 21. Remi.name = "Remi Boncoeur"; 22. } 23. } Lines 2 through 8 dene the class Person as having several attributes. For example, a person has a name property (which is supposed to contain a text string, such as Sal Paradise), an age property (which would contain an integer, such as 23), and so forth. Lines 14 and 15 each instantiate a person object, assigning each new object a unique name (Dean and Remi). Lines 18, 19, and 21 set properties of the objects that have been instantiated. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 50 Classication of Objects There are many ways to classify objects. The main thing is that you should be consistent in using a classication scheme that is useful for your purposes and doesnt get in your way as you develop the program. Refer to the table for a description of each such scheme for classify- ing objects. Classication Scheme Description Representing real objects Represents real, tangible objects such as houses, products for sale online, parts in a machine, and so forth. Hardware devices attached to a computer (such as printers, display monitors, and so forth) might each be represented by an object. Representing interactions, sequences, steps, or events Represents things that happen. For banking, objects might include a deposit and withdrawal. For insurance applications, an event might be an auto accident, or a personal injury of some sort. To track what a user has done and to enable multiple levels of Undo, a graphics program might maintain a set of the last 50 commands that a user per- formed. Representing relationships Represents objects as a kind of another or as a part of another. For example, a Save As dialog box is a kind of dialog box. Objects might represent the relationship of employees (the organization chart) within an organization. Representing a role or function Represents roles or functions that must be served in a given scenario. For example, you might have an object that represents a baseball team, under which you have other objects for the pitcher, short- stop, and so forth. In a real estate transaction, you might have a buyer object and a seller object. Sample Class Structures As an example of how two different groups of programmers can abstract the same problem set differently, but effectively, consider the gures provided here. They illus- trate class structures that dene the same types of objects. The objects are standard parts of Windows applications (windows, menus, buttons, and so forth). The two class structures are the class libraries, which are provided by Javas Abstract Window Toolkit (AWT) and by Java Swing in their software development environments for the purpose of building standard Windows applications. Using the classes provided with the development tool, a programmer can quickly create windows, menus, buttons, and other such objects, which include the built-in functionality (such as title bars, the maxi- mize button, the minimize button, and so forth) for free. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 51 Figure 4-1: A simplified AWT class hierarchy. Figure 4-2: A simplified Swing class hierarchy. There are similarities as well as differences between these two class structures. For programmers, both class libraries provide the functionality to build common compo- nents of Windows applications, but AWT and Swing took different approaches to how they classied the objects involved. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 52 Abstraction Denition: Abstraction is the process of developing a simple representation of a complex object. It is used to represent the vital properties of a complex object and hides the less impor- tant ones. You can create abstraction by determining the attributes of the object that are signicant. Example: Analogy: The concept of abstraction is quite similar to abstract art. It is not the intention of the abstract artist to depict a person or a scene as seen in a photograph. Rather, the inten- tion is to represent those details or attributes that are important to the artist. Similarly, a programmer needs to consider the attributes of an object that are important to the task at hand and those that are not and then set about representing the critical attributes of the object through programming code. Quest for a Good Abstraction We live in a complex world. As a programmer, it would be impossible to capture every bit of information about every object you need to represent. Fortunately, you dont need to know everything about something to write a good computer program (although it might sometimes seem that way). Abstraction, like beauty, lies in the eye of the beholder. This means that there is no single right way of abstracting an object. That doesnt mean that anything goes; the quality of an abstraction is very important to software design. You should test the qual- ity of your abstractions by determining how well they distinguish one kind of object from another. For example, if your program needs to distinguish between a debit and a credit, and you create an abstraction that makes no distinction between those two objects, then your abstraction is not going to serve your needs. Abstraction LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 53 Likewise, if your abstraction makes distinctions that are never used (such as having separate objects for red-haired and blonde-haired employees), then your abstraction is probably more complicated than it needs to be. In designing any system, simplicity is usually betterand almost always less prone to breakage. Approaches to Abstraction Developing effective abstraction is typically a matter of successive approximations and rene- ments. There are some categories of information that you will need when you attempt to design an object-oriented solution to a programming problem set. Refer to the table for a description of each of the approaches to abstraction. Category Helps You Classication Identify the kinds of objects that are involved. Hierarchy Determine how the various kinds of objects relate to each other. Properties Identify what is potentially unique about each instance of an object. Methods Determine the logical sequence that describes an objects behavior or functionality. Events Determine the situations that each object needs to respond to. Getting Started with Abstractions The process of developing a useful abstraction involves looking at the objects you need to represent and determining how theyre different and how theyre alike. You also need to consider how objects are related. Is one object really a kind of another? For example, a fox is a kind of mammal. As a naturalist classies plants and animals in this manner, so must the programmer classify the objects that he or she needs to represent. Animals and plants existed long before the rst naturalist came along and began classi- fying them according to species, genus, and so forth. Naturalists began the task of analyzing similarities and differences between organisms and then grouping them accordingly. Over time, creatures such as the duck-billed platypus were encountered, which did not t neatly into the existing scheme, and naturalists had to adjust things accordingly. It was, and continues to be, a process of trial and error. For the programmer, the process is much the same. The best place to begin is to sim- ply make a stab at the process of abstraction and then test your abstraction to see if it works. Because of the sheer complexity of many systems, it is often impossible to cre- ate a perfect abstraction on the rst try. Real-Time Examples of Abstraction The following are some examples of abstraction that have been implemented through objects. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 54 Standard software partsPrograms developed for software platforms such as Win- dows, Macintosh, and X Windows share many common elements. For example, under Microsoft Windows, most programs have an application window of some sort. Applications also typically have one or more menu bars containing drop- down lists (or some equivalent). Dialog boxes can be represented as objects, as can the various buttons, text boxes, and other components that make up a dialog box. Each of the pieces and parts that make up an applications user interface can be represented as objects. Web page componentsThe various parts that make up a web page are repre- sented in computer memory as objects. Using a web-savvy programming language such as Java or JavaScript, you can access information on a web page, such as data that the user has entered in a form, text (for example, URL) that the user has entered on the browsers address bar, and so forth. Through these and other objects, your web-based programs can interact with the web page. Robots or data acquisition devicesDevices attached to computers are accessed through objects. When a company buys an industrial robot to perform tasks on an assembly line, the robot might include (along with the necessary hardware for communication with a computer and the robot) objects already dened in source code, which can be added to programs that need to control the robot. The same goes for thermal sensors, pressure sensors, and other data acquisition devices that are used as building blocks by companies that install and use automated equip- ment. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 55 Encapsulation Denition: Encapsulation is a software design technique in which data and the procedures related to that data are bundled together within a single entity. The bundle in which data and its procedures are encapsulated is called an object. Example: To understand encapsulation, let us consider a car. A car has certain properties, such as the speed at which it is traveling. Let us consider speed as its property. A car also has methods. For example, you can use the gas pedal (accelerator) to increase the speed of the car. Let us call this the accelerate method. The accelerate method would accept a parameter that species how faster or slower the car should go. In the case of an actual car, this is expressed by how much you press down the gas pedal. When you are at the wheel of any car, you expect the gas pedal already to be there. You consider the gas pedal to be an integral part of the car. In other words, the gas pedal is encapsu- lated within the car object. But consider what life would be like without such encapsulation. A gas pedal, after all can be removed from a car by simply loosening a few bolts. Let us assume that you had to bring your own gas pedal with you from car to car. Some day, you might forget to bring a pedal with you, and you wouldnt be able to go anywhere. Clearly, gas ped- als should be encapsulated within car objects. Encapsulating a Sample Object With a computer program, the benets of encapsulation might not be so clear. But sup- pose you were creating a drawing program. Youd not only need to keep track of how many shapes the user had drawn on the on-screen page, youd also need to keep track of where those shapes are positioned on the page, how large they are, and what kinds of shape they are (circle, rectangle, polygon, and so forth). Without having encapsu- lated data structures, youd need to create several separate data structures (tables, lists, or arrays) to hold all the needed information. One list would store references to each of the shapes that the user created. Another might hold the location, another might hold the color, and so forth. Then, each time a shape is added by the user, youd need to be sure that the information for each shape is added to each of the lists. Deleting a shape would involve deleting the corresponding entry from each list. This approach is pretty messy, with related information hanging out all over the place. Suppose you Encapsulation LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 56 wanted to use shapes in another program. Youd very carefully have to sift through all the related data structures and procedures in your program, and copy them to the other program. If you were to use structured programming techniques, you might have stored all of the related data and procedures within a single, separate le that you could include in another program. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 57 With encapsulation, you would have designed a shape object that encapsulated all of a shapes related data (properties) and procedures (methods). Because the shape object contained all of the information needed for a shape (and nothing extra), you would have designed the object to easily be reused in another program. Examples of Encapsulation Examine the code example below: //Sample 1 class missile { String name; int speed; //other missile properties void create(String missileName) { //Instructions on how to create a missile name = missileName; } void launch( ) { //Instructions on how to launch a missile } } class Newmissile { public static void main(String args[]) { //first missile information missile Missile1 = new missile(); Missile1.create("Missile1"); Missile1.launch(); Missile1.speed = 200; //Second missile information missile Missile2 = new missile(); } } Using Java, you can declare the various properties of an object within the protective boundaries of a class. This approach offers complete protection and foolproof security of data so that it is not manipulated by unauthorized sources. Information Hiding Information hiding is a software design approach that enables you to use a software feature without the need to know how the feature was implemented. It provides mechanisms to sepa- rate the interface, which relates to the part of the object visible to someone using it, from the features implementation, which relates to the inner workings created by the original program- mer of the object. This will prevent a person from making inadvertent changes to a chunk of programming code or an object that he or she is reusing. Information HidingAn Analogy As the driver of an automobile, you need not be concerned about the mechanism that converts your heavier foot pressure into a corresponding increase in speed. You could say that all of the machinery that accomplishes this is essentially hidden information. Most drivers know that hidden information is there, but they do not actually poke around under-the-hood themselves, reserving such tasks for professional auto mechan- LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 58 ics. The fact is, you can drive a car just ne without knowing whats going on under the hood. To many drivers, the car is essentially a black box. They push the go pedal and it goes; they push the stop pedal and it stops. They do this quite effectively with- out understanding the effect that the accelerator pedal has on the fuel pump through the throttle linkage. This side benet, the ability to use the method without having to know the details of how it was implemented, has a name. It is called information hiding. Information hid- ing is a concept that was introduced with structured programming, and it is a natural benet of the object-oriented programming concept of encapsulation. For information hiding to occur, objects must separate their inner workings (the gas pedal linkage, the carburetor, and other under-the-hood stuff) from the part that connects to other objects (the gas pedal). The inner workings are called the implementation, whereas the part that connects to other objects is called the interface. A major benet of object-oriented programming is the ability to create reusable code. Benets of Information Hiding Consider the benets of information hiding. The following line of programming code requests a ten-mile-per-hour increase in speed. car.accelerate(10) To increase the speed by 25 miles per hour, you need to type: car.accelerate(25) You do not have to dig into the code listing to gure out how the accelerate method worked. It was fairly obvious what was going on, even though the implementation details of the accelerate method were not provided. This makes it easy for one pro- grammer to reuse objects that another programmer has created. Because implementation details are hidden from the person using the object, it is less likely that a programmer will make inadvertent changes to a chunk of programming code (an object) that he or she is reusing. For example, an object might have a specic property that, under given conditions, causes the computer to crash. The object can provide a method through which changes to that property must be made. If a potentially harmful setting is applied, the method can take appropriate corrective or preventive measures to prevent the crash. Modularity Modularity involves breaking up a large programming task into subtasks, which are then pro- grammed independently before being assembled into one complete, nal program. In a good modular design, modules are designed to minimize dependence on one other, and they exhibit controlled interactions. Modularity in Structured Programming In structured programming, modularity is attained through the creation of subroutines known as procedures or functions. To maintain control of interactions among subrou- tines, data is passed in and out of subroutines through parameters that provide a list of data structures that the subroutine operates on. Through encapsulation, object-oriented programs provide an even higher degree of modularity by ensuring that the needed data and subroutines are included with the object. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 59 Java Packages A package in Java is a collection of related classes. To use a package in your program, you must rst import into your program the package that contains the associated method. A pack- age name is separated with periods. The rst part of the name identies the folder the package resides in. The remaining part of the name describes the contents of the package. These pack- ages are either in-built or can be dened by the programmer. Types of Packages Some of the types of packages in Java are provided in the following table. Package Description java.lang.* Provides in-built methods that are fundamental to the Java language. It is imported, by default, in all Java programs. java.util.* Provides in-built methods for utilities such as the date and time. java.sql.* Provides in-built methods to access and work with relational databases. java.awt.* AWT stands for Abstract Window Toolkit. This package provides in-built methods to design user interfaces and to work with images. java.io.* Provides in-built methods for system input and output. In Java, packages reside in a folder. To view them, navigate to C:\Program Files\Java\jdk1.6.0_07\ src.zip. The java.lang.* package is imported into all Java programs by default and need not be specied explicitly. How to Dene Object Relationships and Attributes Procedure Reference: Create a Class To create a class: 1. Type import PackageName; to import the packages required for using the in-built methods. 2. Type modifier class ClassName to dene a class. 3. Type { } to enclose the body of the class. 4. Within braces, enter the elds and methods of the class. To assign class variables within a method with values passed from another class, through an object, use the this keyword. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 60 5. Save the le as a Java program. 6. If necessary, compile the program. A program without the main method is abstract, does not produce any result, and so cannot be run. Procedure Reference: Create an Object To create an object: 1. Dene a class and the main method. 2. Type ClassName ObjectName= new ClassName(); to create an object. The class name dened in the object should be the same in both instances. 3. Type ObjectName.MethodName(); to call a method in the class. The name of the method should match one of the public methods within the class. 4. Type System.out.println(ObjectName.MethodName); to display the return value of the called method. 5. Save the le as a Java program. 6. Compile and execute the program. Procedure Reference: Create a Java Package To create a Java package: 1. Create the desired classes required for the application. 2. Come up with the desired package name. 3. In the Java program that contains the necessary classes (modules of the applica- tion), as the rst line of the program, type package PackageName; 4. If necessary, you can import the newly created packages into another Java pro- gram. In the new Java program, as the rst line of the program, type import PackageName; 5. Save the Java programs. 6. To compile the packages, in the command prompt, enter javac -d DirectoryName PackageNameThis will inform the compiler to create a subdirectory in the desired directory and place class les inside it. If you want the subdirectory to be created in the current directory itself, you have to use the dot operator (.) instead of the desired directory name. 7. If desired, run the program. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 61 ACTIVITY 4-1 Creating an Object for a Class Before You Begin: 1. Open the Command Prompt window and minimize it. 2. In the Notepad++ application, open a new le and save it as EmployeeDetails.java in the folder C:\085969Data\Elements of OOP. 3. Choose ViewWrap. Scenario: You have been assigned the task of creating an employee database application for Our Global Company. As a programmer, you have had discussions with your client about the requirements for the proposed application, and they have provided necessary details about an employee. The details include the name, age, social security number, gender, employee ID, address, phone number, email ID, role, department, and salary. Some of the requirements of your client are: Upon request, the proposed application has to display the following information about an employee: employee name, employee ID, age, social security number, gender, address, phone number, email ID, role, and department he/she belongs to. Also, based on the salary information provided, the application should calculate the employees annual income and display the same. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 62 What You Do How You Do It 1. In the EmployeeDetails.java file, import Java packages and declare the EmployeeDetails class. a. In line 1, type import java.util.*; to import the utilities package. b. Press Enter and type import java.io.*; to import the package that provides system input and output meth- ods. The character indicates that the code is con- tinued in the next line. When the character is encountered, the next line of code given in the book should be typed as one continuous line in the application. c. Press Enter twice and type class EmployeeDetails { to declare the EmployeeDetails class. d. Press Enter twice. e. Type } to close the body of the EmployeeDetails class. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 63 2. Declare the variables for the EmployeeDetails class. a. Press the Up arrow key and then press the Spacebar twice. b. In line 5, type String EmpName; to declare EmpName as a string variable. c. Press Enter. d. Add code to declare int Age, String SSN, String Dept, String Gender, int EmpId, String PhoneNo, String Address, String emailId, String JobRole, and double Salary as variables. See Code Sample 1. Code Sample 1 String EmpName; int Age; String SSN; String Dept; String Gender; int EmpId; String PhoneNo; String Address; String emailId; String JobRole; double Salary; LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 64 3. Define the Display() and AnnualIncome() methods for the EmployeeDetails class. a. Press Enter twice. b. In line 17, type public void Display(String name, int empno, int a, String socialno, String gend, String addr, String phone, String email, String desgn, String team) { to define the Display() method for the class. c. Press Enter. d. In line 18, add code to assign values to the variables EmpName, EmpId, Age, SSN, Gender, Address, PhoneNo, emailId, JobRole and Dept. See Code Sample 2. e. Press Enter and type System.out.println("Employee Name: "+EmpName); to display the employees name. f. Press Enter. g. Add code to display the EmpId, Age, Gender, SSN, Address, PhoneNo, emailId, JobRole, and Dept information about the employee. See Code Sample 3. h. Press Enter and type } to close the Display() method definition. i. Press Enter and type public double AnnualIncome(double income) { to define the AnnualIncome() method for the class. j. Press Enter and type this.Salary = income; to assign the income value to the Salary variable of the current object which is calling the method. k. Press Enter and type return(Salary * 12); to return the gross salary of the employee. l. Press Enter and type } to close the AnnualIncome() method definition. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 65 Code Sample 2 public void Display(String name, int empno, int a, String socialno, String gend, String addr, String phone, String email, String desgn, String team) { EmpName = name; EmpId = empno; Age = a; SSN = socialno; Gender = gend; Address = addr; PhoneNo = phone; emailId = email; JobRole = desgn; Dept = team; Code Sample 3 System.out.println("Employee Name: "+EmpName); System.out.println("Employee ID: "+EmpId); System.out.println("Age: "+Age); System.out.println("Gender: "+Gender); System.out.println("Social Security Number: "+SSN); System.out.println("Address: "+Address); System.out.println("Phone Number: "+PhoneNo); System.out.println("Email ID: "+emailId); System.out.println("Designation: "+JobRole); System.out.println("Department: "+Dept); LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 66 4. Declare the main method and get the employee details from the user. a. Press Enter twice. b. Type public static void main(String args[]) throws Exception { to declare the main method. c. Press Enter and type DataInputStream S = new DataInputStream(System.in); to declare an object for the console opera- tion. d. Press Enter and type System.out.print("Enter Employee Name: "); to act as a prompt for the user to enter the desired employees name. e. Press Enter and type String name = S.readLine(); to get the employee name from the user. f. Press Enter. g. Similarly, add code to get the employee ID, employees age, gender, social secu- rity number, address, phone number, email ID, role, department, and salary information from the user. See Code Sample 4. Code Sample 4 String name = S.readLine(); System.out.print("Enter Employee ID: "); int eid = Integer.parseInt(S.readLine()); System.out.print("Enter Employee's Age: "); int ag = Integer.parseInt(S.readLine()); System.out.print("Enter Gender: "); String gen = S.readLine(); System.out.print("Enter Employee's Social Security Number: "); String ssn = S.readLine(); System.out.print("Enter Address: "); String adr = S.readLine(); System.out.print("Enter Phone Number: "); String phno = S.readLine(); System.out.print("Enter Email ID: "); String emlid = S.readLine(); System.out.print("Enter Role: "); String rle = S.readLine(); System.out.print("Enter Department: "); String dpt = S.readLine(); System.out.print("Enter Salary: $"); LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 67 double sal = Double.parseDouble(S.readLine()); 5. Create an object for the EmployeeDetails class, display the employee information, and calculate the annual income. a. Press Enter twice. b. Type EmployeeDetails obj = new EmployeeDetails(); to create an object obj for the EmployeeDetails class. c. Press Enter and type obj.Display(name, eid, ag, ssn, gen, adr, phno, emlid, rle, dpt); to call the Display() method. d. Press Enter and type System.out.println("Annual Income: $"+obj.AnnualIncome(sal)); e. Press Enter and type } to close the main method definition. f. Save and close the file. g. Minimize the Notepad++ application. 6. Compile and execute the Java pro- gram. a. Switch to the Command Prompt window and clear the screen. b. Type cd C:\085969Data\Elements of OOP and press Enter to change the directory. c. Type javac EmployeeDetails.java and press Enter to compile the Java pro- gram. d. Type java EmployeeDetails and press Enter to execute the program. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 68 7. Provide the employee information. a. At the Enter Employee Name prompt, enter the desired name as the employee name. b. At the Enter Employee ID prompt, enter the employees ID. c. At the Enter Employees Age prompt, enter the employees age. d. At the Enter Gender prompt, enter the employees gender. e. At the Enter Employees Social Security Number prompt, enter the employees social security number. f. At the Enter Address prompt, enter the address. g. At the Enter Phone Number prompt, enter the employees phone number. h. At the Enter Email ID prompt, enter the email ID. i. At the Enter Role prompt, enter the role. j. At the Enter Department prompt, enter the employees department. k. At the Enter Salary prompt, enter the sal- ary. l. Observe that the result displays all infor- mation about the employee along with the annual income. m. Minimize the Command Prompt window. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 69 ACTIVITY 4-2 Integrating Department and EmployeeInfo Classes Data Files: Department.java EmployeeInfo.java Before You Begin: 1. In the Notepad++ application, open a new le and save it as DisplayEmployees.java in the folder C:\085969Data\Elements of OOP. 2. From the C:\085969Data\Elements of OOP folder, open the EmployeeInfo.java le in the Notepad++ application. 3. From the C:\085969Data\Elements of OOP folder, open the Department.java le in the Notepad++ application. Scenario: You are creating an application to store employee information of Our Global Company. Your colleague, Samuel, has created an EmployeeInfo class which contains important details about an employee such as the name, employee ID, social security number, role, department, and salary. The class also has a method which will display the information about the employee. Another colleague, Jordan, has created a Department class which contains the list of departments available in Our Global Company. You are asked to integrate the two classes, and use them as individual modules in another class. In order to test the integrated application, you will use the information provided by Our Global Company about two of its employees. The rst employee is James Hope whose employee ID is 825 and social security number is 340-86-1924. His designation is HR Executive belonging to the Human Resources department, whose salary is $6700. The second employee is Joanne Moore. Her employee ID is 1239 and social security number is 257-84-3603. She is a Project Lead belonging to the Project Management department. Her salary is $8500. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 70 What You Do How You Do It 1. In the Department class, create a package statement and make the class public. a. In the Department.java file, in line 1, before the keyword class, press Enter. b. In line 1, type package OGCInfo; to make the Department class part of the OGCInfo package. c. In line 2, click before class and type public to make the Department class public and available to other classes and press the Spacebar. d. Save and close the file. 2. In the EmployeeInfo class, create a package statement and instantiate class variables within the Display method with values passed from an object of the class. a. In the EmployeeInfo.java file, in line 1, before the keyword class, press Enter. b. In line 1, type package OGCInfo; to make the EmployeeInfo class part of the OGCInfo package. c. In line 2, click before class and type public to make the EmployeeInfo class public and available to other classes and press the Spacebar. d. In line 11, before EmpName, click and type this so that the EmpName variable becomes the instance variable of the cur- rently executing class. e. Similarly, add the this keyword and the dot operator (.) to EmpId, SSN, Dept, JobRole, and Salary variables of the Display() method. f. Save and close the file. 3. Import the EmployeeInfo and Department modules of the package OGCInfo. a. In the DisplayEmployees.java file, in line 1, type import OGCInfo.EmployeeInfo; to include the EmployeeInfo class. b. Press Enter and type import OGCInfo.Department; to include the Department class. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 71 4. In the DisplayEmployees class, in the main method, create two objects, one for the EmployeeInfo class and one for the Department class to display employee informa- tion. a. Press Enter twice and type class DisplayEmployees { to declare the DisplayEmployees class. b. Press Enter twice. c. Type } to close the body of the EmployeeDetails class. d. Press the Up arrow key and then press the Spacebar twice. e. In line 5, type public static void main(String args[]) { to define the main method. f. Press Enter and type EmployeeInfo obj = new EmployeeInfo(); to create an object obj for the EmployeeInfo class. g. Press Enter and type obj.Display("James Hope", 825, "340-86-1924", "HR Executive", "Human Resources", 6700.00); to pass values to the Display() method of the EmployeeInfo class. h. Press Enter and type System.out.println("\n"); to pro- vide two lines of delimiting space between the output generated. i. Press Enter and type obj.Display("Joanne Moore", 1239, "257-84-3603", "Project Lead", "Project Management", 8500.00); to pass values to the Display() method of the EmployeeInfo class. j. Press Enter and type System.out.println("\n"); to pro- vide two lines of delimiting space between the output generated. k. Press Enter and type Department obj2 = new Department(); to create an object for the Department class and call the Department() constructor. l. Press Enter and type } to close the main LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 72 method definition. m. Save and close the file. n. Minimize the Notepad++ application. 5. Compile and execute the Java pro- gram. a. Switch to the Command Prompt window and clear the screen. b. Type javac -d . EmployeeInfo.java Department.java to inform the compiler to place the generated class files in the root folder and press Enter. c. Type javac DisplayEmployees.java and press Enter to compile the Java pro- gram. d. Type java DisplayEmployees and press Enter to execute the program. e. Observe the result which displays the information about two of the employees and the names of the departments of Our Global Company. f. Minimize the Command Prompt window. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 73 DISCOVERY ACTIVITY 4-3 Automating the Personnel Department Scenario: You have been assigned the task of automating your companys personnel department. To start with, you initially conduct a study of the constituents and processes within the department. Before you start with the study, you would like to test your knowledge on identifying the object relationships and their attributes. 1. You have identified the various objects within the department and studied their simi- larities and differences. What is this process called? a) Encapsulation b) Information Hiding c) Abstraction d) Modularity 2. You now need to break down the payment procedure into two subproceduresone for paying employees and the other for paying contractors. Which feature of object- oriented programming allows you to achieve this? a) Abstraction b) Encapsulation c) Information hiding d) Modularity 3. In the sample code prepared for the personnel department of an organization, identify the unnecessary attributes. Analyze why some of the attributes are deemed unneces- sary. class employee { String EmpName; int Age; int noOfPets; boolean isBald; } Having one name property is probably not as useful as having separate properties for first and last names. Because age is a factor of time, the age property will become outdated. It would be better to have a date-of-birth property. The other properties, numberOfPets and isBald, are probably not relevant to the type of processing that will be done on an employee object. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 74 DISCOVERY ACTIVITY 4-4 Modeling the Organizational Chart Scenario: As part of automating the personnel department, you need to model the hierarchy within the department. Before you start with the modeling, you would like to identify the various classi- cation schemes. 1. You need to create a separate class for managers. Which classification of objects does this task fall under? a) Representing real objects b) Representing interactions, sequences, steps, or events c) Representing relationships d) Representing a role or function 2. True or False? If you create an object to model the organization chart, it falls under the classification scheme for objects that represent relationships. True False 3. True or False? You created a class to represent the information of employees in the personnel department. An instance of this class is called an object. True False LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 75 TOPIC B Identify the Relationship Between Classes You have dened object relationships and attributes. In a given program, you may need to dene a number of classes that constantly interact and exchange data among themselves. How- ever, before these classes interact, you need to set the relationship between them to facilitate the data exchange process. In this topic, you will identify the relationship between classes. Let us assume that a car company has decided to come up with a new model. It is implied that when they go about building a new model, they will not start at a stage where they dene what a car is. Instead, they will try improvising on their existing model. Similarly, object ori- ented programming allows you to base one class on another, thus reducing the time involved in dening a new class. Subclasses Denition: A subclass is a class that is based on another class. It inherits the attributes and meth- ods of the class it is based on. It can also include new attributes and methods. Example: An Example of a Subclass Consider the following class: Subclasses LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 76 class Person { String Name; int Age; String hairColor; String eyeColor; //Rest of the definitions // Main function //Objects Person Dean = new Person(); Person Remi = new Person(); James.Name = "Dean Moriarty"; Remi.Name = "Remi Boncoeur"; } Notice that both instances of the Person class (objects Dean and Remi) are a spe- cial type of people. Given the special attributes of some people (susceptibility to bouts of restlessness and wanderlust, affinity to coffee, and a continual quest for kicks), you might consider creating a special type or class of person called a Wanderlust. In addition to the Person class, you could create an entirely new class: class Person { String Name; int Age; String hairColor; String eyeColor; //Rest of the definitions } class Wanderlust extends Person { String currentCity; String favoriteCoffee; int writesHowManyPagesPerMinute; string currentNovel; String findsKicksWhere; // Main function //Objects Person Dean = new Person(); Person Remi = new Person(); James.Name = "Dean Moriarty"; Remi.Name = "Remi Boncoeur"; } In this example, the class Wanderlust is a subclass of the class Person. Sub- class is not used here in any derogatory senseit simply means that the Wanderlust class has all of the attributes of the Person class, as well as some additional attributes, such as the current city in which the wanderlust lives (important to track because wanderlusts move so often), favorite kind of coffee, and so forth. The effective properties of a wanderlust are: Name (inherited from Person) Age (inherited from Person) hairColor (inherited from Person) LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 77 eyeColor (inherited from Person) currentCity favoriteCoffee writesHowManyPagesPerMinute currentNovel ndsKicksWhere Inheritance Denition: Inheritance is a feature of object-oriented programming that allows a subclass to acquire the attributes and methods of its parent class. Using inheritance, a change you make to a parent class is applied to all its subclasses. Furthermore, attributes and meth- ods can be passed down through multiple generations. That is to say, a subclass can be based on another subclass, thereby inheriting the attributes and methods of its parent and of all its ancestors. Example: Understanding Inheritance Through Examples In the following example, Dog and Human are subclasses of Animal, and Wanderlust and Beagle are subclasses of Human and Dog, respectively. There are three generations in this example: class Animal { int Age; String Kingdom; String Phylum; String Class; String Order; String Family; String Genus; String Species; //Rest of the definitions } class Dog extends Animal { String Breed; String Markings; Inheritance LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 78 //Rest of the definitions } class Beagle extends Dog { String AKA_identification; //Rest of the definitions } class Human extends Animal { String Name; String hairColor; String eyeColor; //Rest of the definitions } class Wanderlust extends Human { String currentCity; String favoriteCoffee; int writesHowManyPagesPerMinute; String currentNovel; String findsKicksWhere; } In this example, theres a whole lot of inheritance going on. For example, here are the attributes of a Wanderlust, most of which it inherits from its ancestor classes, Human and Animal: Age (inherited from Human, which inherits it from Animal) Kingdom (inherited from Human, which inherits it from Animal) Phylum (inherited from Human, which inherits it from Animal) Class (inherited from Human, which inherits it from Animal) Order (inherited from Human, which inherits it from Animal) Family (inherited from Human, which inherits it from Animal) Genus (inherited from Human, which inherits it from Animal) Species (inherited from Human, which inherits it from Animal) Name (inherited from Human) hairColor (inherited from Human) eyeColor (inherited from Human) currentCity favoriteCoffee writesHowManyPagesPerMinute currentNovel ndsKicksWhere Levels of Inheritance Java supports ve types of inheritance each of which is implemented in a variety of ways. Based on the requirements of the application, a programmer can choose an inheritance type that best serves the purpose. The table provides a description of each inheritance level. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 79 Type Description Single Is the ability of a class to inherit or derive the attributes and behaviors of a single parent class. A child class can not only inherit the members of the parent class, but it can also have its own unique members. The parent class is also known as the base class or superclass and the child class is known as the derived class or subclass. Multilevel Is the ability of a class to inherit or derive the attributes and behaviors from a child class which is a child class of another parent class. Hierarchical Is the ability of many child classes inheriting their attributes from a single parent class. Multiple Is the ability to derive a child class from more than one parent class. Having more than one par- ent class implies that the child class inherits the attributes and behaviors of all its parents. In Java, multiple inheritance is implemented only through interfaces. Hybrid Is the combination of any of the two inheritance types. For example, it can be a combination of multilevel and single inheritance. How to Identify the Relationship Between Classes Procedure Reference: Create a Subclass To create a subclass: 1. Open a Java program containing a class. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 80 2. Type childClassName extends className to create a subclass. 3. Type the body of the class within braces, {}. 4. Save the le. 5. Compile and execute the program. ACTIVITY 4-5 Creating a Manager Subclass of the Employee Class Data Files: EmployeeInherit.java Before You Begin: From the C:\085969Data\Elements of OOP folder, open the EmployeeInherit.java le in the Notepad++ application. Scenario: You have already created the Employee class, which has the employees name, social secu- rity number, and salary variables. It also contains two functions, one displays the employees name and social security number, and the other calculates his overall salary for a year. Your client, Our Global Company, provides you with details about the managers of various departments. A manager in Our Global Company receives an allowance for a calendar year based on his teams performance. This allowance will be added to the annual salary and is considered the total salary. As part of your clients requirements, you now have to create a Manager class, which is based on the Employee class, and calculate the managers total salary for a calendar year and display all information. After you create the classes, as part of testing them, you will provide the desired information about any employee of the organization and test the veracity of the code. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 81 What You Do How You Do It 1. Define Manager as a subclass to the Employee class and define its mem- bers. a. In the EmployeeInherit.java file, in line 19, at the end of the closing brace of the Employee class, press Enter twice. b. Type class Manager extends Employee { to declare the Manager class as a subclass of the Employee class. c. Press Enter twice. d. Type } to close the body of the Manager class. e. Press the Up arrow key and then press the Spacebar twice. f. Type double allowance; to declare allowance as a variable of type double. g. Press Enter and type public void CalculateAllow(double a) { to define the method CalculateAllow() for the Manager class. h. Press Enter and type allowance = a; to assign the value to the allowance variable. i. Press Enter and type double TotalSalary = Salary + allowance; to calculate the total salary for the manager. j. Press Enter and type System.out.println("Total Salary: $"+TotalSalary); to display the total salary of the manager. k. Press Enter and type } to close the CalculateAllow() method. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 82 2. Declare the EmployeeInherit class and the main method. a. In line 28, at the end of the closing brace of the Manager class, press Enter twice. b. Type class EmployeeInherit { to declare the EmployeeInherit class. c. Press Enter twice. d. Type } to close the body of the EmployeeInherit class. e. Press the Up arrow key and then press the Spacebar twice. f. Type public static void main(String args[]) throws Exception { to declare the main method. g. Press Enter and type DataInputStream S = new DataInputStream(System.in); to declare an object for the console opera- tion. h. Press Enter and type System.out.print("Enter Employee Name: "); to act as a prompt for the user to enter the desired employees name. i. Press Enter and type String name = S.readLine(); to get the employee name from the user. j. Press Enter. k. Similarly, add the code to get the social security number, salary and allowance information from the user. See Code Sample 1. Code Sample 1 String name = S.readLine(); System.out.print("Enter Employee's Social Security Number: "); String ssn = S.readLine(); System.out.print("Enter Salary: $"); double sal = Double.parseDouble(S.readLine()); System.out.print("Enter the Allowance: $"); double allo = Double.parseDouble(S.readLine()); LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 83 3. Create an object for the Manager class, display the employee informa- tion, and calculate the annual income and the total allowance. a. Press Enter twice. b. Type Manager obj = new Manager(); to cre- ate an object obj for the Manager class. c. Press Enter and type obj.Display(name, ssn); to call the Display() method. d. Press Enter and type System.out.println("Annual Salary: $"+obj.AnnualSalary(sal)); to calculate the annual salary of the employee and display the same. e. Press Enter and type obj.CalculateAllow(allo); to call the CalculateAllow() method. f. Press Enter and type } to close the main method definition. g. Save and close the file. h. Minimize the Notepad++ application. 4. Compile and execute the Java pro- gram. a. Switch to the Command Prompt window and clear the screen. b. Type javac EmployeeInherit.java and press Enter to compile the Java pro- gram. c. Type java EmployeeInherit and press Enter to execute the program. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 84 5. Provide the employee information. a. At the Enter Employee Name prompt, enter the desired name as the employee name. b. At the Enter Employees Social Security Number prompt, enter the employees social security number. c. At the Enter Salary prompt, enter the sal- ary. d. At the Enter the Allowance prompt, enter the allowance information of the employee. e. Observe the result displays all the infor- mation about the employee along with the annual income, and allowance. f. Minimize the Command Prompt window. DISCOVERY ACTIVITY 4-6 Modeling the Workow Structure of the Personnel Department Scenario: As part of automating the personnel department, you are expected to model the workow structure within the department. Before you start modeling the workow, you would like to test your knowledge of identifying the relationship between the classes involved. 1. The accessibility of information within the organization is modeled in such a way that a subordinate is authorized to view information related to his role but not classified information, whereas a manager will be able to view all information that his subordi- nate is authorized to view. Apart from this, the manager also has access to classified information. Which object-oriented feature will you deploy here? a) Abstraction b) Encapsulation c) Information Hiding d) Inheritance LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 85 2. Assume that a new manager is appointed. The new manager needs to have the same privileges as the other managers. Which object-oriented feature will help you do this? a) Encapsulation b) Inheritance c) Information Hiding d) Abstraction TOPIC C Implement Multiple Forms of the Same Procedure You have examined the instances of implementing just one form of a procedure within a class. However, in real-time programming, you will be required to implement multiple forms of the same procedure with varied types of input from the user to perform the same action. In this topic, you will implement multiple forms of the same procedure. Lets take the example of an organization with a large number of employees, some of whom share the same name. When a call lands at the office reception asking for a person with a name shared by a couple of other employees, the call gets transferred based on other details specic to the employee, such as his department, second name, or designation. Similarly, object-oriented programming allows the implementation of different forms of a single function, based on the input provided by the end user. Polymorphism Denition: Polymorphism is the ability to assign different uses to an entity under different con- texts. In object-oriented programming, this ability allows you to create a grouping of objects, to send the same message to different objects in the hierarchy, and to enable objects to determine which behavior can be used to respond to the message in the hier- archy. Example: Polymorphism LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 86 Achieving Abstraction Through Polymorphism There may be times when you want to treat different objects in similar ways. For example, an automobile class might be passed to a function named move, which enables you to get the automobile moving in a certain direction at a certain speed. You might also have a helicopter class that you want to be able to pass to the move function. The problem is that these dont all move in quite the same way. For example, a helicopter is propelled through the air by two separate motor-driven propellers. There is a big propeller on top to lift the helicopter, and a little one on the tail to counteract the torque generated by the big propeller and to provide some steer- ing capability. On the other hand, trucks move in a very different manner from a helicopter. Their drive wheels push them by creating directional friction against the road. The truck is steered by changes in the direction of the front tires. Internally, something very different happens with each vehicle to make it move. With object-oriented programming, being able to create abstractions that hide such dif- ferences is part of what makes it powerful. With an abstraction such as the move function, you could make a helicopter move the same way that you could make a truck move, without having to worry about the details that are hidden beneath the abstrac- tion. The move(truck1, 75, "north") command would make a truck go 75 miles per hour in a northerly direction just as move (helicopter1, 75, "north") would make a helicopter move in the same direction at the same speed. An Example of Polymorphism Consider the example shown in the following code: class motorVehicle { //various motorVehicle properties and methods go here public void move() { //Function definition for the motorVehicle class } } class Automobile extends motorVehicle { //various automobile properties and methods go here public void move() { //Function definition for the automobile class } } class Helicopter extends motorVehicle { //various helicopter properties and methods go here public void move() { //Function definition for the helicopter class } } class myTypeOfVehicle { public static void main(String args[]) { motorVehicle theVehicle = new motorVehicle(); public void move(motorVehicle theVehicle, int theDistance, LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 87 direction theDirection) { if(theVehicle = helicopter) //move the vehicle like a helicopter else if(theVehicle = automobile) //move the vehicle like an automobile Helicopter helicopter1 = new Helicopter(); Automobile truck1 = new Automobile(); move(helicopter1, 75, "North"); move(truck1, 75, "North"); } This code denes a motorVehicle class. It then creates two subclasses of motorVehicle: Automobile and Helicopter. These two subclasses inherit the properties and methods of the motorVehicle parent class. A move method is also declared. This method must be passed three parameters when it is called: a motor vehicle object, an integer specifying the speed, and the direction. The move method performs different routines to set the speed and direction of the different kinds of motor vehicles. Finally, the code example creates two objects: helicopter1 (a heli- copter) and truck1 (an automobile). These are two different classes of objects (which share an ancestor class of motorVehicle). The code then uses the same method to move both types of objects, even though the method treats the two objects differently. To a user of the move method, the implementation details are hidden. Moving a heli- copter is the same as moving an automobile. This is what is meant by polymorphism. Polymorphism means many forms. The polymorphic move function provides one interface for dealing with these two classes, yet its implementation branches as needed to support the different classes of objects that might be passed to it. Somewhere, your code needs to dene how to treat different classes of objects differently. But once that code is implemented, you can treat objects from different subclasses the same. Another Example of Polymorphic Usage Polymorphism is best used in situations which involve at least two different types of objects that might be passed to the same function, but that would require different pro- cessing. Suppose you wanted a copy method that could copy a le object or a folder object. The code needed to copy a le would be different from the code needed to copy an entire folder full of les. By using polymorphism you can provide a copy method that is versatile enough that it can be used with either les or folders, and pro- duce the result that most users would expect. Types of Polymorphism Polymorphism can be categorized as static and dynamic polymorphism. The way methods are dened in parent and child classes helps to determine the type of polymorphism that is applied. Refer to the table for a description of each type of polymorphism. Type Description Static Is the ability to overload a method using different sets of parameters, so that the method name remains the same. This type of polymorphism is achieved through method overloading and the call to the method is resolved during compile-time. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 88 Type Description Dynamic Is the ability of a child class to override the method of the parent class. The method in the child class should have the same method name and set of parameters. In Java, method overriding is implemented through both inheritance and inter- faces. The call to the method is resolved during runtime. Method Overload When two or more methods have the same name, they are differentiated by parameters. The object that calls a method needs to pass values that match the parameters of the method. A programmer needs to create overloading methods when a method needs to execute the same logic with different sets of parameters. For example, System.out.println() is designed so that it prints all data types by pass- ing them as parameters. This makes the task of printing much easier for programmers because they can use the same method for all data types instead of having to use different methods for diverse data types. Method Override When the signature and data type of a method in a child class are the same as that of the method in a parent class, the child class method takes precedence over the parent class method. When a method is called by the object of the child class, the child class method is executed and the parent class method is ignored. How to Implement Multiple Forms of the Same Procedure Procedure Reference: Implement Multiple Forms of the Same Method To implement multiple forms of the same method: 1. Determine the methods which are part of both the base and derived classes and that need to be implemented differently in the derived class. 2. Dene the methods for both the base and derived classes. 3. In the class denition, identify the method you would like to overload or override. 4. For overloading a method, dene the method with the same name but with differ- ent arguments or a different number of arguments. 5. For overriding a method, dene the method with the same name and with the same type or number of arguments in both classes. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 89 ACTIVITY 4-7 Implementing Various Forms of the Display Method Data Files: MultipleForms.java Before You Begin: From the C:\085969Data\Elements of OOP folder, open the MultipleForms.java le in the Notepad++ application. Scenario: You have created two classes, Employee and Payroll. The details included in the Employee class are as follows: employees name, ID, designation, department, date joined, and salary variables. It also contains a method that will display only the employees ID. In the Payroll class, you have dened a method that will calculate the employees annual salary. Your client, Our Global Company, has now informed you that they consider the Payroll class as an extension of the Employee class. Also, they have asked you to incorporate some additional requirements as follows: Add two new methods, one in the Employee class and one in the Payroll class. These methods can have the same name as the existing names. It is left to your discretion. The Employee class method has to print the name of the employee and his des- ignation. The Payroll class method will print the name of the department the employee belongs to and date he joined the organization. As part of your clients requirements, you now have to make the Payroll class an extension of the Employee class and would like to display all the relevant information about the employee. After you create the class, as part of testing it, you will provide the desired information about any employee of the organization and test the veracity of the code. LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 90 What You Do How You Do It 1. In the Employee class, define another Display() method with two arguments. a. In line 17, click and type public void Display(String Name, String Role) { to define the Display() method having two String arguments. b. Press Enter. c. Add the code to assign the values of Name and Role to the EmpName and Designation variables of the Employee class and print the values. See Code Sample 1. d. Press Enter and type } to close the body of the Display() method. Code Sample 1 public void Display(String Name, String Role) { this.EmpName = Name; this.Designation = Role; System.out.println("Employee Name: " +EmpName); System.out.println("Designation: "+Designation); LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 91 2. Make the Payroll class the subclass of the Employee class and define a Display method for the Payroll class with two arguments. a. In line 27, click before the opening brace and type extends Employee to make the Payroll class a subclass of the Employee class and press the Spacebar. b. In line 33, press the Spacebar twice. c. Type public void Display(String Dept, String JoinDate) { to define the Display() method having two String arguments. d. Press Enter and then press the Spacebar twice. e. Add the code to assign the values of Dept and JoinDate to the Department and DoJ variables of the inherited Employee class and print the values. See Code Sample 2. f. Press Enter and type } to close the body of the Display() method. Code Sample 2 public void Display(String Dept, String JoinDate) { this.Department = Dept; this.DoJ = JoinDate; System.out.println("Employee's Department: " +Department); System.out.println("Joining date of the Employee: "+DoJ); LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 92 3. Create two objects, one for the Employee class and one for the Payroll class. Call the Display methods of both classes. a. In line 58, above the closing brace of the main method, type Employee obj = new Employee(); to create an object obj for the Employee class. b. Press Enter and type Payroll obj2 = new Payroll(); to create an object for the Payroll class. c. Press Enter and type System.out.println("Employee's ID:" +obj.Display(eid)); to call the Display() method having one param- eter of the Employee class. d. Press Enter and type obj.Display(name, rle); to call the Display() method having two param- eters of the Employee class. e. Press Enter and type obj2.Display(dpt, JDate); to call the Display() method having two parameters of the Payroll class. f. Press Enter and type System.out.println("Employee's Annual Salary: $"+obj2.Display(salary)); to call the Display() method having a single parameter of the Payroll class. g. Save and close the file. h. Minimize the Notepad++ application. 4. Compile and execute the Java pro- gram. a. Switch to the Command Prompt window and clear the screen. b. Type javac MultipleForms.java and press Enter to compile the Java program. c. Type java MultipleForms and press Enter to execute the program. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 93 5. Provide the employee information. a. At the Enter Employee Name prompt, enter the desired name as the employee name. b. At the Enter Employee ID prompt, enter the employees identification number. c. At the Enter Role prompt, enter the employees designation. d. At the Enter Department prompt, enter the name of the department the employee belongs to. e. At the Enter the Date Joined prompt, enter the date when the employee joined the organization. f. At the Enter the Monthly Salary prompt, enter the desired salary of the employee. g. Observe that the result displays all the information about the employee. h. Minimize the Command Prompt window. DISCOVERY ACTIVITY 4-8 Automating the Payment Process of the Personnel Department Scenario: As part of automating the personnel department, you are expected to come up with a concrete procedure to facilitate payment to all stakeholders. Stakeholders include employees as well as contractors. Before you work on the automation, you would like to test your knowledge of implementing multiple forms of the same procedure. 1. You need to implement the same function to make a payment for both permanent employees and contractors. Which object-oriented feature will you deploy? a) Polymorphism b) Encapsulation c) Inheritance d) Abstraction LESSON 4 Object-Oriented Programming and Design Using Java (Third Edition) 94 2. True or False? The polymorphism feature can be used to write a single function called Incentivecalc to calculate the monthly incentives of different employee objects at various levels in the organization. True False Lesson4Follow-up In this lesson, you identied the elements of object-oriented programming. You will now be able to use these elements to manipulate object representations and interactions. 1. In what way implementing the object-oriented methodology in your projects will help you? Explain. Answers will vary but may depend on the students understanding of the object-oriented methodology. Proper implementation of the object-oriented methodology in your projects will help you clearly analyze the requirements of the user, describe clear use cases and design, and construct the software using reusable components. You might also extend the code to include future requirements, make the software robust and meaningful, and ensure easy maintenance and increased quality of the code. It is also easy to chalk out code that will fit hand in glove with real-world scenarios and issues. 2. What are the benefits of implementing inheritance and polymorphism in your pro- grams? Answers will vary but may include easy maintenance, flexibility, code reuse, ability of the base class to extend itself over the various derived classes that increase the perfor- mance of the code, and the ability of the methods to decide which method to call based on its signature. By implementing polymorphism, you may be able to apply different functionalities to the various methods in each of the subclasses. LESSON 4 Lesson 4: Identifying the Elements of Object-Oriented Programming 95 Object-Oriented Programming and Design Using Java (Third Edition) 96 NOTES Determining the Use of Object-Oriented Programming in Windowed Applications In this lesson, you will determine the use of object-oriented programming in windowed appli- cations. You will: Explore the structure and working of a windowed application. Examine the use of frameworks in developing an application. Lesson Time 30 minutes LESSON 5 LESSON 5 Lesson 5: Determining the Use of Object-Oriented Programming in Windowed Applications 97 Introduction You examined the use of the object model for software coding. However, object coding tends to differ for various programming environments. In this lesson, you will determine the use of object programming in windowed applications. Windowed applications have similar functionality and features that require the same class structures to be used. Object-oriented programming facilitates the predenition and reusability of these class structures for application development, thus reducing development time. TOPIC A Explore the Structure and Working of a Windowed Application You examined the predened class structures used for windowed applications. However, before you start using these class structures, you need to understand the workings of a windows appli- cation. In this topic, you will explore the structure of a windows application. Object-oriented programming facilitates the development of complex programs which can do more than one task at any given time. With object-oriented applications, you will be able to carry out multiple tasks such as listening to music even as you keep working on your com- puter. Evolution Stages in Application Development Applications have evolved from being batch and command-line programs to event-driven, interactive programs. Refer to the table for a description of each stage of application evolution. Evolution Stage Description Batch mode Early computers ran programs in batch mode. Batch programs consist of a simple sequence. In this mode a user would submit a batch of informa- tion (using paper tape or paper cards with information encoded through holes that were punched into it) to be processed, and the computer would generate the results (on a teletypewriter/ printer, or onto another paper tape). LESSON 5 Object-Oriented Programming and Design Using Java (Third Edition) 98 Evolution Stage Description Interactive modecommand-line interface As computers became more abundant, more people operated them in interactive mode. In this mode, the computer prompts the user for information on a display screen, and the user enters information using a keyboard. Computer programs were written to run from a command line, and were not much different from the batch mode programs. Instead of submitting information through paper tape, disk les might have been used, but running a program typically consisted of one input and output (or batch) cycle, at the end of which, the program returned to the command line. Interactive modesingle screen interface Programs were then written to take advantage of the interactive relationship between the user and the computer. Rather than spending most of their time issuing commands at a command line, users of personal computers ran programs that provided environ- ments in which they got their work done. While looking at a single screen, a user could opt to do many different things: print, generate a report, save the le, and so forth. At that point, computers were not generally multitasking and programs tended to be very modal. If a user was in the process of entering data in a spreadsheet, and wanted to import some information in a database program, the user would have to save the spreadsheet, exit the spreadsheet program, run the database program, export the data to a le format that could be imported into the spreadsheet, exit the database program, run the spreadsheet program, and import the data. Interactive modeWIMP In todays WIMP (windows, icon, mouse, pull- down menus) computer environments, users hardly give a thought to moving data from one program to another. In todays environment, apart from being able to copy and paste data from one win- dow to another, users are also able to embed one application within another, using a technology such as ActiveX. Evolution of Application Programs Applications have evolved a long way from command-line programs, which did things in a very sequential fashion, to visually enhanced complex programs, which are event driven. Command-line programs had a predictable start (data submitted), middle (the data is processed), and end (the results are returned as output). Soon, spreadsheet programs, word processors, and other productivity software ushered in the age of personal computing. Environments such as VisiCalc and Lotus 123 provided menus or keyboard commands to do different things. LESSON 5 Lesson 5: Determining the Use of Object-Oriented Programming in Windowed Applications 99 Things are not so clear-cut for todays event-driven programs. They need to be written so that they can respond to events from users, other programs, the operating system, and various devices. In many cases, programs also need to account for the fact that they might be embedded as objects within other programs. Embedded object technolo- gies take advantage of object-oriented design, encapsulating all of the necessary data and methods to enable information objects to work outside of their normal application context (like a portion of a database being embedded within a word processor docu- ment or a spreadsheet). Application of OOPs in Windowed Applications Most aspects of windowed applications are common across all programs. For example, most windowed applications have windows with a title bar, a close button, scroll bars, menus, and other common elements. Furthermore, functionality, such as copying and pasting data using the systems clipboard or by using the drag-and-drop utility, is present in most windowed applica- tions. To incorporate such functionality into every program you write can become tedious. Object-oriented programming enables you to reuse such commonly used functionality across programs. Figure 5-1: A windowed application. The Working of a Windowed Application Although there are considerable differences among windowed operating systems, the general structure of programs in such environments is similar. When a windowed application starts to run, it launches into a main routine. This main routine denes the programs overall algorithm. Generally, the main routine performs the following steps: 1. First, it initializes the application, reserving memory and performing other such initializa- tion tasks. 2. After that, it species the general application settings. 3. It then creates any major objects needed by the application such as the main application window. 4. In the next step, it waits for the events to happen. This essentially consists of a routine that goes round and round in a loop, waiting to receive a message that something has occurred that requires some action on the part of the application. 5. In the last step, it terminates the program on exit. Any memory used by the program would then be released. LESSON 5 Object-Oriented Programming and Design Using Java (Third Edition) 100 Event-Driven Programming A program that runs in a windowed environment is not much different from a command-line program, which runs sequentially, does a few tasks, and then exits. In fact, that is pretty much the case with windowed applications. Most of the difference lies in the event loop, which is where the lions share of the work is done. The event loop consists of an algorithm such as the following: 1 do the following { 2 get the event 3 determine what kind of event occurred 4 if event a, then handle event a 5 if event b, then handle event b 6 ... 7 and so forth... } Events (such as a user clicking a mouse button, moving the mouse, pressing a key, moving a window, and so forth) are monitored by the operating system. The operating system sends messages that correspond to each event. Messages contain information such as the object (window, button, and so forth) in which the event occurred, the type of event (such as a mouse click or key press), and any related information (such as the screen coordinates of where the mouse was clicked, which key was pressed, and so forth). These messages are handled in the event loop. The event loop is essentially an endless loop. There is apparently no way to exit the application. In fact, the way that an event loop ends is through an event. Events such as a user closing the application window, choosing FileExit, and so forth would be handled by a routine that exits the event loop and terminates the program. How to Explore the Structure and Working of a Windowed Application Procedure Reference: Explore the Structure and Working of a Windowed Appli- cation To explore the structure and working of a windowed application: 1. Run the application. 2. Choose the various menu options to see the working. 3. Click the Close button to close the application. LESSON 5 Lesson 5: Determining the Use of Object-Oriented Programming in Windowed Applications 101 ACTIVITY 5-1 Exploring the Structure and Working of a Windowed Application Scenario: Your organization has developed a new application for its internal use. You have been asked to test the functionality of the application and furnish reports. What You Do How You Do It 1. Open the run.bat application. a. Choose StartAll Programs AccessoriesWindows Explorer to open Windows Explorer. b. Navigate to the C:\085969Data\ OOP in Windowed Applications folder. c. Double-click the run.bat file to run the program. LESSON 5 Object-Oriented Programming and Design Using Java (Third Edition) 102 2. Examine the various features of the Menu Driven Program window. a. Observe that two windows appear and the Command Prompt window appears in the background. b. In the Menu Driven Program window, choose FileNew. c. Observe that a message box pops up say- ing that the New menu item is selected. d. In the Menu Item Selection message box, click OK to close the message box. e. Choose NormalSub MenuSub Menu One. f. In the Menu Item Selection message box, click OK to close the message box. g. Choose RDCheckControls RadioControlsRadioButtonTwo. h. In the Menu Item Selection message box, click OK to close the message box. i. In the Menu Driven Program window, click OK. j. In the Command Prompt window, observe the message which says that the button has been clicked. k. In the Menu Driven Program window, click the Minimize button to minimize the window. LESSON 5 Lesson 5: Determining the Use of Object-Oriented Programming in Windowed Applications 103 3. Examine the various features of the PopUpColorMenu v1.0 window. a. In the small window that appears, click the Maximize button to maximize the window. b. In the PopUpColorMenu v1.0 window, right-click the Uno button and choose Red to change the color of the button to red. c. Right-click the Due button and choose Green to change the color of the button to green. d. Right-click the Tre button and choose Blue to change the color of the button to blue. e. Click the Close button to close the win- dow. f. Close Windows Explorer. TOPIC B Examine the Use of Frameworks in Developing an Application You examined the development of application frameworks as part of the software coding phase. In most cases in real-time programming, programmers use ready-made frameworks to reduce coding time. In this topic, you will examine the use of such frameworks in developing an application. Let us assume that you have decided to buy furniture for your office. You will prefer purchas- ing ready-made furniture from the market to save time, rather than making new furniture. Similarly, programmers around the world use ready-made frameworks for application develop- ment to reduce coding time. Frameworks A framework is a template for the generic features of windowed applications such as windows, menus, buttons, and scroll bars. It can be designed, programmed, and fully tested under a vari- ety of circumstances and for different kinds of applications. It can then be used to quickly develop a new application by hooking the features of the specic application onto the frame- work. LESSON 5 Object-Oriented Programming and Design Using Java (Third Edition) 104 Benets of Application Frameworks Over the years, many application frameworks have been developed. Examples include Microsoft Foundation Classes (MFC), Borlands Object Windows Library (OWL) and Visual Component Library (VCL), the GIMP toolkit (GTK), Motif, and many others. Like any good class structure, one of the greatest benets of frameworks lies in abstraction. They hide the complexities behind common tasks such as what happens when a user clicks a button or a scroll bar. There is really a lot that must happen in simple tasks such as when a user clicks a button. The program must determine what kind of click occurred (left or right mouse button). In addition, it must make a button appear to go down when the user presses the mouse button, and up or forward when the user releases the mouse button. These simple tasks require quite a bit of processing. What if half of the button is hidden under another window? When the user clicks the button, the overlapping window must be sent behind the window that contains the button, and then the button must be made to appear as having been pressed down. There are many other details such as this that are related to a simple button click. A good framework already contains the programming for dealing with such details, permitting the application developer to focus on what should actually happen when the button is clicked. Class Libraries A class library is a collection of reusable classes, which are used in building a set of related software features. For example, a single class library can support multiple functions such as le operations and graphics display. An application framework is a type of class library. ACTIVITY 5-2 Examining the Use of Frameworks in Developing an Application Scenario: You are about to be inducted into a team of programmers who will be creating window based applications. Initially they would like to test your knowledge on the subject. What You Do How You Do It 1. What is a framework? a) A template for creating objects. b) A collection of reusable classes. c) A template for the generic features of windowed applications. d) A template for creating classes. LESSON 5 Lesson 5: Determining the Use of Object-Oriented Programming in Windowed Applications 105 2. True or False? A class library is a collection of reusable objects, which are used in building a set of related software features. True False Lesson5Follow-up In this lesson, you determined the use of object-oriented programming in windowed applica- tions. You also examined the structure of a windowed application. This will enable you to implement object coding for windowed environments with ease. 1. What do you think are the various events that you might come across while coding for windowed environments? Answers will vary but will include the mouse click event, button click event, mouse over event, mouse up event, etc. 2. While developing your own window based application, name a few features that you will implement using frameworks. Answers will vary but will include menus, the close button, etc. LESSON 5 Object-Oriented Programming and Design Using Java (Third Edition) 106 Examining Application Development for the Internet In this lesson, you will examine application development for the Internet. You will: Describe the web communication process. Examine the technologies involved in web communication. Identify web objects. Write an applet in Java. Lesson Time 1 hour(s), 30 minutes LESSON 6 LESSON 6 Lesson 6: Examining Application Development for the Internet 107 Introduction You examined application development for the windowed environment. You may now need to develop an application that can be viewed across different environments. In this lesson, you will examine application development for the Internet. The Internet consists of many applications that each run in more than one environment. Shar- ing of information can take place only when communication among these applications is seamless. Object-oriented programming helps you design web applications that can be inte- grated not only with one another but also with tools that are spread across the Internet. TOPIC A Examine the Web Communication Process You examined how objects and their interactions are modeled. To design an object model for a web application, you need to know the various web objects involved and the methods by which they interact with each other. In this topic, you will describe the processes involved in the communication between web objects. The object-oriented approach to designing a system involves the study of its constituents and the manner in which they interact. As an Internet programmer, a thorough knowledge of the constituent entities and their interactions will help you design a rigid web object model. Web Applications Web applications are applications that run over either the World Wide Web or an intranet. They follow a client-server model, which means that the functionality of an application is provided through computers working in conjunction with one another across a network. They enable you to perform banking transactions, view an up-to-date map of a geographic location, and do the shopping, all from the comfort of your living room. Web Elements Sharing of information on the web entails several elements to interact with one another to accomplish the data transfer process. Refer to the table for a description of each such element. Web Element Description Web browser An application that resides on the users computer. It serves as the user interface for a web applica- tion, enabling users to view web pages and click links to navigate from one page to another. It also enables users to enter data in forms (text boxes, drop-down lists, and so forth), which can be sent back to a web server for processing. Examples include Internet Explorer and Netscape Navigator. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 108 Web Element Description Web server Web servers handle requests for information that are made by web browsers, and return the appro- priate information to the browser. HTTP HyperText Transfer Protocol (HTTP) is a protocol or a communication language that enables web browsers such as Internet Explorer or Netscape Navigator to communicate with web servers. HTML HyperText Markup Language (HTML) is a lan- guage used to design web pages. HTML can be used to create basic web pages consisting of text, graphics, and links as well as advanced, dynamic web pages with animated content and interactive features. Development of the World Wide Web In the late 1980s, when Tim Berners-Lee and others set about creating what became the World Wide Web, several new components needed to be invented. The Internet already existed and contained a large repository of data, but the data on the Internet was not particularly easy to access. To download a le, you needed to have one kind of application (an FTP client). To view images, you needed to have another kind of application (one or more image viewers). Simply viewing text, in fact, required the use of several applications, depending on where the text was located (on an FTP server, news server, email server, and so forth). Most of this data was not particularly easy to nd nor was it linked in any way to related information. Gopher applications were a stepping stone toward the web. Gopher sites were like websites in that they indexed information to provide fast searching, but they neither provided links to related information nor facilitated the integration of text, graphics, and sound. To accomplish this sort of linking and presentation of informa- tion, a new type of application needed to be created. This application, called a browser, would enable information to be presented on the Internet in a way that was not pos- sible before. But browsers only provide half of the picture. If you could consider a web browser application to be like a customer, then a website is like a store where that customer does information shopping. Some kind of software is needed to mind the store, and that piece of software is called a web server. Also, some kind of protocol or language is required to enable communication between the server and the browser, and the HTTP and HTML languages lled that gap. Static and Dynamic Web Pages A static web page is the simplest type of web page. Every time you visit it, its content remains the same. Dynamic or active web pages are those whose content is generated on the y by the server before the page is sent to a browser. The Web Communication Process Both HTML and HTTP work together to enable communication between a web server and a web browser. The communication takes place in the following stages: 1. Users initiate a connection to a website either by clicking a web page link or by entering a URL on the browsers address bar. LESSON 6 Lesson 6: Examining Application Development for the Internet 109 2. The browser transmits the URL over the Internet to the destination web server using HTTP. 3. The web server examines the URL sent by the web browser, and then searches for the page or le that was requested. 4. When the server nds the requested item, it sends the item back to the browser that made the request. 5. The browser displays the requested les as it receives them. Figure 6-1: The web communication process. ACTIVITY 6-1 Programming Web Applications Scenario: As part of its expansion plan, Our Global Company has decided to develop a web application that will ease the communication process between its employees across the globe. 1. If the application had to deal with the transmission of web pages over the Internet, which protocol will it use? a) HTML b) FTP c) HTTP d) URL The Web Communication Process LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 110 2. True or False? Static web pages are those whose content is generated on the fly by the server before the page is sent to a browser. True False TOPIC B Examine the Technologies Involved in Web Communication You examined the communication process between web elements. However, there are certain technologies that actually aid the communication process. In this topic, you will examine the technologies involved in web communication. Information sharing over the Internet becomes a cause of concern when two computers work- ing with different technologies need to communicate. Therefore, it becomes mandatory for you to identify the various technologies used to establish an interface between web elements to facilitate communication. Server-Side Objects and Technologies There are many different types of objects and technologies that help generate active content on web servers. Refer to the table for a description of what you can use to generate active content on the web server. LESSON 6 Lesson 6: Examining Application Development for the Internet 111 Server-Side Technology Description Scripts Scripts are typically text les that contain instruc- tions in a scripting language, such as Perl, JavaScript, VBScript, PHP, and others. Many scripting languages are object-oriented. Typically, some sort of interpreter must be installed on the server, to enable the scripts to run. Some interpreters are a separate application from the web server itself. Some web servers include a script interpreter as an integrated feature of the server, or as an add-on module. When scripts run, they perform various tasks on the server. Typically, they produce a result of some sortmost often generating a web page that is returned to the web client that made the request. Because scripts are easy to modify and can per- form powerful operations on the server (such as modifying the contents of a database, deleting les, replacing les, and so forth), they are kept in a special location on the server that cannot be modied without administrative access rights. This prevents hackers from modifying scripts or adding their own scripts that might damage the website. To be able to respond to requests from web clients, script interpreters running on a web server must use certain protocols. Typically, the protocol used for this purpose is the Common Gateway Interface (or CGI). Through CGI, scripts are able to read the data coming from a Get or Post request. Executables Executables are compiled programs that run directly on the computer. Like script interpreters, executables must be designed to use CGI if they are to function as a web application. CGI executables can be written in object-oriented pro- gramming languages, such as C++ or Delphi, and they can also be written in other programming lan- guages, such as C or BASIC. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 112 Server-Side Technology Description Java Java applications (or servlets as they are some- times called when they are running on a server) share some of the attributes of executables and of scripts. Unlike executables, Java applications do not run directly on the computer. Instead, they run in a special environment called a virtual machine. A virtual machine is somewhat like a script inter- preter in that it provides an engine that runs the program. Unlike scripts, however, Java applets are compiledalbeit in a special format that can only run on the virtual machine. There are several ben- ets to this. Unlike executables, Java applications can run (with some limitations) on any type of computer for which there is a Java virtual machine. Because they are already compiled, Java applications can be run more quickly than scripts. Active Server Pages and Server-Side Includes It can be tedious to write programs that must gen- erate entire web pages. In many cases, dynamic content actually comprises only a small part of the actual page. One way around this is to include placeholders for dynamic content within an otherwise static web page. When web pages are requested by clients, the server rst makes a copy (in memory) of the web page, and then scans it to nd any sections of the web page that contain the special placeholders (which are called server-side scripts and server- side includes) that need to be processed before the web page is delivered to the client. The placeholders are processed and replaced with con- tent that was generated on the y. The web page with its newly modied content is then sent to the client. This approach has the advantage of enabling web page designers to lay out and design web pages as though they con- tained static content, while enabling them to write scripts and programming code only where it is needed to generate dynamic content. Various tech- nologies such as Server-Side Includes and Active Server Pages use this approach. LESSON 6 Lesson 6: Examining Application Development for the Internet 113 Server-Side Technology Description Server extensions Many web servers provide ways to enhance the functionality of the server through the use of add-on modules, written in a compiled language (such as C++ or Delphi). Microsofts Internet Information Server (IIS), for example, can be extended through its ISAPI inter- face, which essentially consists of writing software modules (dynamic-link libraries, or DLLs) that communicate directly with the web server. Netscape servers use an interface called NSAPI. Apache has its own proprietary module format as well. Because these add-ons consist of compiled code (optimized to run fast on a particular kind of com- puter) that interfaces directly to the web server, they are very fast and useful where high perfor- mance extensions are needed. Server modules can be used to provide customized extensions to a web server for specic purposes, and they can also be used to add high-performance scripting capabilities to a server. Extensible Markup Language The Extensible Markup Language (XML) provides an object-oriented way for developers to dene data structures. Through a hierarchical system of tags and descriptive elds of information, develop- ers can embed all sorts of information about data (metadata) within the data. XMLs object-oriented structure as well as univer- sal format (XML les can easily be shared by different platformsUNIX, Macintosh, Windows, and so forth) lends itself to web development, where data might be distributed among various locations over a network. In some cases, it is even possible to embed Java applets or other types of software functionality within an XML le. Unlike HTML (which is itself a markup language), XML is structured and tagged according to the information it contains, not according to appear- ance. A style sheet can be used to dene how XML data should be displayed. Client-Side Objects and Technologies As a web programmer, you might also encounter client-side objects and technologies. Refer to the table for a description of each such client-side technology. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 114 Client-Side Technology Description Scripts Many of the scripting languages available on the server side are also available on the client side. In general, there are more choices on the server side because its not so much an issue whether or not the server already supports a particular script- ing language. Still, its easy enough to add one by installing a scripting engine (interpreter) on the server. On the client side, however, its more of an issue because many users do not want to install a script- ing engine just because they can use a web application. For this reason, the most popular scripting languages on the client side are those that are included within web browsers. In the case of Internet Explorer, that means JScript (Microsofts avor of JavaScript) or VBScript (a scripting lan- guage based on Microsofts Visual Basic). For Netscape, HotJava, Opera, and various other brands of web browsers, your choice is pretty much just ECMAScript, which is commonly called JavaScript. Because JavaScript (or some dialect of it) is supported on most popular browsers, JavaScript is the language of choice for client-side scripting. Scripts are embedded within the HTML of a web page through the use of Script tags. After the web page is downloaded from the server, browser soft- ware runs the scripts contained within it. Java It is a technology used for client-side program- ming. Special software applications (called applets) can be written in Java and compiled using a Java compiler. These applets are embedded within a web page (much like pictures can be embedded within a web page), providing program functionality that is much more exible than the limited functionality provided through JavaScript and HTML, or through HTML alone. LESSON 6 Lesson 6: Examining Application Development for the Internet 115 Client-Side Technology Description ActiveX A Microsoft technology supported directly by Microsofts web browsers, and on other types of browsers using Microsoft add-ons. ActiveX pro- vides functionality similar to Java applets, enabling applications to be embedded within a web page. ActiveX, in some regards, might be considered more powerful than Java because it runs in native compiled code. This might really be considered a drawback because, unlike Java, it requires that separate ActiveX objects be provided for each type of client computer that will be used. For this reason, Java applets tend to be more popu- lar than ActiveX objects, except in situations (such as intranets) where it is known that users will only have a specic type of browser and operating sys- tem. ShockWave, Flash, and other plug-ins The most popular web browsers support a special type of add-on software module known as a plug- in. Like server extensions, these modules are tightly integrated with web browsers to the extent that they function like part of the browser itself. Unfortunately, some plug-ins have not been well implemented, have been difficult to install, and generally have caused more problems for users than they have provided benets. This has given the plug-in concept a bad reputation in general. However, well developed plug-ins install automati- cally off the web as needed, with little user intervention, and provide amazingly extended capabilities to web browsers (such as the ability to present 3D graphics, synthesized sound, and so forth). Some plug-ins have become so widely accepted that software manufacturers include them as an automatic part of the installation process for their web browsers and operating systems. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 116 Client-Side Technology Description Internet-enabled executables A web browser is essentially just a desktop appli- cation that can communicate across the web, using HTTP and other web communication protocols. Besides browsers, there are other applications that can also communicate across the web using web communication protocols. For example, streaming music players such as Real Audio and Windows Media Player run as desktop applications, yet they download music from the web. Web-based features have slowly begun to appear in other kinds of applications, such as word processors and spreadsheet programs. Some programs automatically check for updates and bug xes from the web as a background task each time the program runs. Other programs keep information up to date by periodically download- ing updates from the web. Over time, as more applications are designed to run in web browsers, and more desktop applications incorporate web- browser-like features, the distinction between desktop applications and web applications will blur. AJAX (Asynchronous JavaScript and XML) A technique to create interactive web applications. On a dynamic web page, if a certain content changes, the entire web page will reload. But AJAX allows you to reload only those components that have changed and not the entire web page. In web applications that are developed using AJAX, data is retrieved from the server asynchro- nously or without interfering with the operation of the web page. Web Communication in Dynamic Pages A web page might contain embedded active content that runs on the client computer instead of on the server. In this case, information transfer between the browser and the web server takes place in the following stages. 1. First, the web page is downloaded to the client computer, and the web browser looks for the embedded program, such as an applet or a script, on the page. 2. The browser locates the embedded program and reserves space on the web page to dis- play it. 3. The browser then makes another request to the server to download the needed le. 4. And nally, when the le is received, the browser runs the program contained within the le. Web Communication in Dynamic Pages LESSON 6 Lesson 6: Examining Application Development for the Internet 117 Figure 6-2: A typical exchange of information in a web application. Examining Server-Side Applications A script might be contained either within the web page itself, or within a separate le on the server. The web page shown below contains a form with a eld and a button. When the user enters a value in the Zip Code eld and clicks the Get Weather Report button, the web browser sends a request to the server, which includes the information that the user entered in the form. The browser requests that the server run a specic program named getWeather.exe. When the server receives the request, it runs getWeather.exe using the data that was sent to it (in this case, the area code for which a weather report is desired). The getWeather.exe program, now running on the server, looks up the requested weather report information, and then generates an HTML web page that displays the results. It then transmits the web page back to the requesting web client, which then displays it. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 118 Figure 6-3: A web form. ACTIVITY 6-2 Developing an E-Learning Application Scenario: E-school has come up with a massive plan to launch a worldwide education program. An e-learning application that will facilitate student access from across the globe needs to be developed. 1. Which of these is a client side scripting technology? a) ActiveX b) Java Servlet c) Java Script d) Active Server Pages 2. True or False? AJAX is a technique to create static web pages. True False LESSON 6 Lesson 6: Examining Application Development for the Internet 119 TOPIC C Identify Web Objects You identied the fundamental software objects and processes involved in the communication between a web server and a client. You may now need to administer additional functionality that aids in displaying web pages, establishing server connectivity, and providing distributed processing capabilities. In this topic, you will identify the various objects and classes that enable web developers to write software that processes data on the server and the client com- puter, and to display information on the client computer. Object-oriented programming is perhaps nowhere as prevalent as it is in the world of web development. As a programmer, you will develop a number of objects for the web. It is of prime importance that any new object that you create is compatible and is able to communi- cate with existing objects. This can be accomplished by identifying the existing objects of the system and studying their behavior. The Browser Document Object Model Programmers who write software to be displayed on a web browser need to have some way to communicate with the browser in order to access the information on a web page. Web pages are abstracted through a hierarchy of objects known as a Document Object Model, or DOM. Developers of web client software can read and set the properties of objects in a browsers DOM to determine or specify what is displayed within a web page. The Process of Displaying a Web Page The web communication process involves a series of objects, which continually interact with each other to transfer information. The following steps are involved when you open an HTML document in a browser: 1. The browser rst downloads the le from its storage location on the server to a local stor- age location called a cache. 2. The browser then reads the le from the cache into memory, and based on the HTML instructions that it contains, creates a model in memory on how the page will look. 3. Next, based on the pages links to additional objects, such as images and applets that are embedded in the page, the browser downloads these objects into the cache as well. 4. Based on the properties of the document object that contains the document model, the browser begins to construct the displayed page. It notes any special content embedded in the page that might affect how the page appears or behaves, such as formatting tags, the size of images, scripts to be run, and applets or plug-ins to be loaded. 5. After the initial scripts have run, the browser begins to display the pages contents. Text is displayed with placeholders for applets, plug-ins, and images. This gives the user some- thing to begin reading while the rest of the page downloads. Images are displayed as they load, in the locations reserved for them. For applets and plug-ins, the browser calls upon the computers operating system to load the applet environment or a plug-in module. The Process of Displaying a Web Page LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 120 Figure 6-4: The document object is involved in the process of constructing and dis- playing a web page. A Sample HTML/JavaScript Page Because the document object provides access to many different properties of a web page, it gives programmers the capability to make web pages dynamic and interactive. For example, the web page given below contains a text box and a button. The page allows you to enter only a nonzero value in the text box. Figure 6-5: A simple form example. The HTML/Javascript code given below is the source code for the above page. LESSON 6 Lesson 6: Examining Application Development for the Internet 121 1 <html> 2 <head> 3 <title>Form Entry</title> 4 </head> 5 <body> 6 7 <form name="myForm" method="post" action= "/cgi-bin/magicnum.exe"> 8 Enter anything but zero: 9 <input type="text" name="magicNumber"> 10 <input type="Button" name="OK" onclick="verify()" value= "OK"> 11 </form> 12 13 <script language="JavaScript"> 14 function verify() { 15 if (document.myForm.magicNumber.value == 0) { 16 alert("I can't process the magic number if it's zero. Sorry."); 17 } else { 18 document.myForm.submit(); 19 } 20 } 21 </script> 22 23 </body> 24 </html> Lines 1 through 5 contain HTML tags that begin a web page, such as <html>, <head>, <title> and so forth. The information contained within each of these tag sets (such as the text contained between <title> and </title>) is stored within objects that are part of the document object model. In this example, Javascript is used to access the objects. For example, you can use the JavaScript expression document.title to refer to the title (Form Entry in this example) of the web page. Lines 7 through 11 contain HTML code that creates a form. The web browser trans- lates this code and creates a form object named myForm. You need to use the expression document.myForm to refer to the form object, because the form object is created as a child object of the document object. In addition, the form object con- tains two child objects of its own. One is a text box named magicNumber, and the other is a button named OK. For example, to refer to the text box object, you can use the expression document.myForm.magicNumber. The browser also sets proper- ties of the objects it creates. The OK button has an interesting property, onclick. Notice that the onclick property is set to the verify() function, which will run when the user clicks the OK button. Lines 13 through 21 contain some JavaScript code. It is separated from HTML code using opening and closing <script> tags. The verify() function is dened within the <script> tags. The verify() function contains a conditional statement that checks whether or not the magicNumber text box contains a zero value. If the text box contains a zero, then a message box is displayed, informing the user that the number cant be processed. As this example illustrates, the browser DOM provides you with a way to access the objects that dene an HTML page, enabling you to build web appli- cations that build upon and extend the functionality of web pages. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 122 CGI Executables A CGI executable is an executable le that is run by an HTTP server. This le has a .cgi extension and is placed in a separate folder named cgi-bin on the web server. It is executed in phases, and the resultant output is stored in a buffer. Once the entire le is executed, it is sent to the client system in a form that is easily recognized by the browser. Shortcomings of CGI Applications CGI applications typically run as standalone executables or use scripts that run within an interpreter of some sort. Because of the communication involved when such pro- grams run separately from the server program, they tend to be somewhat slower than functions provided directly as part of the server itself. Furthermore, in some congura- tions, CGI applications must be loaded from the hard disk to memory and initialized before they can run. This takes time. Such applications are benecial because they enable developers to customize the functionality provided by a web server, but such customization comes at the cost of performance because the applications are not inte- grated tightly with the server. Server Extensions A server extension is an application, which contains software code that is loaded with the server application. It remains resident in memory so that it can be used as needed. A server extension acts as an interface between the server and any third-party tool, thus increasing the performance of the server. Server Extension Technologies Many web server applications address the shortcomings of CGI executables by using server extensions as a means of extending server functionality through code that essen- tially becomes part of the web server itself. Examples of server extensions include Microsoft ISAPI and NetScape NSAPI modules. Apache also has its own format for server extensions. These modules are provided through DLLs, or dynamic link libraries (or the equivalent on other operating system platforms). Using object-oriented programming, developing a server extension with a development tool such as C++ Builder is not much different from programming a CGI application. For example, Borlands TWebModule object abstracts the details well enough that you could develop a web server application that will run on three different platforms (ISAPI, NSAPI, and CGI) by only making slight modications for each platform. Java Java is an object-oriented programming language that does not access computer hardware directly. This enables programmers to develop applications that are not specic to a computer. Java is compiled in byte code, which is similar to a normal executable program, except that it is written in a language that a virtual machine can understand. This feature provides a consis- tent platform for running Java programs. LESSON 6 Lesson 6: Examining Application Development for the Internet 123 The Java Runtime Environment The Java Runtime Environment is a program that enables a Java program to run on a particu- lar type of computer. Because the JRE creates a virtual machine which abstracts differences among several computer systems, Java programs can run on a wide variety of computers. A drawback to this abstraction is that Java cannot perform some of the low-level tasks that C or C++ can. Java Classes and Objects A large collection of Java classes is available to support various types of software functional- ity. Refer to the table for a description of each of the Java classes. Class Description java.applet Provides support for implementing Java applets. java.awt Includes classes that perform graphics and text operations, and displays windows and other ele- ments of a windowed user interface. java.awt.image Provides classes to enable image processing. java.io Supports input and output operations. java.lang Provides the core Java language. java.math Provides comprehensive math capabilities. java.net Supports network operations, such as opening web pages. java.util Provides various useful data types and routines, such as compression and decompression. Java CLASSPATH Java classes are typically installed along with the Java Runtime Environment. The sys- tem is informed of their whereabouts through a system setting known as the CLASSPATH. When a Java program runs, it searches for code contained in any needed classes by looking in the directory that contains the Java program, and in the directo- ries specied in CLASSPATH until it nds the needed classes. Within a Java program, a programmer simply identies which classes are used with an import statement. For example, import java.io indicates that the Java program needs to use classes in the java.io library. Classes within the library can then be used to create objects as needed. The Java Development Kit The Java Development Kit (JDK) is a development kit that is used to compile and run Java programs from environments such as Windows 98s MS-DOS prompt or Windows 2000s com- mand prompt. Some of the important components of the JDK include the Java interpreter, the Java compiler, the Java debugger, and the Java Runtime Environment (JRE). It does not pro- vide a code editor; however, a text editor such as Windows Notepad will work ne. Since the compiler reports errors by the number of the line in which they occur, it is convenient to have a text editor that provides line numbering. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 124 ACTIVITY 6-3 Developing a Web Browser Application Scenario: Surfers International has approached you for developing a browser application using the Java technology. Prior to coding, you decide to make a list of classes that might come in handy dur- ing the coding phase. 1. Identify the class that provides support to network operations. a) java.awt b) java.io c) java.net d) java.util 2. True or False? The java.awt class provides support to both graphics and text. True False TOPIC D Create a Web-based Application Using Java You examined various programs that run on the Internet. However, the most common of these programs is the Java applet, which is compatible with all browsers. In this topic, you will write an applet in Java. Just as a linguist can communicate with ease with people speaking different languages, Java applets can interact with different types of applications available on the Internet. For the same reason, programmers prefer to use the Java applet because it saves them the trouble of writing different programs for different environments. LESSON 6 Lesson 6: Examining Application Development for the Internet 125 Applets Denition: An applet is a Java program that you can embed in an HTML page just as you can embed an image in a web page. Java applets are run on the Java virtual machine. When you view a page that contains an applet, the applet is executed by the browsers Java Virtual Machine (JVM). Applets differ from other Java programs, since they can- not run as a separate entity. They must be run in a container such as an HTML page. Example: A Sample Java Applet Program Below is a sample Java applet program: import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } This program is designed to be used within a web page, as an applet, so it uses the java.applet.Applet class. Because it needs to be able to create graphical output, it also uses the java.awt.Graphics class. The HelloWorld class is designed to extend the capa- bility of a generic applet, so it has been made a subclass of the Applet class. This is why the class is declared as HelloWorld extends Applet. HelloWorlds paint method takes one object, a graphics object called g. The g object is used to draw a simple message, a text string that says Hello world! The message begins at a location 50 pixels from the left edge of the applet, and 25 pixels down from the top of the applet. This program is saved in a text le named HelloWorld.java. The le name should be the same as the main class of the program. When this program is compiled, a byte- code le named HelloWorld.class is created. This le contains the compiled Java program, which can be embedded within a web page. The code given below is used to embed the applet in an HTML le. The applet will appear in the specied location using dimensions specied in the APPLET tag. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 126 <HTML> <BODY> Here is the output of my program: <APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25> </APPLET> </BODY> </HTML> Life Cycle of an Applet An applet is created based on the four methods of the Applet class. They are described in the following table. Method Description init It is the rst method to be called. It is used to ini- tialize the applet. start It is called immediately after the init method. It is used to start the execution of the applet. stop It is called whenever the user navigates away from the page containing applets. It is used to stop the execution of the applet. destroy It is called when the browser application is closed. It is used to release all the resources which are used by the applet. The paint Method The paint method is used to draw the applet on a web page. The onscreen appear- ance of the applet is determined in the paint method. You can draw various shapes such as rectangles and squares around the applets display area. How to Create a Web-based Application Using Java Procedure Reference: Create a Java Applet and Embed It in a Web Page To create a Java applet and embed it in a web page: 1. Create the Java applet le and save it with a .java extension. 2. Compile the Java applet le. A new class le will be created if code is compiled correctly. 3. In the HTML le in which you would like to embed the applet, add the required tags at the desired location. 4. Save the HTML le. 5. Open the le in the browser to view the changes. 6. If necessary, modify the source Java applet and reload the web page to view the results of your modication. LESSON 6 Lesson 6: Examining Application Development for the Internet 127 The JDK Download URL At the time this course was written, the JDK was available for download from http:// java.sun.com/j2se. The JDK Environment Setup There are many free and inexpensive tools available to provide users with an opportu- nity to work on object-oriented programming. For example, there are many free compilers and interpreters available for download on the World Wide Web. One of the most popular free compilers is Suns Java Development Kit (JDK). After you install JDK, youll need to congure the system so that Java can nd the class les. You can do this by setting the CLASSPATH environment variable to include the directories that contain the Java classes. This is done differently on differ- ent systems, and Java SDK documentation includes instructions on how to do this for different systems. Once you have installed the JDK and set the CLASSPATH setting, you are ready to compile a program. To compile a program, you run the Java compiler from a com- mand line, using a command such as c:\jdk1.2.2\bin\javac.exe c:\myNewProgram.java where c:\jdk1.2.2\bin\javac.exe is the complete le name of the Java com- piler and c:\myNewProgram.java is the complete le name of the Java program that you want to compile. (If javac.exe is in a directory that is included in your sys- tems PATH environment variable, then you do not need to enter the complete path. Likewise, if your current directory is the directory that contains your Java program, then you do not need to include the complete path.) On Windows, you might nd it convenient to create an MS-DOS batch le that runs the compiler when you drag a .java le onto the batch les icon, as in the following batch le named compilejava.bat: @echo off cls echo COMPILING: %1 C:\jdk1.2.2\bin\javac.exe -verbose -deprecation %1 pause This batch le clears the screen, puts up a compiling message, and then runs the Java compiler using two of its command-line settings. (The Verbose requests that the com- piler provide detailed feedback, and deprecation requests that the compiler inform you when you are using methods that are from older versions of Java and are about to become obsolete.) The pause command halts the execution of the batch le until you press a key to continue. Without this command, the compiler would nish running, and the console window would close itself immediately. This enables you to see the feed- back from the compiler, such as error messages. In batch les, the %1 parameter says to include the name of the le that was typed at the end of the command to run the batch le, or in this case, the le that is dragged onto the batch les icon. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 128 ACTIVITY 6-4 Create a Java Applet and Embed It in a Web Page Setup: Restore the Notepad++ application. Scenario: The Everything for Coffee website is an HTML web page and does not contain any other Java content. You would like to embed the following in the web page: an image of a speaker and a button each for playing or stopping music. What You Do How You Do It 1. Create an applet for the speaker image. a. In the Notepad++ application, in the blank file, in line 1, type import java.applet.*; to import the java applet package. b. Press Enter and type import java.awt.*; to import the java awt package. c. Press Enter and type public class ImageApplet extends Applet{ Image img; MediaTracker tr; public void paint(Graphics g) { tr = new MediaTracker(this); img = getImage( getCodeBase(), "speakertrans.gif"); tr.addImage(img,0); g.drawImage(img, 0, 0, this); } } to create an applet that draws an image using the speakertrans.gif image. d. Click the Save button. e. Navigate to the C:\085969Data\Internet Applications folder. f. Save the file as ImageApplet.java and close it. LESSON 6 Lesson 6: Examining Application Development for the Internet 129 2. Create an applet for the play and stop buttons. a. In the blank file, type import java.applet.*; import java.awt.*; import java.awt.event.*; to import the applet, awt, and awt event pack- ages. b. Press Enter and type public class ButtonsApplet extends Applet implements ActionListener{ to create an applet for creating the buttons. c. Press Enter and then press the Spacebar twice. d. Type Button play,stop; to create a reference for the play and stop buttons. e. Press Enter and type AudioClip audioClip; to create a ref- erence for the audio clip. f. Press Enter. g. Type public void init(){ play = new Button("Play"); add(play); play.addActionListener(this); stop = new Button("Stop"); add(stop); stop.addActionListener(this); audioClip = getAudioClip( getCodeBase(), "Coffee.wav"); } to create the init method that will create the play and stop buttons. h. Press Enter. i. Type public void actionPerformed(ActionEvent ae){ Button source = (Button) ae.getSource(); if (source.getLabel() == "Play"){ audioClip.play(); } else if(source.getLabel() == "Stop"){ audioClip.stop(); LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 130 } } to create the actionPerformed method that will perform the play or stop action depending on which button is clicked. j. Press Enter, press Backspace twice and type } to add the closing braces for the ButtonsApplet class. k. Click the Save button. l. Navigate to the C:\085969Data\Internet Applications folder. m. Save the file as ButtonsApplet.java and close it. n. Minimize the Notepad++ application. 3. Compile the applet programs. a. Switch to the Command Prompt window and clear the screen. b. Type cd C:\085969Data\ Internet Applications and press Enter. c. Type javac ImageApplet.java and press Enter to compile the program. d. Type javac ButtonsApplet.java and press Enter to compile the program. e. Close the Command Prompt window. LESSON 6 Lesson 6: Examining Application Development for the Internet 131 4. Embed the applets in the HTML page. a. Switch to the Notepad++ application. b. From the C:\085969Data\Internet Applications folder, open the Everything For Coffee.htm file in the Notepad++ application. c. In line 180, click and type <center><applet code= "ImageApplet" height=80 width=80> </applet><br> <applet code="ButtonsApplet" height=100 width=300> </applet></center> to embed the ImageApplet and the ButtonsApplet in the HTML page. d. Save the file. 5. Verify the change. a. Choose Runlaunch in IE to launch the file in Internet Explorer. b. Observe that a button image and two but- tons are embedded in the web page. c. Click the Play button to play the audio that conveys information about the com- pany. d. Click Stop to stop playing the audio. e. Close Internet Explorer and the Notepad++ application. Lesson6Follow-up In this lesson, you examined the steps involved in the communication process between two web objects. You also examined the various client-server technologies involved in this process. You will now be able to model a web application using these objects and subsequently make a selection of the right kind of technology for your development needs. 1. What do you think are the various objects and their properties that you would like to define while developing a web application? Answers will vary. 2. What are the benefits of using object-oriented development tools to create server-side applications? Answers will vary. LESSON 6 Object-Oriented Programming and Design Using Java (Third Edition) 132 Follow-up In this course, you examined the principles of object-oriented programming. You will now be able to identify the problem areas in your program where you can deploy the object model as a solution. In addition, you will be able to adopt a structured approach to software develop- ment. 1. What are the factors that you may want to consider before choosing the right technol- ogy for your object-oriented programming needs? Answers will vary. 2. How do you think object-oriented programming can help raise the programming stan- dards in your organization? Answers will vary. 3. What aspects of object-oriented programming do you feel will make your job easy as a programmer? Answers will vary. Whats Next? This is the only course that deals with the principles of object-oriented programming and design. FOLLOW-UP 133 Object-Oriented Programming and Design Using Java (Third Edition) 134 NOTES Due to classroom setup constraints, some labs cannot be keyed in sequence immediately fol- lowing their associated lesson. Your instructor will tell you whether your labs can be practiced immediately following the lesson or whether they require separate setup from the main lesson content. Lesson-level lab setup information is listed in the front of this manual in the course setup section. LESSON 1 LAB 1 Dening Project Requirements and Milestones Scenario: As a business analyst, you have been assigned the task of preparing the requirements and schedule for a major project secured by your company to digitize government records of the last four decades. Before you start preparing the requirements and planning the schedule, you would like to test your knowledge on the various phases of software development. 1. Identify the requirements defined as part of the software requirements specifications phase. a) Software interface requirements b) User interface requirements c) Stakeholders of the project d) Business rules 2. True or False? Implementation of features occurs before the development of an appli- cation framework. True False 3. True or False? Business rules are defined as part of the planning phase. True False LESSON LABS LESSON LABS Lesson Labs 135 4. True or False? Changes to the class structure can happen after software ships. True False 5. Identify the phases in the design of class structures. a) Performing iterative analysis and design b) Sketching class structures c) Updating class structures d) Implementing class structures LESSON 2 LAB 1 Automating Processes for OGC Auctions Scenario: An online auction company, OGC Auctions, Inc., has contracted your company to automate their auction process. Being a high-priority project, all programmers are to be tested on their knowledge of software design methodologies and tools before being assigned to the project. 1. Identify the constituents of a software methodology definition. a) Heuristics b) Process c) Business rules d) Notations 2. True or False? A language of graphic symbols or text markup for representing software systems and subsystems is called heuristics. True False 3. True or False? A set of rules to promote a methodical software design is called nota- tions. True False 4. Use casediagrams represent software from a users perspective. LESSON LABS Object-Oriented Programming and Design Using Java (Third Edition) 136 5. True or False? Sequence diagrams represent messaging within a system. True False 6. Packagediagrams show how software will be broken up into modules and how various modules depend on one another to work. LESSON 3 LAB 1 Calculating Employee Work Hours Objective Examine a problem set using the object-oriented approach. Scenario: OGC Bank plans to automate the attendance entry of its employees. Apart from marking the attendance, the process will also calculate the total number of work hours for each employee for the month. At the start and end of the day, the employees of the bank will be expected to submit their entry to record their attendance. As a business process analyst, you are expected to conduct a study on the system. 1. For the given module, identify the information you will require. a) Distance between the bank and an employees residence b) Mode of conveyance of the employees c) Employee names d) Customer names 2. Assume that you have a procedure to calculate the total number of hours worked by an employee for the day. On what data does this procedure work? a) Employee entry time b) Employee exit time c) Employee meeting time d) Employee break time 3. Assume that the code for this procedural module has already been developed as part of a previous assignment. If you are able to use this existing code, which feature of object-oriented programming will be put to use? a) Flexibility b) Extensibility c) Scalability d) Reusability LESSON LABS Lesson Labs 137 4. If you were to use a true object-oriented programming language to develop this mod- ule, which one will you use? a) C b) C++ c) BASIC d) COBOL 5. True or False? A compiler is a program that translates source code into an executable file. True False 6. Why would you recommend the use of the object-oriented model for coding the pro- cess? a) Reduced development time. b) Previously developed code, if any, can be reused to avoid rework. c) Quality of the application can be checked for individual modules. d) Tools for object-oriented languages are easily available on the local market. 7. True or False? The final executable file created upon compilation on one computer can be readily deployed on all the other computers without the need for another compila- tion. True False LESSON 4 LAB 1 Automating the Library Management System Scenario: Your organization, Our Global Company, has secured a major project for automating the pro- cesses of the State Library of Chermont City. You have been assigned the task of performing a ground study on the requirements and modeling the system using object-oriented programming features. Before you start studying the requirements of the system, you would like to test your knowledge on identifying the various object-oriented programming concepts. LESSON LABS Object-Oriented Programming and Design Using Java (Third Edition) 138 1. The book return function has been divided into two subfunctions, one of which deals with ontime returns, and the other with late returns. Which feature of object-oriented programming will you deploy in this situation? a) Encapsulation b) Information Hiding c) Modularity d) Abstraction 2. If you were to use the same function to handle both ontime as well as late returns, which object-oriented feature will help you do this? a) Polymorphism b) Inheritance c) Encapsulation d) Abstraction 3. True or False? The Books section consists of a variety of subjects such as science, lit- erature, and arts. You create two objects, Books and ScienceBooks. The classification scheme for the objects would be to represent the science book as a type of book. True False 4. Which feature of the object-oriented model would help you bundle customer informa- tion and customer procedures into one unit? a) Abstraction b) Encapsulation c) Information Hiding d) Inheritance 5. True or False? The object-oriented feature that helps you represent just the important features of a book object is called abstraction. True False LESSON LABS Lesson Labs 139 LESSON 5 LAB 1 Developing Applications for Our Global Company, Inc. Objective Develop applications for a windowed environment. Scenario: Our Global Company wants to increase prots by cutting costs wherever possible. Employee travel allowance is one area that has been targeted for cost cutting. The system needs to be automated so that it is easy to analyze employee travel patterns. As a programmer, you will have to ensure that the software works ne in a windowed environment. 1. True or False? Command-line applications are slower than WIMP applications because they execute one instruction at a time. True False 2. Which technology will you use to embed data from one application into another? a) VisiCalc b) Lotus 1-2-3 c) ActiveX d) WIMP 3. True or False? Embedded object technologies take advantage of the concept of encap- sulation for their working. True False 4. True or False? Batch mode programs use the ActiveX technology for their processing. True False 5. True or False? Windowed applications use event-driven programming. True False LESSON LABS Object-Oriented Programming and Design Using Java (Third Edition) 140 LESSON 6 LAB 1 Developing a Web Application Objective Develop applications for the Internet. Scenario: An organization has contracted you to develop a web application that will display the list of medical facilities in an area when its zip code is typed. The application should also include the functionality for transferring scanned reports between any two locations. You also need to pro- vide for three-dimensional images to be viewed over the network. 1. You initially decide to create a simple version of the application using HTML. What does HTML stand for? a) Hyper Test Markup Language b) Hypertext Makeup Language c) High Test Markup Language d) HyperText Markup Language 2. Which protocol will you deploy to facilitate the transfer of scanned file reports between any two locations? a) FTP b) HTTP c) PPP d) TCP/IP 3. True or False? HTTP helps transfer web pages over the Internet. True False 4. True or False? For viewing images, you can use a plug-in such as Shockwave. True False 5. True or False? You have decided to embed the zip code finder application within the web page by using one of the Internet technologies. Java applets are a better choice over ActiveX controls because they spare you the trouble of providing interfaces for various environments. True False LESSON LABS Lesson Labs 141 6. True or False? If you were to develop the web application by using XML, you will be able to manipulate the appearance of the web page by using style sheets. True False LESSON LABS Object-Oriented Programming and Design Using Java (Third Edition) 142 abstraction The process of developing a simple represen- tation of a complex object. ActiveX A technology that facilitates the transfer of data between two applications. activity diagram A UML diagram that enables you to model business workow. algorithmic approach An approach that focuses on the functionality of a program. analysis phase The rst phase of the SDLC in which the feasibility and scope of a project are decided. applet A Java program that can be embedded in an HTML page. assembler A tool used to convert assembly language into machine language. Booch A method that is used for designing object- oriented models in object-oriented software design. CGI executable An application le with a .cgi extension that is primarily run by an HTTP server. class diagram A UML diagram that helps represent the structure of classes used within a system, identifying each classs attributes, operations, and relationships to other classes. class library A collection of reusable classes that are used in building a set of related software features. class A template from which objects are derived. coding phase The third phase of the SDLC in which the source code of the program is written. communication diagram A UML diagram that helps represent interac- tions that occur among different objects within a system with more focus on the object. compiler A programming tool used to convert high- level instructions (source code) to an executable le containing machine-level instructions. component diagram A UML diagram that helps show the depen- dencies of one software component upon another. composite structure diagram A UML diagram that describes the function- ing of a system by displaying interactions between classes, interfaces, and components. deployment diagram A UML diagram that shows how various ele- ments of a system will be congured when the program is nally installed and running. derived class A class derived from the base class. It is oth- erwise known as a subclass or child class. GLOSSARY GLOSSARY Glossary 143 design phase The second phase of the SDLC in which the ow of work is planned. encapsulation A software design technique in which data and procedures related to the data are bundled together within a single entity, called the object. framework A collection of classes and related template code that are used in building generic features of an application. gopher application An application that searches for and retrieves documents that reside on remote computer systems. Information thus retrieved is pre- sented in the form of menus. Gophers are predecessors to web browsers. hierarchical inheritance Ability of many child classes inheriting its attributes from a single parent class. hybrid inheritance Ability of a child class to be derived from any two of the other four inheritance types. information hiding A programming technique that hides the implementation of the software from the user interface. inheritance A mechanism whereby a subclass accumulates attributes and methods from one or more ancestor classes. integration phase The fth phase of the SDLC, which involves making the developed software available for commercial use. interaction overview diagram A UML diagram that depicts the collaboration among interaction diagrams. machine language A coding language with instructions specied at the level of hardware. maintenance phase The sixth stage of the SDLC, which involves regular updates of the software and other maintenance services. modularity Breaking up a large programming task into subtasks, which are then programmed inde- pendently. multilevel inheritance Ability of a class to derive its attributes from a child class which is a child class of another parent class. multiple inheritance Ability to derive a child class from more than one parent class. notations A specialized language that aids communica- tion between object-oriented programmers. object diagram A UML diagram that represents the logical relationships of objects within a system. object-based programming languages Languages that provide the programmer the facility to use pre-dened objects. object-oriented approach A system analysis approach that views the system as a set of objects and the interactions among them. object-oriented programming languages Languages that provide the programmer with some means for dening and using objects. object An instance of a class. OMT (Object Modeling Technique) A modeling lan- guage used to develop object-oriented models. OOSE (Object Oriented Software Engineering) Pro- vides an approach to object-oriented analysis and design that focuses on use cases. package diagram A UML diagram that shows how software will be broken up into modules. GLOSSARY Object-Oriented Programming and Design Using Java (Third Edition) 144 package A collection of classes. parent class A class from which a subclass is derived. polymorphism It is the ability to assign different uses to an entity under different contexts. project plan A formal document, which is accepted by management that contains a generic descrip- tion about the project, various tasks, resources, and costs involved. SDLC (Software Development Life Cycle) A set of processes followed to develop a software application. sequence diagram A UML diagram that helps represent the type of communication and the interactions that occur among objects. single inheritance Ability of a child or derived class to derive its characteristics from a single parent or base class. software design methodologies Specic approaches programmers have devel- oped over many years of trial and error to designing objects. software development process A framework based on which a software product is developed. SQL (Structured Query Language) A fourth- generation language used to retrieve information from a database using instructions similar to human language. srs (Software Requirements Specications) A document furnishing the details of the func- tionality to be incorporated into software based on customer requirements. It is also known as functional requirements, user requirements, or software specications. state machine diagram A UML diagram that represents the various events that cause an object to change from one state to another, and the actions that result from the change in state. subclass A class that is based on another class, inherit- ing the attributes and methods of the class it is based on. test cases A description of various scenarios that will be constructed and analyzed to identify if a pro- gram runs correctly as designed. testing phase The fourth phase of the SDLC in which the program is tested to make sure it generates the expected results and is error free. timing diagram A behavioral representation of different objects of a system in a given time window. UML (Unied Modeling Language) A notational language that provides different types of dia- grams for designing software systems. It includes features from OOSE, OMT, and Booch. use case diagram A UML diagram that helps model a business process from a users perspective. use cases A description of the type of user accessing software to accomplish a particular task. They provide a means of identifying the functional- ity that software must support. user interface The portion of a program with which users interact to issue commands, and view or hear results. web server Software that enables a computer to send web pages over a network connection, such as the Internet, to a client computertypically a computer running a web browser. GLOSSARY Glossary 145 Object-Oriented Programming and Design Using Java (Third Edition) 146 NOTES A abstraction, 53 ActiveX, 99, 116 applets, 120, 126 life cycle of, 127 approaches to problem-set analysis algorithmic, 35 object-oriented assemblers, 39 B Booch, 13 C CGI executables, 123 class libraries, 105 class structure attributes of, 15 classes, 12 compilers, 39 D Document Object Model See: DOM DOM, 120 E encapsulation, 56 evolution stages in application development, 98 Also See: ActiveX F frameworks, 105 G generations of programming languages, 39 gopher applications, 109 I information hiding, 58 inheritance, 78 levels of, 79 J Java, 123 classes in Java, 124 CLASSPATH, 124 Java Development Kit See: JDK Java Runtime Environment, 124 JDK, 124 M machine language, 39 methods overloading, 89 overriding, 89 modularity, 59 N notations, 24 O Object Modeling Technique See: OMT Object Oriented Software Engineering See: OOSE objects, 12 OMT, 13 OOSE, 13 P packages, 60 parent classes, 78 polymorphism, 86 types of, 88 problem sets programming, 34 processes coding, 16 INDEX INDEX Index 147 software development, 2 web communication, 109 web page display, 120 programming languages object-based, 42 object-oriented, 41 project plans, 3 guidelines for developing, 4 S SDLC phases in, 2 server extensions, 123 software design methodologies, 22 Software Development Life Cycle See: SDLC Software Requirements Specications See: srs SQL, 39 srs, 7 general aspects of, 8 identifying elements in, 10 static/dynamic web pages, 109 subclasses, 76 T technologies client-side, 114 server-side, 111 test cases, 9 U UML, 13 UML diagrams, 25 Unied Modeling Language See: UML use cases, 9 W web applications, 108 web communication in dynamic pages, 117 web elements, 108 windowed applications, 100 working of, 100 INDEX Object-Oriented Programming and Design Using Java (Third Edition) 148