intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Object Oriented Programming With Java

Chia sẻ: Phung Tuyet | Ngày: | Loại File: PDF | Số trang:846

209
lượt xem
33
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Welcome to the world of Object-Oriented Programming with Java. Please take your time to read this introduction. It will help you set up your computer system so that you can execute the Java program examples used throughout this book and so that you will be able to create and execute your own Java programs. The chapter begins by instructing you how to download and install the Java 2 Software Development Kit (SDK) from Sun Microsystems, Inc

Chủ đề:
Lưu

Nội dung Text: Object Oriented Programming With Java

  1. Object-Oriented Programming With Java, Second Edition Barry J. Holmes Daniel T. Joyce JONES AND BARTLETT PUBLISHERS
  2. Object-Oriented Programming with Java Second Edition Barry J. Holmes Oxford Brookes University Daniel T. Joyce Villanova University JONES AND BARTLETT PUBLISHERS Sudbury, Massachusetts B OSTON T ORONTO L ONDON S INGAPORE
  3. World Headquarters Jones and Bartlett Publishers Jones and Bartlett Publishers Jones and Bartlett Publishers Canada International 40 Tall Pine Drive 2406 Nikanna Road Barb House, Barb Mews Sudbury, MA 01776 Mississauga, ON L5C 2W6 London W6 7PA 978-443-5000 CANADA UK info@jbpub.com www.jbpub.com Copyright © 2001 by Jones and Bartlett Publishers, Inc. Library of Congress Cataloging-in-Publication Data Holmes, Barry (Barry J.) Object-oriented programming with Java / Barry Holmes, Daniel Joyce. p. cm. Includes bibliographical references and index. ISBN 0-7637-1435-6 1. Java (Computer program language) 2. Object-oriented programming (Computer Science) I. Joyce, Daniel T. II. Title. QA76.73.J38 H62 2000 005.13’3—dc21 00-062545 7278 Cover image © Peter R. Harris All rights reserved. No part of the material protected by this copyright notice may be repro- duced or utilized in any form, electronic or mechanical, including photocopying, recording, or any information storage or retrieval system, without written permission from the copyright owner. The computer programs presented in this book have been included for their instructional value. They have been computer-tested with considerable care and are not guaranteed for any particular purpose. The authors do not offer any warranties or representations, nor do they accept any liabilities with respect to the computer programs. Chief Executive Officer: Clayton Jones Chief Operating Officer: Don W. Jones, Jr. Executive Vice President and Publisher: Tom Manning V.P., Sales and Marketing: Paul Shepardson V.P., College Editorial Director: Brian L. McKean V.P., Managing Editor: Judith H. Hauck V.P., Design and Production: Anne Spencer V.P., Manufacturing and Inventory Control: Therese Bräuer Director of Media Services: W. Scott Smith Senior Acquisitions Editor: Michael Stranz Development and Product Manager: Amy Rose Cover Design: Night & Day Design Composition: Northeast Compositors, Inc. Text Design: Delgado Design, Inc. Printing and Binding: Courier Westford Cover printing: John Pow Company, Inc. This book was typeset in Quark 4.1 on a Macintosh G4. The font families used were Adobe Caslon, Franklin Gothic, and Prestige Elite. The first printing was printed on 45 lb. Utopia Book Matte. Printed in the United States of America 04 03 02 01 00 10 9 8 7 6 5 4 3 2 1
  4. This book is dedicated to all of our students, past, present, and future
  5. This page intentionally left blank
  6. Preface Our Intended Audience Object-Oriented Programming with Java is written for first-year college/univer- sity programming courses worldwide. It introduces you to object-oriented design and programming and can be used in computing programs for a first course. The book is aimed at a broad audience of students in science, engineer- ing, and business, where a knowledge of programming is thought to be essential. We have assumed that you have no prior knowledge of computer program- ming; however, you are expected to be familiar with the fundamentals of operat- ing a home computer. Our Philosophy We believe students should be exposed to sound, modern software development practices from the very start of their studies. Several features of this textbook support this philosophy: ■ Our audio-visual interface (avi) package, described in more detail later, allows you to create interesting screen-oriented user interfaces from the very start. For example, you will use check boxes, radio buttons, sliders, and dia- logue boxes for input and will be able to output images and sounds. ■ In addition to allowing modern I/O approaches, the avi package provides good practice in the use of abstraction and third-party packages. v
  7. vi Preface ■ Since Java is an object-oriented programming language, we introduce objects from the word go! In Chapter 2 we show you how to use classes from the Java Application Programming Interface (API) and how to create objects. By Chapter 3 we introduce you to object-oriented programming and the creation of your own classes and objects. ■ We introduce a systematic approach to program design, implementation, and testing in Chapter 3, and this approach is used in examples and case studies throughout the rest of the text. ■ We present the Unified Modeling Language (UML) and use it throughout the text on an as-needed basis, allowing you to gradually learn this univer- sally accepted modeling language as you also learn the fundamentals of object-oriented programming with Java. ■ We provide an early introduction to object-oriented design approaches, such as using noun and verb analysis to help identify objects and methods. ■ As the problems addressed become more complex, we turn to CRC cards to drive the analysis stage. ■ We provide many nontrivial programs throughout the text to clarify topic coverage and to provide examples of substantial programs. The AVI Package One of the difficulties we have found in the past in teaching Java to beginners is the complexity of the Java input/output scheme, whether it is in the context of a simple windowing system or a full-blown graphical user interface. To overcome this problem, Barry Holmes has written an audio-visual inter- face package in Java called avi, to enable beginner programmers to create and use windowing components for input and output. In addition to the input and output of text, the avi package will permit you to input from predefined check boxes, radio buttons, and scrolling lists; display pictures; and play prerecorded sound. This approach allows us to use more interesting examples than do most introductory textbooks and will increase your interaction with the text. By the end of the book you will have enough knowledge to understand fully how this package was written and the functionality of its Java code. Use of the avi package is introduced gradually throughout the early chap- ters of the text: ■ In Chapter 2 we give an overview of the package, and you learn how to cre- ate a window to hold your input and output objects, how to obtain an input String from the user, and how to output text to the window. ■ Chapter 3 covers the output of images and sounds, and includes the use of a “timer” so that you can control when these items are shown in the window. Example programs include one that features a slide show of vacation spots
  8. vii Preface and another that simulates rolling a die, complete with the image of the die face that turns up and an announcement of what was rolled. ■ Chapter 4 provides more input and output options: Sliders, Radio- Buttons, and Memo boxes. ■ Chapter 5 completes the presentation of the avi by introducing the Checkbox input object. Examples in this chapter include an “alarm clock” program. The avi package is included on the CD-ROM bundled with this book. Overview of the Book This textbook includes material typically covered in a first course in computer programming, which are sometimes referred to as “CS1.” The CS1 material can be found in Chapters 1 through 7, and should be enough material to build a first course around. Additionally, Chapters 8 through 11 introduce graphical user interface programming in Java, a topic that is increasingly finding its way into the early part of the CS curriculum. Finally, Chapter 12 provides an introduc- tion to more advanced data structure and algorithm topics. Comparing the book’s topics to the current draft of the IEEE/ACM Computing Curricula 2001, we can safely claim that it provides complete cover- age of Programming Fundamentals areas 1 (Algorithms and problem-solving), 2 (Fundamental programming constructs), and 3 (Basic data structures), and most of areas 5 (Abstract data types), 6 (Object-oriented programming), 7 (Event-driven and concurrent programming), and 8 (Using modern APIs). Note that we do not cover area 4 (Recursion), since we believe that topic is more suited to a later course. A more detailed description of the contents follows. Chapters 1 to 5 provide a gradual introduction to the fundamentals of pro- gramming. Here, much emphasis is placed upon good practice involving object- oriented program design, testing, and implementation. These chapters broadly cover: primitive data types, arithmetic, classes, objects, and input and output via an audio-visual interface; class methods, constructors, and instance methods; program design, UML notation, implementation, compilation and error correc- tion; if and switch selection statements; while, do, and for loop statements; and one-dimensional arrays. Once you understand the fundamentals of programming and can create and use classes competently, you can then explore the Java language and object-ori- ented programming to a much greater depth. Chapters 6 and 7 cover the topics of encapsulation, abstract data types, object properties, inheritance, polymor- phism, genericity, exception handling, and data streams. Graphical user interfaces are so important in the development of modern software that Chapters 8 and 9 are devoted to the production of graphical interfaces using the classes supplied by the Java Abstract Windowing Toolkit.
  9. viii Preface These chapters also explain how some of the avi package components that have been used throughout the book for input and output are written in Java. Since program and class design feature strongly in this book, Chapter 10 covers the topic of objects working together as well as further UML notation. Chapter 11 provides a complete coverage of writing and running Java Applets on a web browser. Finally, Chapter 12 introduces the topics of sorting, searching, and dynamic data structures. Language and Computer Requirements The most effective way to learn Java programming with this book is to use your computer to run the example programs and case studies, and to check your answers to the programming problems. All the programs written in this book have been compiled and tested using Sun Microsystems, Inc. Java Development Kit (SDK) version 1.2 (release 1.2.2) on both a PC-compatible microcomputer under Windows 98 and a Sun Workstation under Solaris. The Introduction explains how to download and install the latest version of the Java Development Kit from the World Wide Web to your computer. Pedagogical Features Objectives Each chapter begins with a set of learning objectives. Case Studies Many chapters contain fully designed case studies with comprehensive docu- mentation, program listings, and output. Example Programs All chapters contain complete example programs used to demonstrate the key features of the chapter. All computer programs are followed by a listing of the output from the program. End-of-Chapter Summary Every chapter contains a summary of its key points. This provides you with a check-list of topics you should understand before you progress to the next chapter. Review Questions All chapters contain review questions to enable you to test and reinforce your knowledge.
  10. ix Preface Exercises All chapters contain pencil-and-paper exercises that are designed to test your understanding of the programming topics introduced in the chapter. The exer- cises should normally be tackled before the programming problems. Solutions to the exercises appear in Appendix C. Programming Problems All chapters contain a robust set of programming problems that require the use of a computer to solve. Icons The chapters include icons or special design elements for quick reference: SYNTAX These statements express the grammar of the language, and illustrate how language statements are constructed. i This icon signals information the authors feel should be brought to your attention. 1 ! Pay special attention to this cautionary advice. NOW DO THIS Throughout the chapters you are asked to experiment with the language features that have been introduced. Experimentation can take the form of modifying an existing program to gain insight into its functionality, or writing a new program to reinforce knowledge gained. This feature can form the focus for many laboratory exercises.
  11. x Preface Supplements to the Text Compact Disk A CD-ROM accompanies this book and contains the following software: ■ The audio-visual interface. ■ All of the example and case-study computer programs used throughout the book. ■ All of the image and sound files required to support the example programs. Instructor’s Guide A comprehensive web-based instructor’s guide is available, free of charge, to adopters of Object-Oriented Programming with Java. The instructor’s guide is accessible via a password protected page on the Jones and Bartlett web site. This guide contains hints and tips on teaching the material, together with all of the answers to the review questions, and many of the programming problems. To utilize this guide, qualified instructors should contact their Jones and Bartlett Publisher’s Representative at (800) 832-0034 or info@jbpub.com to receive a URL and password. Acknowledgments The authors would like to express their thanks to the following technical reviewers, whose comments they found to be most constructive and helpful, and who have contributed toward shaping this book into its present form: Robert Burton, Brigham Young University; Michael Fry, Lebanon Valley College; David Hughes, Brock University; Pamela Lawhead, University of Mississippi; Dale Skrien, Colby College. In addition, the authors would like to express their thanks to Amy Rose and Michael Stranz at Jones and Bartlett and to Mike and Sigrid Wile at Northeast Compositors for their professional insight and team approach to the develop- ment and the production of the book. Barry Holmes—Oxford, England Daniel Joyce—Philadelphia, USA
  12. Contents Chapter 0 Introduction 1 0.1 What is Java? 2 0.2 Using the Internet 3 0.3 Downloading the Java 2 SDK for Windows, Unix (Solaris), and Linux Users 4 0.4 Downloading Java 2 SDK Documentation 4 0.5 Creating a Java Software Development Environment 5 0.6 Copying and Installing the Audio-Visual Interface (AVI) 7 0.7 How to Input and Save a Java Program in the Computer 9 0.8 How to Compile a Java Program 10 0.9 How to Execute (run) a Java Program 12 0.10 SDK Tools 14 0.11 Copying and Editing Programs from the CD 15 Summary 17 Chapter 1 Primitive Data Types and Arithmetic 19 1.1 Data 20 1.2 Data Storage 21 Number Systems 23 1.3 Identifiers 27 1.4 Syntax 29 1.5 Variables and Constants 31 xi
  13. xii Contents 1.6 The Format of a Simple Program 33 1.7 Arithmetic 35 Unary Operators 35 Binary Multiplicative Operators 35 Binary Additive Operators 35 1.8 Operator Precedence 40 1.9 Casting 42 Summary 45 Review Questions 46 Exercises 47 Programming Problems 49 Chapter 2 Objects 51 2.1 Introduction to Objects 52 2.2 The String Class 53 Declaring Objects 54 Methods and Parameters 54 Constructors 56 String Assignment 58 Instance Methods 58 2.3 The Anatomy of a Simple Program Revisited 61 Heading Giving Details of the Name and Purpose of the Program 62 Import List 62 Class Name 63 Main Method 63 2.4 The AVI Package 63 2.5 The Window Class 65 2.6 Input to a Dialog Box 69 2.7 Converting Strings to Numbers 72 2.8 Command Line Arguments 75 2.9 Errors 78 Syntax Errors 78 Run-Time Errors 82 Logical Errors 82 Summary 82 Review Questions 83 Exercises 84 Programming Problems 85 Chapter 3 Object-Oriented Programming 87 3.1 Abstract Data Type 88 3.2 Constructors 90 3.3 Instance Methods 93 3.4 Class Methods 101
  14. xiii Contents 3.5 Scope and Lifetime of Identifiers 104 3.6 Software Development 106 3.7 Object-Oriented Program Design 108 Identify the Classes and Methods 109 Algorithm Development 111 Testing 112 Compilation and Execution 112 Documentation 113 Case Study: Cutting Logs 116 3.8 The AVI Package Revisited 124 The Audio Class 125 The Timer Class 128 The Filmstrip Class 130 Case Study: A Simulation of Rolling a Die 135 Summary 144 Review Questions 146 Exercises 147 Programming Problems 150 Chapter 4 Selection 153 4.1 More AVI Classes 154 The Slider Class 154 The RadioButtons Class 156 4.2 If..else Statement 161 4.3 Nested If Statement 166 4.4 Conditional Expressions 172 4.5 Else if Statements 176 4.6 Boolean Data Type 177 4.7 Switch 179 4.8 Wrapper Classes 184 Case Study: Body Mass Index 185 4.9 Yet another AVI Class! 194 The Memo Class 194 4.10 The This Object 195 Case Study: Validation of Dates including Leap Years 196 Summary 209 Review Questions 210 Exercises 210 Programming Problems 212 Chapter 5 Repetition and One-Dimensional Arrays 217 5.1 Loop Structure 218 5.2 While Loop 220
  15. xiv Contents While Loop Controlled by a Counter 220 While Loop Controlled by Data 220 5.3 Do..while Loop 227 5.4 Increment/Decrement Operators 232 5.5 For Loop 235 5.6 Which Loop? 239 while 240 do..while 240 for 240 5.7 Arrays Revisited 241 5.8 Declaring and Initializing One-Dimensional Arrays 242 Three Methods 242 5.9 Using Arrays 245 Case Study: Palindrome 253 5.10 Our Last AVI Class: CheckBoxes 261 The CheckBox Class 261 5.11 Formatting Numbers for Output 264 Case Study: Ben’s Breakfast Bar 267 Summary 282 Review Questions 283 Exercises 283 Programming Problems 285 Chapter 6 Advanced Concepts with Classes 289 6.1 Inheritance 290 6.2 An Example of Inheritance 292 6.3 Overriding Superclass Methods 299 6.4 Polymorphism 303 6.5 Instanceof Operator 307 6.6 Shadowed Variables 309 6.7 Inner Classes 312 6.8 Abstract Methods and Classes 312 Case Study: Boats 317 6.9 Interfaces 339 6.10 Constructors Revisited 345 6.11 Instance Methods Revisited 347 6.12 Object Properties 348 Comparing Objects 348 Copying Objects 350 Passing Objects as Parameters 352 Case Study: Arithmetic of Rational Numbers 353 6.13 Garbage Collection and Object Finalization 361 Summary 363
  16. xv Contents Review Questions 365 Exercises 366 Programming Problems 371 Chapter 7 Exceptions and Streams 375 7.1 Introduction 376 7.2 Exception Classes 377 7.3 Catching an Exception 379 7.4 Catching Multiple Exceptions 383 7.5 Creating Your Own Exception Class 387 7.6 Throwing an Exception 390 7.7 Finally Blocks 394 7.8 Using Exception Handling 396 7.9 Stream Input and Output 398 7.10 The StreamTokenizer Class 404 7.11 Text File Processing 407 Book Example Problem 412 Another Example: Using a File Viewer 417 7.12 The FileDialog Class 419 Case Study: Reporting on the Statistics of a Text File 422 Summary 433 Review Questions 434 Exercises 435 Programming Problems 438 Chapter 8 An Introduction to the java.awt Package 443 8.1 Creating a Container 444 8.2 Handling an Event 448 8.3 Adding a Button to the Container 451 8.4 Adding Labels, Fonts, and Text Fields to a Container 457 Labels 457 Fonts 458 Text Fields 461 8.5 Adding Check Boxes, Radio Buttons, and Lists to a Container 465 Check Boxes 465 Radio Buttons 468 List 472 8.6 Creating a Reusable Container 476 8.7 Creating a Reusable WritingPad Component 480
  17. xvi Contents 8.8 Creating a Reusable DialogBox Component 486 8.9 Creating a Reusable CheckBoxes Component 491 8.10 Java Swing 497 Summary 497 Review Questions 499 Exercises 500 Programming Problems 500 Chapter 9 Vectors, Serialization, and the java.awt Graphics Class 501 9.1 Vectors 502 Case Study: Chemical Elements 508 9.2 Saving and Loading Serializable Objects 520 9.3 The Graphics Class 524 9.4 Mouse Events 527 9.5 Pop-Up Menus 534 9.6 Painting the Screen 544 9.7 Printing Objects 548 Summary 558 Review Questions 558 Exercises 559 Programming Problems 560 Chapter 10 Objects Working Together 563 10.1 Packages 564 10.2 Associations 570 10.3 CRC Cards 582 10.4 Aggregation 586 10.5 Composition 598 10.6 Building a Student Management System 599 10.7 Menus Revisited 604 10.8 Testing the Student Management System 608 Summary 613 Review Questions 614 Exercises 615 Programming Problems 616 Chapter 11 Applets and Threads 619 11.1 Introduction 620 11.2 Applets 622 11.3 Input to Applets 628 11.4 Playing Sounds 634 11.5 Displaying Images 637
  18. xvii Contents 11.6 Loading Images 639 11.7 Arrays Revisited 641 11.8 Image Maps 645 11.9 Threads 649 Case Study: An Example of Multithreading 657 11.10 Animation 668 11.11 Restrictions 673 11.12 Sound and Images with Applications 674 Sound 675 Images 675 11.13 Conclusion 676 Summary 677 Review Questions 679 Exercises 680 Programming Problems 682 Chapter 12 Sorting, Searching, and Dynamic Data Structures 685 12.1 Sorting 686 12.2 Class java.util.Arrays—Sort 12.3 Sequential Search 700 12.4 Class java.util.Arrays—Binary Search 12.5 Linked Lists 708 LinkedList Class 718 12.6 Stacks 726 Case Study: Using a Stack for Converting Algebraic Expressions 728 Summary 738 Review Questions 739 Exercises 739 Programming Problems 739 Appendix A Tables 743 A.1 ASCII Characters 743 A.2 Java Primitive Data Types 744 A.3 Operator Priorities 745 A.4 Escape-Sequence Characters 746 Appendix B Syntax of Java 747 B.1 Productions of Lexical Structures 747 B.2 Productions from Types, Values, and Variables 747 B.3 Productions from Names 748 B.4 Productions from Packages 748
  19. xviii Contents B.5 Productions Used Only in the LALR(1) Grammar 749 B.6 Productions from Classes 749 Productions from Class Declarations 749 Productions from Field Declarations 750 Productions from Method Declarations 751 Productions from Static Initializers 751 Productions from Constructor Declarations 751 B.7 Productions from Interfaces 752 Productions from Interface Declarations 752 B.8 Productions from Arrays 752 B.9 Productions from Blocks and Statements 753 B.10 Productions from Expressions 756 Appendix C Answers to Exercises 761 Index 805
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2