An Introduction To Object-Oriented Programming With Java

Transcription

wu23305 fm.qxd2/17/0910:38 AMPage iAn Introduction to Object-OrientedTMProgramming with JavaFifth EditionC.Thomas WuNaval Postgraduate School

wu23305 fm.qxd2/17/0910:38 AMPage iiAN INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING WITH JAVA , FIFTH EDITIONPublished by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of theAmericas, New York, NY 10020. Copyright 2010 by The McGraw-Hill Companies, Inc. All rights reserved.Previous editions 2006, 2004, and 2001. No part of this publication may be reproduced or distributed in anyform or by any means, or stored in a database or retrieval system, without the prior written consent of TheMcGraw-Hill Companies, Inc., including, but not limited to, in any network or other electronic storage ortransmission, or broadcast for distance learning.Some ancillaries, including electronic and print components, may not be available to customers outside theUnited States.This book is printed on acid-free paper.1 2 3 4 5 6 7 8 9 0 DOC/DOC 0 9ISBN 978–0–07–352330–9MHID 0–07–352330–5Global Publisher: Raghothaman SrinivasanDirector of Development: Kristine TibbettsDevelopmental Editor: Lorraine K. BuczekSenior Marketing Manager: Curt ReynoldsSenior Project Manager: Jane MohrLead Production Supervisor: Sandy LudovissyLead Media Project Manager: Stacy A. PatchAssociate Design Coordinator: Brenda A. RolwesCover Designer: Studio Montage, St. Louis, Missouri(USE) Cover Image: Getty ImagesCompositor: Macmillan Publishing SolutionsTypeface: 10.5/12 Times RomanPrinter: R. R. Donnelley Crawfordsville, INAll credits appearing on page or at the end of the book are considered to be an extension of the copyright page.Library of Congress Cataloging-in-Publication DataWu, C. Thomas.An introduction to object-oriented programming with Java / C. Thomas Wu (Otani).—5th ed.p. cm.Includes index.ISBN 978–0–07–352330–9— ISBN 0–07–352330–5 (hard copy : alk. paper) 1. Object-orientedprogramming (Computer science) 2. Java (Computer program language) I. Title.QA76.64.W78 2010005.1'17—dc222008053612www.mhhe.com

wu23305 fm.qxd2/17/0910:38 AMPage iiiTo my family

wu23305 fm.qxd2/17/0910:38 AMPage iv

wu23305 fm.qxd2/17/0910:38 AMPage .22.32.42.5xiIntroduction to Computers andProgramming LanguagesA History of ComputersComputer ArchitectureProgramming LanguagesJavaIntroduction to Object-Oriented Programming andSoftware DevelopmentClasses and ObjectsMessages and MethodsClass and Instance Data ValuesInheritanceSoftware Engineering and SoftwareLife CycleGetting Started with JavaThe First Java ProgramProgram ComponentsEdit-Compile-Run CycleSample Java Standard ClassesSample Development1241112151618202324293039495269v

wu23305 fm.qxdvi2/17/0910:38 AMPage 5.8Numerical Data85VariablesArithmetic ExpressionsConstantsDisplaying Numerical ValuesGetting Numerical InputThe Math ClassRandom Number GenerationThe GregorianCalendar ClassSample DevelopmentNumerical Representation (Optional)869499101107113117120125136Defining Your Own Classes—Part 1First Example: Defining and Using a ClassSecond Example: Defining and Using Multiple ClassesMatching Arguments and ParametersPassing Objects to a MethodConstructorsInformation Hiding and Visibility ModifiersClass ConstantsLocal VariablesCalling Methods of the Same ClassChanging Any Class to a Main ClassSample DevelopmentSelection StatementsThe if StatementNested if StatementsBoolean Expressions and VariablesComparing ObjectsThe switch StatementDrawing GraphicsEnumerated ConstantsSample 222233239247252256266272

wu23305 fm.qxd2/17/0910:38 AMPage etition StatementsThe while StatementPitfalls in Writing Repetition StatementsThe do–while StatementLoop-and-a-Half Repetition ControlThe for StatementNested for StatementsFormatting OutputLoan TablesEstimating the Execution TimeRecursive Methods (Optional)Sample DevelopmentDefining Your Own Classes—Part 2Returning an Object from a MethodThe Reserved Word thisOverloaded Methods and ConstructorsClass Variables and MethodsCall-by-Value Parameter PassingOrganizing Classes into a PackageUsing Javadoc Comments forClass DocumentationThe Complete Fraction ClassSample DevelopmentExceptions and AssertionsCatching ExceptionsThrowing Exceptions and Multiple catch BlocksPropagating ExceptionsTypes of ExceptionsProgrammer-Defined ExceptionsAssertionsSample 1477

wu23305 fm.qxdviii2/17/0910:38 AMPage haracters and StringsCharactersStringsPattern Matching and Regular ExpressionThe Pattern and Matcher ClassesComparing StringsStringBuffer and StringBuilderString Processing and BioinformaticsSample DevelopmentArrays and CollectionsArray BasicsArrays of ObjectsThe For-Each LoopPassing Arrays to MethodsTwo-Dimensional ArraysLists and MapsSample DevelopmentSorting and SearchingSearchingSortingHeapsortSample DevelopmentFile Input and OutputFile and JFileChooser ObjectsLow-Level File I/OHigh-Level File 6609633634638646659685686695700

wu23305 fm.qxd2/17/0910:38 AMPage ixContents12.412.513Object I/OSample DevelopmentInheritance and 713.8A Simple ExampleDefining Classes with InheritanceUsing Classes Effectively with PolymorphismInheritance and Member AccessibilityInheritance and ConstructorsAbstract Superclasses and Abstract MethodsInheritance versus InterfaceSample Development73473774174474975375875914GUI and Event-Driven Simple GUI I/O with JOptionPaneCustomizing Frame WindowsGUI Programming BasicsText-Related GUI ComponentsLayout ManagersEffective Use of Nested PanelsOther GUI ComponentsMenusHandling Mouse Events79079379980882083083985786115Recursive Algorithms88115.115.215.315.415.515.6Basic Elements of RecursionDirectory ListingAnagramTowers of HanoiQuicksortWhen Not to Use Recursion882883885888890895

wu23305 fm.qxdx2/17/0910:38 AMPage xContentsAppendix AHow to Run Java Programs903Appendix BSample Programs911Appendix CStandard Classes and Interfaces933Appendix DUML Diagrams955Index963

wu23305 fm.qxd2/17/0910:38 AMPage xiPrefaceThis book is an introduction to object-oriented programming using the Javaprogramming language. We use the object-first approach where objects are usedfrom the first sample program. Object-oriented thinking is emphasized and promoted from the beginning. Students learn how to use objects first and then learnhow to define their own objects.Key Changes in the 5th EditionThe key differences between this edition and the fourth edition are as follows:1. More Discussion on Java 5.0 Features and Java 6.0 Compatibility. Manyof the new Java 5.0 features are explained and used in the sample programs.They include the enumerator type, the for-each loop construct, auto boxingand unboxing, and the generics.2. Exclusive Use of Console Input and Output. All the GUI related topics,including the JOptionPane class, are moved to Chapter 14. Sample programsbefore Chapter 14 use the standard console input (Scanner) and output(System.out). Those who want to use JOptionPane for simple input and outputcan do so easily by covering Section 14.1 before Chapter 3.3. More Examples from Natural Sciences. In several key chapters, we illustrate concepts using examples from biology and chemistry. For example, inChapter 4, we use the elements in the periodic table to illustrate the concept ofprogrammer-defined classes. In Chapter 9, we demonstrate how the stringprocessing techniques are applied to implement DNA sequencing and othercommon DNA operations.4. Level-by-level Organization for Programming Exercises. Programmingexercises at the end of chapters are organized into three levels of difficulties.The one-star level exercises require the basic understanding of the materialscovered in the chapter. The two-star level exercises require some additionalthinking beyond the basic understanding. The three-star level exercises arexi

wu23305 fm.qxdxii2/17/0910:38 AMPage xiiPrefacemost difficult and require significant effort. For some of the three-star exercises, students must find or study additional information beyond those presented in the book. Please keep in mind that the level of difficulties is only ageneral guideline. One student may find some level-three exercises much easier than level-two exercises, for example.Book OrganizationThere are 16 chapters in this book, numbered from 0 to 15. The first 11 chapterscover the core topics that provide the fundamentals of programming. Chapters 11 to15 cover intermediate-level topics such as sorting, searching, recursion, inheritance,polymorphism, and file I/O. There are more than enough topics for one semester.After the first 11 chapters (Ch 0 to Ch 10), instructors can mix and match materialsfrom Chapters 11 to 15 to suit their needs. We first show the dependency relationships among the chapters and then provide a brief summary of each chapter.Chapter DependencyFor the most part, chapters should be read in sequence, but some variations arepossible, especially with the optional chapters. Here’s a simplified dependencygraph:01234567811 12 1391014* 15*Note: Some examples use arrays,but the use of arrays is not anintegral part of the examples.These examples can be modifiedto those that do not use arrays.Many topics from the early partof the chapter can be introducedas early as after Chapter 2.

wu23305 fm.qxd2/17/0910:38 AMPage xiiiPrefacexiiiBrief Chapter SummaryHere is a short description of each chapter: Chapter 0 is an optional chapter. We provide background information oncomputers and programming languages. This chapter can be skipped or assigned as an outside reading if you wish to start with object-oriented programming concepts. Chapter 1 provides a conceptual foundation of object-oriented programming.We describe the key components of object-oriented programming and illustrate each concept with a diagrammatic notation using UML. Chapter 2 covers the basics of Java programming and the process of editing,compiling, and running a program. From the first sample program presented inthis chapter, we emphasize object-orientation. We will introduce the standardclasses String, Date, and SimpleDateFormat so we can reinforce the notion ofobject declaration, creation, and usage. Moreover, by using these standardclasses, students can immediately start writing practical programs. We describeand illustrate console input with System.in and the Scanner class and output withSystem.out. Chapter 3 introduces variables, constants, and expressions for manipulatingnumerical data. We explain the standard Math class from java.lang andintroduce more standard classes (GregorianCalendar and DecimalFormat) tocontinually reinforce the notion of object-orientation. We describe additionalmethods of the Scanner class to input numerical values. Random numbergeneration is introduced in this chapter. The optional section explains how thenumerical values are represented in memory space. Chapter 4 teaches the basics of creating programmer-defined classes. Wekeep the chapter accessible by introducting only the fundamentals with illustrative examples. The key topics covered in this chapter are constructors, visibility modifiers (public and private), local variables, and passing data tomethods. We provide easy-to-grasp illustrations that capture the essence ofthe topics so the students will have a clear understanding of them. Chapter 5 explains the selection statements if and switch. We cover booleanexpressions and nested-if statements. We explain how objects are comparedby using equivalence ( ) and equality (the equals and compareTo methods).We use the String and the programmer-defined Fraction classes to make thedistinction between the equivalence and equality clear. Drawing 2-D graphicsis introduced, and a screensaver sample development program is developed.We describe the Java 5.0 feature called enumerated type in this chapter. Chapter 6 explains the repetition statements while, do–while, and for. Pitfallsin writing repetition statements are explained. One of the pitfalls to avoid isthe use of float or double for the data type of a counter variable. We illustratethis pitfall by showing a code that will result in infinite loop. Finding the greatest common divisor of two integers is used as an example of a nontrivial loopstatement. We show the difference between the straightforward (brute-force)and the clever (Euclid’s) solutions. We introduce the Formatter class and show

wu23305 fm.qxdxiv2/17/0910:38 AMPage xivPreface how the output can be aligned nicely. The optional last section of the chapterintroduces recursion as another technique for repetition. The recursive versionof a method that finds the greatest common divisor of two integers is given.Chapter 7 is the second part of creating programmer-defined classes. Weintroduce new topics related to the creation of programmer-defined classesand also repeat some of the topics covered in Chapter 4 in more depth. Thekey topics covered in this chapter are method overloading, the reservedword this, class methods and variables, returning an object from a method,and pass-by-value parameter passing. As in Chapter 4, we provide manylucid illustrations to make these topics accessible to beginners. We use theFraction class to illustrate many of these topics, such as the use of this andclass methods. The complete definition of the Fraction class is presented inthis chapter.Chapter 8 teaches exception handling and asserti

v Preface xi 0 Introduction to Computers and Programming Languages 1 0.1 A History of Computers 2 0.2 Computer Architecture 4 0.3 Programming Languages 11 0.4 Java 12 1 Introduction to Object-Oriented Programming and Software Development 15 1.1 Classes and Objects 16 1.2 Messages and Methods 18 1.3 Class and Instance Data Values 20 1.4 Inheritance 23 1.5 Software Engineering and Software