Click here to load reader
Click here to load reader
Understanding
Object-Oriented
Programming
with JAVA
Timothy BuddOregon State University
An imprint of Addison Wesley Longman, Inc.
Reading, Massachusetts . Harlow, England . Menlo Park, CaliforniaBerkeley, California . Don Mills, Ontario . Sydney
Bonn . Amsterdam . Tokyo . Mexico City
Acquisitions Editor: Susan HartmanProduction Editor: Patricia A. O. UnubunDesign Editor: Alwyn R. Vel�asquezPackager: Jennifer Brownlow BagdigianCompositor: Windfall Software, Paul C. Anagnostopoulos & Jacqui ScarlottManufacturing Coordinator: Judy SullivanCover 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 areclaimed as trademarks. Where those designations appear in this book, and the publisher wasaware 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 theirinstructional value. They have been tested with care but are not guaranteed for any particularpurpose. Neither the publisher or the author o�ers any warranties or representations, nor do theyaccept 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, andBell 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 databaseor 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 becomeknown, 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-91. Object-oriented programming (Computer science) 2. Java
(Computer program language) I. Title.QA76.64.B835 1998005.1303|dc21 97-46728
CIPAC
ISBN 0-201-30881-9
1 2 3 4 5 6 7 8 9 10 MA 0201009998
Preface
There are many books on Java that teach you how to use the language, butfew 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 booksteach you the deeper issues that lie behind the programming syntax. The goalof this book is to give the reader a fuller, more complete understanding of thephilosophy behind Java, not just the mechanics of the language.
Throughout the book these principles and practices are illustrated withextensive examples from the Java standard library. Here you can learn, forexample, the many design patterns that are found in the AWT, the multitudeof purposes for which inheritance is used in the standard classes, and why thereare 22 di�erent types of input/output �le streams. Here you can discover whythe lack of an ordered container class in the standard library is not a simpleomission, but is instead a re ection of a fundamental and deep property of theJava language.
In short, this book should not be considered a reference manual for the Javalanguage, but rather a tool for understanding the Java philosophy.
Structure of the Book
The book is structured in �ve major sections:
Part 1 is a general, language-independent introduction to the ideas that lie atthe heart of the Java world. The �rst major object-oriented concepts, thoseof classes, encapsulation, behavior, and responsibilities, will be introduced inthis part and reinforced in Part 2. Here the student will be introduced to theidea that the solution to a problem can be structured as interactions amonga community of agents. The second chapter of Part 1 presents a brief historyof the development of Java, and can be omitted at the instructor's discretion.However, Chapter 3, on design, should in no way be avoided. In fact, I stronglyencourage students to conduct at least one, if not several, design exercises usingCRC cards, similar to the one presented here, even before they start to learnaspects of the Java programming language.
Part 2 introduces Java through several graduated example programs (paradigms,in the original sense of the word). These examples lead the reader through suc-cessively more of the Java language, introducing new features as they arerequired for speci�c applications. This is not a systematic introduction to all
iii
iv Preface
of the Java language, but rather provides examples designed to motivate theneed for mechanisms discussed in other parts of the text.
Part 3 discusses inheritance, the next major object-oriented concept that thestudent must master after learning about classes and objects. Inheritanceis a technique that is super�cially obvious, but that possesses many subtleaspects that can trap the unwary programmer. The introduction of inheritanceinto a programming language has an impact on almost every other aspect ofthe language. For this reason, students familiar with conventional non-object-oriented languages should pay careful attention to this part of the book.
Part 4 discusses polymorphism, which is often an even subtler concept forthe student to understand than inheritance. Polymorphism is the mechanismthrough which much of the power and applicability of object-oriented tech-niques is manifest. Polymorphism is found in Java in many ways, as shown bythe extensive examples studied in this part of the book.
Part 5 discusses features of the Java world that are important for the studentto understand, but not particularly notable for their object-oriented features.These items are separated from the remainder of the text so that they do notinterrupt the ow of the narrative developed earlier in the book. However, thefeatures discussed are not as di�cult as their late placement in the book mightindicate. At the instructor's discretion these features can be omitted altogether,or introduced in parallel with earlier material.
Obtaining the Source
Source code for the case studies presented in the book can be accessed via themechanism of anonymous ftp from the machine ftp.cs.orst.edu, in the di-rectory /pub/budd/java. This directory is also used to maintain a number ofother items, such as an errata list. This information can also be accessed via theWorld Wide Web, from my personal home pages at http://www.cs.orst.edu/~budd/. Requests for further information can be forwarded to the electronicmail address [email protected], or to Professor Timothy A. Budd, Depart-ment of Computer Science, Oregon State University, Corvallis, Oregon, 97331.
Acknowledgments
Invaluable advice was provided by the reviewers who examined an early draft ofthe book. These included Richard Anderson, University of Washington; RichardCarver, George Mason University; Deborah Frincke, University of Idaho; MattGreenwood, 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 andDeborah La�erty, who patiently and quietly su�ered through countless delays
Acknowledgments v
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
I UNDERSTANDING THE OBJECT-ORIENTED
WORLDVIEW 1
1 Object-Oriented Thinking 3
1.1 A Way of Viewing the World 3
1.1.1 Agents and Communities 41.1.2 Messages and Methods 51.1.3 Responsibilities 61.1.4 Classes and Instances 61.1.5 Class Hierarchies|Inheritance 71.1.6 Method Binding, Overriding, and Exceptions 91.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 A Brief History of Object-Oriented Programming 17
2.1 The History of Java 18
2.2 Client-Side Computing 19
2.2.1 Bytecode Interpreters and Just In Time Compilers 21
vii
viii Contents
2.2.2 Security Issues 212.2.3 Specialization of Interfaces 22
2.3 The White Paper Description 22
2.3.1 Java Is Simple 232.3.2 Java Is Object-Oriented 232.3.3 Java Is Network Savvy 232.3.4 Java Is Interpreted 242.3.5 Java Is Robust 242.3.6 Java Is Secure 252.3.7 Java Is Architecture Neutral 252.3.8 Java Is Portable 262.3.9 Java Is High-Performance 262.3.10 Java Is Multithreaded 262.3.11 Java Is Dynamic 26
2.4 Chapter Summary 26
Study Questions 27
Exercises 27
3 Object-Oriented Design 29
3.1 Responsibility Implies Noninterference 29
3.2 Programming in the Small and in the Large 30
3.3 Why Begin with Behavior? 31
3.4 A Case Study in RDD 32
3.4.1 The Interactive Intelligent Kitchen Helper 323.4.2 Working With Components 333.4.3 Identi�cation of Components 33
3.5 CRC Cards|Recording Responsibility 34
3.5.1 Giving Components a Physical Representation 353.5.2 The What/Who Cycle 353.5.3 Documentation 35
3.6 Components and Behavior 36
3.6.1 Postponing Decisions 373.6.2 Preparing for Change 383.6.3 Continuing the Scenario 383.6.4 Interaction Diagrams 40
3.7 Software Components 41
3.7.1 Behavior and State 413.7.2 Instances and Classes 42
Contents ix
3.7.3 Coupling and Cohesion 423.7.4 Interface and Implementation: Parnas's Principles 43
3.8 Formalizing the Interface 44
3.8.1 Coming Up with Names 44
3.9 Designing the Representation 46
3.10 Implementing Components 47
3.11 Integration of Components 47
3.12 Maintenance and Evolution 48
3.13 Chapter Summary 49
Study Questions 49
Exercises 50
II UNDERSTANDING PARADIGMS 53
4 A Paradigm 55
4.1 Program Structure 56
4.2 The Connection to the Java World 58
4.3 Types 59
4.4 Access Modi�ers 61
4.5 Lifetime Modi�ers 63
4.6 Chapter Summary 64
Cross References 65
Study Questions 65
Exercises 66
5 Ball Worlds 69
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
x Contents
5.7 Chapter Summary 82
Cross References 83
Study Questions 83
Exercises 84
6 A Cannon Game 85
6.1 The Simple Cannon Game 86
6.1.1 Balls That Respond to Gravity 906.1.2 Integers and ints 91
6.2 Adding User Interaction 91
6.2.1 Inner Classes 926.2.2 Interfaces 946.2.3 The Java Event Model 956.2.4 Window Layout 97
6.3 Chapter Summary 97
Cross References 99
Study Questions 99
Exercises 99
7 Pinball Game Construction Kit 101
7.1 First Version of Game 101
7.1.1 Collection Classes 1027.1.2 Mouse Listeners 1057.1.3 Multiple Threads of Execution 1077.1.4 Exception Handling 108
7.2 Adding Targets: Inheritance and Interfaces 109
7.2.1 The Pinball Target Interface 1097.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
III UNDERSTANDING INHERITANCE 125
8 Understanding Inheritance 127
8.1 An Intuitive Description of Inheritance 127
8.2 The Base Class Object 128
8.3 Subclass, Subtype, and Substitutability 129
8.4 Forms of Inheritance 130
8.4.1 Inheritance for Specialization 1318.4.2 Inheritance for Speci�cation 1318.4.3 Inheritance for Construction 1338.4.4 Inheritance for Extension 1358.4.5 Inheritance for Limitation 1368.4.6 Inheritance for Combination 1368.4.7 Summary of the Forms of Inheritance 137
8.5 Modi�ers and Inheritance 138
8.6 Programming as a Multiperson Activity 139
8.7 The Bene�ts of Inheritance 139
8.7.1 Software Reusability 1398.7.2 Increased Reliability 1398.7.3 Code Sharing 1408.7.4 Consistency of Interface 1408.7.5 Software Components 1408.7.6 Rapid Prototyping 1408.7.7 Polymorphism and Frameworks 1418.7.8 Information Hiding 141
8.8 The Costs of Inheritance 141
8.8.1 Execution Speed 1428.8.2 Program Size 1428.8.3 Message-Passing Overhead 1428.8.4 Program Complexity 142
8.9 Chapter Summary 143
Study Questions 143
Exercises 144
9 A Case Study: Solitaire 147
9.1 The Class Card 147
9.2 The Game 149
xii Contents
9.3 Card Piles|Inheritance in Action 152
9.3.1 The Suit Piles 1559.3.2 The Deck Pile 1559.3.3 The Discard Pile 1579.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 Mechanisms for Software Reuse 167
10.1 Substitutability 167
10.1.1 The Is-a Rule and the Has-a Rule 16910.1.2 Inheritance of Code and Inheritance of Behavior 169
10.2 Composition and Inheritance Described 170
10.2.1 Using Composition 17210.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 17810.5.2 Inheritance of Inner Classes 17910.5.3 Unnamed Classes 180
10.6 Chapter Summary 181
Study Questions 183
Exercises 183
11 Implications of Inheritance 185
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
IV UNDERSTANDING POLYMORPHISM 201
12 Polymorphism 203
12.1 Varieties of Polymorphism 203
12.2 Polymorphic Variables 204
12.3 Overloading 205
12.3.1 Overloading Messages in Real Life 20512.3.2 Overloading and Coercion 20512.3.3 Overloading from Separate Classes 20612.3.4 Parametric Overloading 207
12.4 Overriding 208
12.4.1 Replacement and Re�nement 208
12.5 Abstract Methods 210
12.6 Pure Polymorphism 210
12.7 E�ciency and Polymorphism 212
12.8 Chapter Summary 212
Further Reading 212
Study Questions 213
Exercises 214
13 The AWT 215
13.1 The AWT Class Hierarchy 215
13.2 The Layout Manager 218
13.2.1 Layout Manager Types 219
13.3 User Interface Components 221
13.3.1 Labels 22113.3.2 Button 22213.3.3 Canvas 223
xiv Contents
13.3.4 Scroll Bars 22313.3.5 Text Components 22413.3.6 Checkbox 22513.3.7 Checkbox Groups, Choices, and Lists 226
13.4 Panels 227
13.4.1 ScrollPane 229
13.5 Case Study: A Color Display 230
13.6 Dialogs 234
13.6.1 Example Program for Dialogs 235
13.7 The Menu Bar 235
13.7.1 A Quit Menu Facility 237
13.8 Chapter Summary 239
Study Questions 239
Exercises 240
14 Input and Output Streams 241
14.1 Streams versus Readers and Writers 241
14.2 Input Streams 242
14.2.1 Physical Input Streams 24314.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 Design Patterns 263
15.1 Adapter 263
15.2 Composite 264
15.3 Strategy 266
15.4 Observer 267
Contents xv
15.5 Flyweight 268
15.6 Abstract Factory 268
15.7 Factory Method 269
15.8 Iterator 270
15.9 Decorator (Filter or Wrapper) 271
15.10 Proxy 272
15.11 Bridge 273
15.12 Chapter Summary 273
Further Reading 273
Study Questions 273
Exercise 274
V UNDERSTANDING THE JAVA WORLD 275
16 Exception Handling 277
16.1 Information Transmitted to the Catch Block 279
16.2 Catching Multiple Errors 279
16.3 The Finally Clause 280
16.4 Termination or Resumptive Models 280
16.5 Exceptions Thrown in the Standard Library 281
16.6 Throwing Exceptions 282
16.7 Passing On Exceptions 283
16.8 Chapter Summary 284
Study Questions 284
Exercises 284
17 Utility Classes 285
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 29217.8.2 String Bu�ers 29517.8.3 String Tokenizers 29617.8.4 Parsing String Values 297
17.9 Chapter Summary 297
Study Questions 298
18 Understanding Graphics 299
18.1 Color 299
18.2 Rectangles 300
18.2.1 Rectangle Sample Program 301
18.3 Fonts 303
18.3.1 Font Metrics 30518.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 Collection Classes 319
19.1 Element Types and Primitive Value Wrappers 319
19.2 Enumerators 320
19.3 The Array 322
19.4 The Vector Collection 323
19.4.1 Using a Vector as an Array 32319.4.2 Using a Vector as a Stack 32519.4.3 Using a Vector as a Queue 32519.4.4 Using a Vector as a Set 32619.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 33119.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 Multiple Threads of Execution 341
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 34620.2.2 The PieceMover Thread 35020.2.3 The Game Piece Class 353
20.3 Chapter Summary 356
Cross References 356
Study Questions 356
Exercises 357
21 Applets and Web Programming 359
21.1 Applets and HTML 359
21.2 Security Issues 360
21.3 Applets and Applications 360
21.4 Obtaining Resources Using an Applet 362
21.4.1 Universal Resource Locators 36321.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
Exercises 366
22 Network Programming 367
22.1 Addresses, Ports, and Sockets 367
22.2 A Simple Client Server Program 369
22.3 Multiple Clients 372
22.4 Transmitting Objects over a Network 375
22.5 Providing More Complexity 380
22.6 Chapter Summary 381
Study Questions 381
Exercises 382
23 Whats new in 1.2 383
23.1 Collection Classes 384
23.2 Swing User Interface Components 384
23.3 Improvements to the Graphics Library 384
23.4 Internationalization 385
23.5 Java Beans 385
23.6 Sound 385
23.7 Data Bases 385
23.8 Remote Method Invocation 386
23.9 Servlets 386
23.10 Chapter Summary 386
23.11 Further Information 386
Glossary 387
30 Java Syntax 401
30.1 Program Structure 401
30.1.1 Import Declaration 40130.1.2 Class Declaration 40230.1.3 Interface declaration 40330.1.4 Method Declaration 40330.1.5 Constructors 40430.1.6 Data Field Declaration 405
Contents xix
30.2 Statements 405
30.2.1 Declaration statement 40530.2.2 Assignment Statement 40630.2.3 Procedure Calls 40630.2.4 If statement 40630.2.5 Switch Statement 40730.2.6 While Statement 40730.2.7 For Statement 40830.2.8 Return Statement 40830.2.9 Throw Statement 40830.2.10 Try Statement 409
30.3 Expressions 409
30.3.1 Literal 40930.3.2 Variable 41030.3.3 Data Field and Method Access 41130.3.4 Operators 41230.3.5 Object Creation 41230.3.6 Arrays 412
31 Packages in the Java API 415
Bibliography 417
Index 421