Understanding Oop With Java by Timothy Budd
Understanding Oop With Java by Timothy Budd
Timothy Budd
Oregon State University
Acquisitions Editor: Susan Hartman Production Editor: Patricia A. O. Unubun Design Editor: Alwyn R. Vel squez a Packager: Jennifer Brownlow Bagdigian Compositor: Windfall Software, Paul C. Anagnostopoulos & Jacqui Scarlott Manufacturing Coordinator: Judy Sullivan Cover Illustrator: Susan Cyr
Access the latest information about Addison-Wesley titles from our World Wide Web site: http: www.awl.com cseng Java is a trademark of Sun Microsystems, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or in all caps. The programs and the applications presented in this book have been included for their instructional value. They have been tested with care but are not guaranteed for any particular purpose. Neither the publisher or the author o ers any warranties or representations, nor do they accept any liabilities with respect to the programs or applications. This book was typeset in ZzTEX on a PC. The fonts used were Sabon, Univers, MathTime, and Bell Centennial. It was printed on New Era Matte. Copyright 1998 by Addison Wesley Longman, Inc. All rights reserved. No part of this publication may be reproduced, or stored in a database or retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or any other media embodiments now known or hereafter to become known, without the prior written permission of the publisher. Printed in the United States of America.
Library of Congress Cataloging-in-Publication Data
Budd, Timothy. Understanding object-oriented programming with Java Timothy A. Budd. p. cm. Includes index. ISBN 0-201-30881-9 1. Object-oriented programming Computer science 2. Java Computer program language I. Title. QA76.64.B835 1998 005.13 3|dc21 97-46728 CIP AC
0
Preface
There are many books on Java that teach you how to use the language, but few books that teach you why the language works in the way that it does. Many books help you learn the mechanics of Java programming; few books teach you the deeper issues that lie behind the programming syntax. The goal of this book is to give the reader a fuller, more complete understanding of the philosophy behind Java, not just the mechanics of the language. Throughout the book these principles and practices are illustrated with extensive examples from the Java standard library. Here you can learn, for example, the many design patterns that are found in the AWT, the multitude of purposes for which inheritance is used in the standard classes, and why there are 22 di erent types of input output le streams. Here you can discover why the lack of an ordered container class in the standard library is not a simple omission, but is instead a re ection of a fundamental and deep property of the Java language. In short, this book should not be considered a reference manual for the Java language, but rather a tool for understanding the Java philosophy.
iv
Preface
of the Java language, but rather provides examples designed to motivate the need for mechanisms discussed in other parts of the text. Part 3 discusses inheritance, the next major object-oriented concept that the student must master after learning about classes and objects. Inheritance is a technique that is super cially obvious, but that possesses many subtle aspects that can trap the unwary programmer. The introduction of inheritance into a programming language has an impact on almost every other aspect of the language. For this reason, students familiar with conventional non-objectoriented languages should pay careful attention to this part of the book. Part 4 discusses polymorphism, which is often an even subtler concept for the student to understand than inheritance. Polymorphism is the mechanism through which much of the power and applicability of object-oriented techniques is manifest. Polymorphism is found in Java in many ways, as shown by the extensive examples studied in this part of the book. Part 5 discusses features of the Java world that are important for the student to understand, but not particularly notable for their object-oriented features. These items are separated from the remainder of the text so that they do not interrupt the ow of the narrative developed earlier in the book. However, the features discussed are not as di cult as their late placement in the book might indicate. At the instructor's discretion these features can be omitted altogether, or introduced in parallel with earlier material.
Acknowledgments
Invaluable advice was provided by the reviewers who examined an early draft of the book. These included Richard Anderson, University of Washington; Richard Carver, George Mason University; Deborah Frincke, University of Idaho; Matt Greenwood, Bell Laboratories; David Riley, University of Wisconsin La Crosse; J. Richard Rinewalt, Texas Christian University. I would like to thank my editors at Addison-Wesley, Susan Hartman and Deborah La erty, who patiently and quietly su ered through countless delays
Acknowledgments
and postponements. It is my sincere hope that they, as well as the reader, will nd the result to have been worth the wait.
Contents
Preface iii
Structure of the Book iii Obtaining the Source iv Acknowledgments iv
1.1 A Way of Viewing the World 3 1.1.1 Agents and Communities 4 1.1.2 Messages and Methods 5 1.1.3 Responsibilities 6 1.1.4 Classes and Instances 6 1.1.5 Class Hierarchies|Inheritance 7 1.1.6 Method Binding, Overriding, and Exceptions 9 1.1.7 Summary of Object-Oriented Concepts 9 1.2 Computation as Simulation 10 1.2.1 The Power of Metaphor 11 1.3 Chapter Summary 12 Further Reading 13 Study Questions 14 Exercises 15 2.1 The History of Java 18 2.2 Client-Side Computing 19 2.2.1 Bytecode Interpreters and Just In Time Compilers 21
1 Object-Oriented Thinking 3
vii
viii
Contents
2.2.2 Security Issues 21 2.2.3 Specialization of Interfaces 22 2.3 The White Paper Description 22 2.3.1 Java Is Simple 23 2.3.2 Java Is Object-Oriented 23 2.3.3 Java Is Network Savvy 23 2.3.4 Java Is Interpreted 24 2.3.5 Java Is Robust 24 2.3.6 Java Is Secure 25 2.3.7 Java Is Architecture Neutral 25 2.3.8 Java Is Portable 26 2.3.9 Java Is High-Performance 26 2.3.10 Java Is Multithreaded 26 2.3.11 Java Is Dynamic 26 2.4 Chapter Summary 26 Study Questions 27 Exercises 27 Responsibility Implies Noninterference 29 Programming in the Small and in the Large 30 Why Begin with Behavior? 31 A Case Study in RDD 32 3.4.1 The Interactive Intelligent Kitchen Helper 32 3.4.2 Working With Components 33 3.4.3 Identi cation of Components 33 3.5 CRC Cards|Recording Responsibility 34 3.5.1 Giving Components a Physical Representation 35 3.5.2 The What Who Cycle 35 3.5.3 Documentation 35 3.6 Components and Behavior 36 3.6.1 Postponing Decisions 37 3.6.2 Preparing for Change 38 3.6.3 Continuing the Scenario 38 3.6.4 Interaction Diagrams 40 3.7 Software Components 41 3.7.1 Behavior and State 41 3.7.2 Instances and Classes 42 3.1 3.2 3.3 3.4
3 Object-Oriented Design 29
Contents
ix
3.7.3 Coupling and Cohesion 42 3.7.4 Interface and Implementation: Parnas's Principles 43 Formalizing the Interface 44 3.8.1 Coming Up with Names 44 Designing the Representation 46 Implementing Components 47 Integration of Components 47 Maintenance and Evolution 48 Chapter Summary 49 Study Questions 49 Exercises 50
II UNDERSTANDING PARADIGMS 53
4.1 4.2 4.3 4.4 4.5 4.6
4 A Paradigm 55
Program Structure 56 The Connection to the Java World 58 Types 59 Access Modi ers 61 Lifetime Modi ers 63 Chapter Summary 64 Cross References 65 Study Questions 65 Exercises 66
5.1 Data Fields 70 5.2 Constructors 73 5.2.1 Constructing the Application 74 5.3 Inheritance 76 5.4 The Java Graphics Model 77 5.5 The Class Ball 79 5.6 Multiple Objects of the Same Class 80
5 Ball Worlds 69
Contents
6.1 The Simple Cannon Game 86 6.1.1 Balls That Respond to Gravity 90 6.1.2 Integers and ints 91 6.2 Adding User Interaction 91 6.2.1 Inner Classes 92 6.2.2 Interfaces 94 6.2.3 The Java Event Model 95 6.2.4 Window Layout 97 6.3 Chapter Summary 97 Cross References 99 Study Questions 99 Exercises 99
6 A Cannon Game 85
7.1 First Version of Game 101 7.1.1 Collection Classes 102 7.1.2 Mouse Listeners 105 7.1.3 Multiple Threads of Execution 107 7.1.4 Exception Handling 108 7.2 Adding Targets: Inheritance and Interfaces 109 7.2.1 The Pinball Target Interface 109 7.2.2 Adding a Label to Our Pinball Game 114 7.3 Pinball Game Construction Kit: Mouse Events Reconsidered 118 7.4 Chapter Summary 118 Cross References 121 Study Questions 121 Exercises 122
Contents
xi
8.8
8.9
An Intuitive Description of Inheritance 127 The Base Class Object 128 Subclass, Subtype, and Substitutability 129 Forms of Inheritance 130 8.4.1 Inheritance for Specialization 131 8.4.2 Inheritance for Speci cation 131 8.4.3 Inheritance for Construction 133 8.4.4 Inheritance for Extension 135 8.4.5 Inheritance for Limitation 136 8.4.6 Inheritance for Combination 136 8.4.7 Summary of the Forms of Inheritance 137 Modi ers and Inheritance 138 Programming as a Multiperson Activity 139 The Bene ts of Inheritance 139 8.7.1 Software Reusability 139 8.7.2 Increased Reliability 139 8.7.3 Code Sharing 140 8.7.4 Consistency of Interface 140 8.7.5 Software Components 140 8.7.6 Rapid Prototyping 140 8.7.7 Polymorphism and Frameworks 141 8.7.8 Information Hiding 141 The Costs of Inheritance 141 8.8.1 Execution Speed 142 8.8.2 Program Size 142 8.8.3 Message-Passing Overhead 142 8.8.4 Program Complexity 142 Chapter Summary 143 Study Questions 143 Exercises 144
xii
Contents
9.3 Card Piles|Inheritance in Action 152 9.3.1 The Suit Piles 155 9.3.2 The Deck Pile 155 9.3.3 The Discard Pile 157 9.3.4 The Tableau Piles 157 9.4 The Application Class 161 9.5 Playing the Polymorphic Game 161 9.6 Building a More Complete Game 164 9.7 Chapter Summary 164 Study Questions 165 Exercises 165 10.1 Substitutability 167 10.1.1 The Is-a Rule and the Has-a Rule 169 10.1.2 Inheritance of Code and Inheritance of Behavior 169 10.2 Composition and Inheritance Described 170 10.2.1 Using Composition 172 10.2.2 Using Inheritance 173 10.3 Composition and Inheritance Contrasted 174 10.4 Combining Inheritance and Composition 176 10.5 Novel Forms of Software Reuse 178 10.5.1 Dynamic Composition 178 10.5.2 Inheritance of Inner Classes 179 10.5.3 Unnamed Classes 180 10.6 Chapter Summary 181 Study Questions 183 Exercises 183 11.1 The Polymorphic Variable 186 11.2 Memory Layout 187 11.2.1 An Alternative Technique 189 11.3 Assignment 190 11.3.1 Clones 191
Contents
xiii
11.3.2 Parameters as a Form of Assignment 193 11.4 Equality Test 194 11.5 Garbage Collection 197 11.6 Chapter Summary 198 Study Questions 198 Exercises 199
12 Polymorphism 203
xiv
Contents
13.3.4 Scroll Bars 223 13.3.5 Text Components 224 13.3.6 Checkbox 225 13.3.7 Checkbox Groups, Choices, and Lists 226 Panels 227 13.4.1 ScrollPane 229 Case Study: A Color Display 230 Dialogs 234 13.6.1 Example Program for Dialogs 235 The Menu Bar 235 13.7.1 A Quit Menu Facility 237 Chapter Summary 239 Study Questions 239 Exercises 240
14.1 Streams versus Readers and Writers 241 14.2 Input Streams 242 14.2.1 Physical Input Streams 243 14.2.2 Virtual Input Streams 244 14.3 Stream Tokenizer 246 14.4 Output Streams 247 14.5 Object Serialization 250 14.6 Piped Input and Output 252 14.7 Readers and Writers 257 14.8 Chapter Summary 259 Study Questions 260 Exercises 261 15.1 15.2 15.3 15.4
Contents
xv
Flyweight 268 Abstract Factory 268 Factory Method 269 Iterator 270 Decorator Filter or Wrapper 271 Proxy 272 Bridge 273 Chapter Summary 273 Further Reading 273 Study Questions 273 Exercise 274
17.1 Point 285 17.2 Dimension 286 17.3 Date 286 17.3.1 After the Epoch 287 17.4 Math 288 17.5 Random 289
xvi
Contents
17.6 Toolkit 290 17.7 System 291 17.8 Strings and Related Classes 291 17.8.1 Operations on Strings 292 17.8.2 String Bu ers 295 17.8.3 String Tokenizers 296 17.8.4 Parsing String Values 297 17.9 Chapter Summary 297 Study Questions 298 18.1 Color 299 18.2 Rectangles 300 18.2.1 Rectangle Sample Program 301 18.3 Fonts 303 18.3.1 Font Metrics 305 18.3.2 Font Example Program 305 18.4 Images 308 18.4.1 Animation 309 18.5 Graphics Contexts 310 18.6 A Simple Painting Program 312 18.7 Chapter Summary 314 Study Questions 317 Exercises 317 19.1 19.2 19.3 19.4
Element Types and Primitive Value Wrappers 319 Enumerators 320 The Array 322 The Vector Collection 323 19.4.1 Using a Vector as an Array 323 19.4.2 Using a Vector as a Stack 325 19.4.3 Using a Vector as a Queue 325 19.4.4 Using a Vector as a Set 326 19.4.5 Using a Vector as a List 327
Contents
xvii
19.5 The Stack Collection 327 19.6 The BitSet Collection 328 19.6.1 Example Program: Prime Sieve 329 19.7 The Dictionary Interface and the Hashtable Collection 329 19.7.1 Example Program: A Concordance 331 19.7.2 Properties 333 19.8 Why Are There No Ordered Collections? 334 19.9 Building Your Own Containers 336 19.10 Chapter Summary 339 Study Questions 339 Exercises 340 20.1 Creating Threads 341 20.1.1 Synchronizing Threads 345 20.2 Case Study: A Tetris Game 346 20.2.1 The Tetris Game Class 346 20.2.2 The PieceMover Thread 350 20.2.3 The Game Piece Class 353 20.3 Chapter Summary 356 Cross References 356 Study Questions 356 Exercises 357 21.1 21.2 21.3 21.4
Applets and HTML 359 Security Issues 360 Applets and Applications 360 Obtaining Resources Using an Applet 362 21.4.1 Universal Resource Locators 363 21.4.2 Loading a New Web Page 364 21.5 Combining Applications and Applets 364 21.6 Chapter Summary 365 Study Questions 365
xviii
Contents
Addresses, Ports, and Sockets 367 A Simple Client Server Program 369 Multiple Clients 372 Transmitting Objects over a Network 375 Providing More Complexity 380 Chapter Summary 381 Study Questions 381 Exercises 382 Collection Classes 384 Swing User Interface Components 384 Improvements to the Graphics Library 384 Internationalization 385 Java Beans 385 Sound 385 Data Bases 385 Remote Method Invocation 386 Servlets 386 Chapter Summary 386 Further Information 386
23.1 23.2 23.3 23.4 23.5 23.6 23.7 23.8 23.9 23.10 23.11
30.1 Program Structure 401 30.1.1 Import Declaration 401 30.1.2 Class Declaration 402 30.1.3 Interface declaration 403 30.1.4 Method Declaration 403 30.1.5 Constructors 404 30.1.6 Data Field Declaration 405
Contents
xix
30.2 Statements 405 30.2.1 Declaration statement 405 30.2.2 Assignment Statement 406 30.2.3 Procedure Calls 406 30.2.4 If statement 406 30.2.5 Switch Statement 407 30.2.6 While Statement 407 30.2.7 For Statement 408 30.2.8 Return Statement 408 30.2.9 Throw Statement 408 30.2.10 Try Statement 409 30.3 Expressions 409 30.3.1 Literal 409 30.3.2 Variable 410 30.3.3 Data Field and Method Access 411 30.3.4 Operators 412 30.3.5 Object Creation 412 30.3.6 Arrays 412