Σχόλια 0

Το κείμενο του εγγράφου

Introduction to Programming Using JavaVersion 5.0,December 2006(Version 5.1.2,with minor updates and corrections,December 2010)David J.EckHobart and William Smith CollegesThis is a PDF version of an on-line book that is available athttp://math.hws.edu/javanotes/.The PDF does not includesource code ﬁles,solutions to exercises,or answers to quizzes,butit does have external links to these resources,shown in blue.In addition,each section has a link to the on-line version.The PDF also has internal links,shown in red.These links canbe used in Acrobat Reader and some other PDF reader programs.iic 1996–2010,David J.EckDavid J.Eck (eck@hws.edu)Department of Mathematics and Computer ScienceHobart and William Smith CollegesGeneva,NY 14456This book can be distributed in unmodiﬁed form with no restrictions.Modiﬁed versions can be made and distributed provided they are distributedunder the same license as the original.More speciﬁcally:This work islicensed under the Creative Commons Attribution-Share Alike 2.5 License.To view a copy of this license,visit http://creativecommons.org/licenses/by-sa/2.5/or send a letter to Creative Commons,543 Howard Street,5thFloor,San Francisco,California,94105,USA.The web site for this book is:http://math.hws.edu/javanotesContentsPrefacex1 The Mental Landscape11.1 Machine Language...................................11.2 Asynchronous Events..................................31.3 The Java Virtual Machine...............................61.4 Building Blocks of Programs.............................81.5 Object-oriented Programming.............................91.6 The Modern User Interface..............................121.7 The Internet......................................14Quiz on Chapter 1......................................172 Names and Things182.1 The Basic Java Application..............................182.2 Variables and Types..................................212.2.1 Variables....................................222.2.2 Types and Literals...............................232.2.3 Variables in Programs.............................262.3 Objects and Subroutines................................272.3.1 Built-in Subroutines and Functions......................282.3.2 Operations on Strings.............................312.3.3 Introduction to Enums.............................332.4 Text Input and Output................................352.4.1 A First Text Input Example..........................362.4.2 Text Output..................................372.4.3 TextIO Input Functions............................382.4.4 Formatted Output...............................402.4.5 Introduction to File I/O............................422.5 Details of Expressions.................................432.5.1 Arithmetic Operators.............................442.5.2 Increment and Decrement...........................452.5.3 Relational Operators..............................452.5.4 Boolean Operators...............................462.5.5 Conditional Operator.............................472.5.6 Assignment Operators and Type-Casts....................472.5.7 Type Conversion of Strings..........................492.5.8 Precedence Rules................................492.6 Programming Environments..............................50iCONTENTS ii2.6.1 Java Development Kit.............................502.6.2 Command Line Environment.........................512.6.3 IDEs and Eclipse................................532.6.4 The Problem of Packages...........................55Exercises for Chapter 2...................................57Quiz on Chapter 2......................................593 Control603.1 Blocks,Loops,and Branches.............................603.1.1 Blocks......................................603.1.2 The Basic While Loop.............................613.1.3 The Basic If Statement............................633.2 Algorithm Development................................653.2.1 Pseudocode and Stepwise Reﬁnement....................653.2.2 The 3N+1 Problem..............................683.2.3 Coding,Testing,Debugging..........................713.3 while and do..while...................................723.3.1 The while Statement..............................733.3.2 The do..while Statement............................753.3.3 break and continue...............................773.4 The for Statement...................................783.4.1 For Loops....................................793.4.2 Example:Counting Divisors..........................823.4.3 Nested for Loops................................843.4.4 Enums and for-each Loops...........................863.5 The if Statement....................................883.5.1 The Dangling else Problem..........................883.5.2 The if...else if Construction..........................883.5.3 If Statement Examples.............................903.5.4 The Empty Statement.............................943.6 The switch Statement.................................953.6.1 The Basic switch Statement..........................953.6.2 Menus and switch Statements.........................963.6.3 Enums in switch Statements.........................973.6.4 Deﬁnite Assignment..............................983.7 Exceptions and try..catch...............................993.7.1 Exceptions...................................993.7.2 try..catch....................................1003.7.3 Exceptions in TextIO.............................1013.8 GUI Programming...................................103Exercises for Chapter 3...................................110Quiz on Chapter 3......................................1134 Subroutines1154.1 Black Boxes.......................................1154.2 Static Subroutines and Variables...........................1174.2.1 Subroutine Deﬁnitions.............................1174.2.2 Calling Subroutines..............................119CONTENTS iii4.2.3 Subroutines in Programs............................1204.2.4 Member Variables...............................1224.3 Parameters.......................................1254.3.1 Using Parameters................................1254.3.2 Formal and Actual Parameters........................1264.3.3 Overloading...................................1274.3.4 Subroutine Examples..............................1284.3.5 Throwing Exceptions..............................1304.3.6 Global and Local Variables..........................1314.4 Return Values......................................1324.4.1 The return statement.............................1324.4.2 Function Examples...............................1334.4.3 3N+1 Revisited.................................1364.5 APIs,Packages,and Javadoc.............................1384.5.1 Toolboxes....................................1384.5.2 Java’s Standard Packages...........................1394.5.3 Using Classes from Packages.........................1404.5.4 Javadoc.....................................1424.6 More on Program Design...............................1444.6.1 Preconditions and Postconditions.......................1444.6.2 A Design Example...............................1454.6.3 The Program..................................1494.7 The Truth About Declarations............................1514.7.1 Initialization in Declarations.........................1524.7.2 Named Constants...............................1534.7.3 Naming and Scope Rules...........................156Exercises for Chapter 4...................................159Quiz on Chapter 4......................................1625 Objects and Classes1635.1 Objects and Instance Methods............................1635.1.1 Objects,Classes,and Instances........................1645.1.2 Fundamentals of Objects...........................1655.1.3 Getters and Setters...............................1705.2 Constructors and Object Initialization........................1715.2.1 Initializing Instance Variables.........................1715.2.2 Constructors..................................1725.2.3 Garbage Collection...............................1775.3 Programming with Objects..............................1775.3.1 Some Built-in Classes.............................1785.3.2 Wrapper Classes and Autoboxing.......................1795.3.3 The class “Object”...............................1805.3.4 Object-oriented Analysis and Design.....................1815.4 Programming Example:Card,Hand,Deck......................1835.4.1 Designing the classes..............................1835.4.2 The Card Class.................................1855.4.3 Example:A Simple Card Game........................189CONTENTS iv5.5 Inheritance and Polymorphism............................1925.5.1 Extending Existing Classes..........................1925.5.2 Inheritance and Class Hierarchy.......................1945.5.3 Example:Vehicles...............................1955.5.4 Polymorphism.................................1985.5.5 Abstract Classes................................2005.6 this and super......................................2035.6.1 The Special Variable this...........................2035.6.2 The Special Variable super..........................2045.6.3 Constructors in Subclasses..........................2065.7 Interfaces,Nested Classes,and Other Details....................2075.7.1 Interfaces....................................2075.7.2 Nested Classes.................................2095.7.3 Anonymous Inner Classes...........................2125.7.4 Mixing Static and Non-static.........................2125.7.5 Static Import..................................2145.7.6 Enums as Classes................................215Exercises for Chapter 5...................................218Quiz on Chapter 5......................................2216 Introduction to GUI Programming2236.1 The Basic GUI Application..............................2236.1.1 JFrame and JPanel...............................2256.1.2 Components and Layout............................2276.1.3 Events and Listeners..............................2286.2 Applets and HTML..................................2296.2.1 JApplet.....................................2296.2.2 Reusing Your JPanels.............................2316.2.3 Basic HTML..................................2336.2.4 Applets on Web Pages.............................2366.3 Graphics and Painting.................................2386.3.1 Coordinates...................................2406.3.2 Colors......................................2416.3.3 Fonts......................................2426.3.4 Shapes......................................2436.3.5 Graphics2D...................................2446.3.6 An Example..................................2456.4 Mouse Events......................................2496.4.1 Event Handling.................................2506.4.2 MouseEvent and MouseListener........................2516.4.3 Mouse Coordinates...............................2546.4.4 MouseMotionListeners and Dragging.....................2566.4.5 Anonymous Event Handlers..........................2606.5 Timer and Keyboard Events..............................2626.5.1 Timers and Animation.............................2626.5.2 Keyboard Events................................2646.5.3 Focus Events..................................267CONTENTS v6.5.4 State Machines.................................2686.6 Basic Components...................................2716.6.1 JButton.....................................2736.6.2 JLabel......................................2746.6.3 JCheckBox...................................2756.6.4 JTextField and JTextArea...........................2766.6.5 JComboBox...................................2776.6.6 JSlider......................................2786.7 Basic Layout......................................2806.7.1 Basic Layout Managers............................2816.7.2 Borders.....................................2836.7.3 SliderAndComboBoxDemo..........................2856.7.4 A Simple Calculator..............................2876.7.5 Using a null Layout..............................2896.7.6 A Little Card Game..............................2916.8 Menus and Dialogs...................................2946.8.1 Menus and Menubars.............................2956.8.2 Dialogs.....................................2986.8.3 Fine Points of Frames.............................3006.8.4 Creating Jar Files...............................302Exercises for Chapter 6...................................304Quiz on Chapter 6......................................3097 Arrays3117.1 Creating and Using Arrays..............................3117.1.1 Arrays......................................3127.1.2 Using Arrays..................................3127.1.3 Array Initialization...............................3147.2 Programming With Arrays..............................3167.2.1 Arrays and for Loops.............................3167.2.2 Arrays and for-each Loops...........................3187.2.3 Array Types in Subroutines..........................3197.2.4 Random Access.................................3207.2.5 Arrays of Objects................................3227.2.6 Variable Arity Methods............................3257.3 Dynamic Arrays and ArrayLists............................3277.3.1 Partially Full Arrays..............................3277.3.2 Dynamic Arrays................................3307.3.3 ArrrayLists...................................3337.3.4 Parameterized Types..............................3377.3.5 Vectors.....................................3407.4 Searching and Sorting.................................3417.4.1 Searching....................................3417.4.2 Association Lists................................3437.4.3 Insertion Sort..................................3467.4.4 Selection Sort..................................3477.4.5 Unsorting....................................349CONTENTS vi7.5 Multi-dimensional Arrays...............................3507.5.1 Creating Two-dimensional Arrays......................3507.5.2 Using Two-dimensional Arrays........................3527.5.3 Example:Checkers...............................355Exercises for Chapter 7...................................362Quiz on Chapter 7......................................3688 Correctness and Robustness3708.1 Introduction to Correctness and Robustness.....................3708.1.1 Horror Stories..................................3718.1.2 Java to the Rescue...............................3728.1.3 Problems Remain in Java...........................3748.2 Writing Correct Programs...............................3758.2.1 Provably Correct Programs..........................3758.2.2 Robust Handling of Input...........................3788.3 Exceptions and try..catch...............................3828.3.1 Exceptions and Exception Classes......................3838.3.2 The try Statement...............................3858.3.3 Throwing Exceptions..............................3878.3.4 Mandatory Exception Handling........................3898.3.5 Programming with Exceptions........................3908.4 Assertions........................................3938.5 Introduction to Threads................................3968.5.1 Creating and Running Threads........................3978.5.2 Operations on Threads.............................4018.5.3 Mutual Exclusion with “synchronized”....................4028.5.4 Wait and Notify................................4058.5.5 Volatile Variables................................4098.6 Analysis of Algorithms.................................410Exercises for Chapter 8...................................416Quiz on Chapter 8......................................4219 Linked Data Structures and Recursion4239.1 Recursion........................................4239.1.1 Recursive Binary Search............................4249.1.2 Towers of Hanoi................................4269.1.3 A Recursive Sorting Algorithm........................4289.1.4 Blob Counting.................................4319.2 Linked Data Structures................................4359.2.1 Recursive Linking...............................4359.2.2 Linked Lists...................................4379.2.3 Basic Linked List Processing.........................4379.2.4 Inserting into a Linked List..........................4419.2.5 Deleting from a Linked List..........................4439.3 Stacks,Queues,and ADTs...............................4449.3.1 Stacks......................................4459.3.2 Queues.....................................4489.3.3 Postﬁx Expressions...............................452CONTENTS vii9.4 Binary Trees......................................4559.4.1 Tree Traversal.................................4569.4.2 Binary Sort Trees...............................4589.4.3 Expression Trees................................4639.5 A Simple Recursive Descent Parser..........................4669.5.1 Backus-Naur Form...............................4669.5.2 Recursive Descent Parsing...........................4689.5.3 Building an Expression Tree..........................472Exercises for Chapter 9...................................475Quiz on Chapter 9......................................47810 Generic Programming and Collection Classes48010.1 Generic Programming.................................48010.1.1 Generic Programming in Smalltalk......................48110.1.2 Generic Programming in C++........................48210.1.3 Generic Programming in Java.........................48310.1.4 The Java Collection Framework........................48410.1.5 Iterators and for-each Loops..........................48610.1.6 Equality and Comparison...........................48710.1.7 Generics and Wrapper Classes........................49010.2 Lists and Sets......................................49110.2.1 ArrayList and LinkedList...........................49110.2.2 Sorting.....................................49410.2.3 TreeSet and HashSet..............................49510.2.4 EnumSet....................................49810.3 Maps...........................................49910.3.1 The Map Interface...............................50010.3.2 Views,SubSets,and SubMaps........................50110.3.3 Hash Tables and Hash Codes.........................50410.4 Programming with the Collection Framework....................50610.4.1 Symbol Tables.................................50610.4.2 Sets Inside a Map...............................50710.4.3 Using a Comparator..............................51010.4.4 Word Counting.................................51210.5 Writing Generic Classes and Methods........................51410.5.1 Simple Generic Classes.............................51510.5.2 Simple Generic Methods............................51610.5.3 Type Wildcards................................51810.5.4 Bounded Types.................................522Exercises for Chapter 10...................................526Quiz on Chapter 10.....................................53011 Files and Networking53111.1 Streams,Readers,and Writers............................53111.1.1 Character and Byte Streams.........................53111.1.2 PrintWriter...................................53311.1.3 Data Streams..................................53411.1.4 Reading Text..................................535CONTENTS viii11.1.5 The Scanner Class...............................53811.1.6 Serialized Object I/O.............................53911.2 Files...........................................54011.2.1 Reading and Writing Files...........................54011.2.2 Files and Directories..............................54311.2.3 File Dialog Boxes................................54611.3 Programming With Files................................54811.3.1 Copying a File.................................54911.3.2 Persistent Data.................................55111.3.3 Files in GUI Programs.............................55311.3.4 Storing Objects in Files............................55511.4 Networking.......................................56211.4.1 URLs and URLConnections..........................56311.4.2 TCP/IP and Client/Server..........................56511.4.3 Sockets.....................................56611.4.4 A Trivial Client/Server............................56811.4.5 A Simple Network Chat............................57211.5 Network Programming and Threads.........................57511.5.1 A Threaded GUI Chat Program........................57611.5.2 A Multithreaded Server............................57911.5.3 Distributed Computing............................58211.6 A Brief Introduction to XML.............................59011.6.1 Basic XML Syntax...............................59011.6.2 XMLEncoder and XMLDecoder.......................59211.6.3 Working With the DOM............................594Exercises for Chapter 11...................................600Quiz on Chapter 11.....................................60312 Advanced GUI Programming60412.1 Images and Resources.................................60412.1.1 Images and BuﬀeredImages..........................60412.1.2 Working With Pixels..............................61012.1.3 Resources....................................61312.1.4 Cursors and Icons...............................61412.1.5 Image File I/O.................................61512.2 Fancier Graphics....................................61712.2.1 Measuring Text.................................61812.2.2 Transparency..................................62012.2.3 Antialiasing...................................62212.2.4 Strokes and Paints...............................62312.2.5 Transforms...................................62612.3 Actions and Buttons..................................62912.3.1 Action and AbstractAction..........................62912.3.2 Icons on Buttons................................63112.3.3 Radio Buttons.................................63212.3.4 Toolbars.....................................63512.3.5 Keyboard Accelerators.............................636CONTENTS ix12.3.6 HTML on Buttons...............................63812.4 Complex Components and MVC...........................63912.4.1 Model-View-Controller.............................63912.4.2 Lists and ListModels..............................64012.4.3 Tables and TableModels............................64312.4.4 Documents and Editors............................64712.4.5 Custom Components..............................64812.5 Finishing Touches...................................65312.5.1 The Mandelbrot Set..............................65312.5.2 Design of the Program.............................65512.5.3 Internationalization..............................65712.5.4 Events,Events,Events.............................65912.5.5 Custom Dialogs.................................66112.5.6 Preferences...................................662Exercises for Chapter 12...................................664Quiz on Chapter 12.....................................667Appendix:Source Files668PrefaceIntroduction to Programming Using Java is a free introductory computer programmingtextbook that uses Java as the language of instruction.It is suitable for use in an introductoryprogramming course and for people who are trying to learn programming on their own.Thereare no prerequisites beyond a general familiarity with the ideas of computers and programs.There is enough material for a full year of college-level programming.Chapters 1 through 7can be used as a textbook in a one-semester college-level course or in a year-long high schoolcourse.This version of the book covers “Java 5.0”.It also works well with later versions of Java.(While Java 5.0 introduced major new features that need to be covered in an introductoryprogramming course,Java 6.0 and the upcoming Java 7.0 do not.) Many of the examples inthe book use features that were not present before Java 5.0.Note that Java applets appearthroughout the pages of the on-line version of this book.Many of those applets will be non-functional in Web browsers that do not support Java 5.0.The home web site for this book ishttp://math.hws.edu/javanotes/.The page at thataddress contains links for downloading a copy of the web site and for downloading a PDFversion of the book.∗ ∗ ∗In style,this is a textbook rather than a tutorial.That is,it concentrates on explainingconcepts rather than giving step-by-step how-to-do-it guides.I have tried to use a conversationalwriting style that might be closer to classroom lecture than to a typical textbook.You’llﬁnd programming exercises at the end of most chapters,and you will ﬁnd a detailed solutionfor each exercise,with the sort of discussion that I would give if I presented the solution inclass.(Solutions to the exercises can be found in the on-line version only.) I strongly advisethat you read the exercise solutions if you want to get the most out of this book.This iscertainly not a Java reference book,and it is not even close to a comprehensive survey of allthe features of Java.It is not written as a quick introduction to Java for people who alreadyknow another programming language.Instead,it is directed mainly towards people who arelearning programming for the ﬁrst time,and it is as much about general programming conceptsas it is about Java in particular.I believe that Introduction to Programming using Java isfully competitive with the conventionally published,printed programming textbooks that areavailable on the market.(Well,all right,I’ll confess that I think it’s better.)There are several approaches to teaching Java.One approach uses graphical user interfaceprogramming from the very beginning.Some people believe that object oriented programmingshould also be emphasized from the very beginning.This is not the approach that I take.Theapproach that I favor starts with the more basic building blocks of programming and buildsfrom there.After an introductory chapter,I cover procedural programming in Chapters 2,3,and 4.Object-oriented programming is introduced in Chapter 5.Chapters 6 covers the closelyrelated topic of event-oriented programming and graphical user interfaces.Arrays are covered inxPreface xiChapter 7.Chapter 8 marks a turning point in the book,moving beyond the fundamental ideasof programming to cover more advanced topics.Chapter 8 is mostly about writing robust andcorrect programs,but it also has a section on parallel processing and threads.Chapters 9 and10 cover recursion and data structures,including the Java Collection Framework.Chapter 11 isabout ﬁles and networking.Finally,Chapter 12 returns to the topic of graphical user interfaceprogramming to cover some of Java’s more advanced capabilities.∗ ∗ ∗Major changes were made for the ﬁfth edition of this book.Perhaps the most signiﬁcantchange is the use of parameterized types in the chapter on generic programming.Parameterizedtypes—Java’s version of templates—were the most eagerly anticipated new feature in Java 5.0.Other new features in Java 5.0 are also covered.Enumerated types are introduced,althoughthey are not covered in their full complexity.The “for-each” loop is covered and is usedextensively.Formatted output is also used extensively,and the Scanner class is covered (thoughnot until Chapter 11).Static import is covered brieﬂy,as are variable arity methods.The non-standard TextIO class that I use for input in the ﬁrst half of the book has beenrewritten to support formatted output.I have also added some ﬁle I/O capabilities to this classto make it possible to cover some examples that use ﬁles early in the book.Javadoc comments are covered for the ﬁrst time in the ﬁfth edition.Almost all code exampleshave been revised to use Javadoc-style comments.The coverage of graphical user interface programming has been reorganized,much of it hasbeen rewritten,and new material has been added.In previous editions,I emphasized applets.Stand-alone GUI applications were covered at the end,almost as an afterthought.In the ﬁfthedition,the emphasis on applets is gone,and almost all examples are presented as stand-aloneapplications.However,applet versions of each example are still presented on the web pages ofthe on-line version of the book.The chapter on advanced GUI programming has been movedto the end,and a signiﬁcant amount of new material has been added,including coverage ofsome of the features of Graphics2D.Aside fromthe changes in content,the appearance of the book has been improved,especiallythe appearance of the PDF version.For the ﬁrst time,the quality of the PDF approaches thatof conventional textbooks.Version 5.1 of this book is a minor update of Version 5.0.A number of typographical andcoding errors in Version 5.0 have been corrected.Also,the discussion of the Eclipse IDE inSection 2.6 has been updated to be consistent with more recent versions of Eclipse.∗ ∗ ∗The latest complete edition of Introduction to Programming using Java is always availableon line athttp://math.hws.edu/javanotes/.The ﬁrst version of the book was written in 1996,and there have been several editions since then.All editions are archived at the following Webaddresses:• First edition:http://math.hws.edu/eck/cs124/javanotes1/(Covers Java 1.0.)• Second edition:http://math.hws.edu/eck/cs124/javanotes2/(Covers Java 1.1.)• Third edition:http://math.hws.edu/eck/cs124/javanotes3/(Covers Java 1.1.)• Fourth edition:http://math.hws.edu/eck/cs124/javanotes4/(Covers Java 1.4.)• Fifth edition:http://math.hws.edu/eck/cs124/javanotes5/(Covers Java 5.0.)Introduction to Programming using Java is free,but it is not in the public domain.As ofVersion 5.0,it is published under the terms of the Creative Commons Attribution-Share AlikePreface xii2.5 License.To viewa copy of this license,visithttp://creativecommons.org/licenses/by-sa/2.5/or send a letter to Creative Commons,543 Howard Street,5th Floor,San Francisco,Califor-nia,94105,USA.This license allows redistribution and modiﬁcation under certain terms.Forexample,you can:• Post an unmodiﬁed copy of the on-line version on your own Web site (including the partsthat list the author and state the license under which it is distributed!).• Give away or sell printed,unmodiﬁed copies of this book,as long as they meet the re-quirements of the license.• Make modiﬁed copies of the complete book or parts of it and post them on the web orotherwise distribute them,provided that attribution to the author is given,the modiﬁca-tions are clearly noted,and the modiﬁed copies are distributed under the same license asthe original.This includes translations to other languages.While it is not actually required by the license,I do appreciate hearing from people whoare using or distributing my work.∗ ∗ ∗A technical note on production:The on-line and PDF versions of this book are createdfrom a single source,which is written largely in XML.To produce the PDF version,the XMLis processed into a form that can be used by the TeX typesetting program.In addition to XMLﬁles,the source includes DTDs,XSLT transformations,Java source code ﬁles,image ﬁles,aTeX macro ﬁle,and a couple of scripts that are used in processing.I have made the complete source ﬁles available for download at the followingaddress:http://math.hws.edu/eck/cs124/downloads/javanotes5-full-source.zipThese ﬁles were not originally meant for publication,and therefore are not very cleanlywritten.Furthermore,it requires a fair amount of expertise to use them eﬀectively.However,I have had several requests for the sources and have made them available on an “as-is” basis.For more information about the source and how they are used see the README ﬁle from thesource download.∗ ∗ ∗Professor David J.EckDepartment of Mathematics and Computer ScienceHobart and William Smith CollegesGeneva,New York 14456,USAEmail:eck@hws.eduWWW:http://math.hws.edu/eck/Chapter 1Overview:The Mental LandscapeWhen you begin a journey,it’s a good idea to have a mental map of the terrain you’llbe passing through.The same is true for an intellectual journey,such as learning to writecomputer programs.In this case,you’ll need to know the basics of what computers are andhow they work.You’ll want to have some idea of what a computer program is and how one iscreated.Since you will be writing programs in the Java programming language,you’ll want toknow something about that language in particular and about the modern,networked computingenvironment for which Java is designed.As you read this chapter,don’t worry if you can’t understand everything in detail.(In fact,it would be impossible for you to learn all the details from the brief expositions in this chapter.)Concentrate on learning enough about the big ideas to orient yourself,in preparation for therest of the book.Most of what is covered in this chapter will be covered in much greater detaillater in the book.1.1 The Fetch and Execute Cycle:Machine LanguageA computer is a complex system consisting of many diﬀerent components.But at the(online)heart—or the brain,if you want—of the computer is a single component that does the actualcomputing.This is the Central Processing Unit,or CPU.In a modern desktop computer,the CPU is a single “chip” on the order of one square inch in size.The job of the CPU is toexecute programs.A program is simply a list of unambiguous instructions meant to be followed mechanicallyby a computer.A computer is built to carry out instructions that are written in a very simpletype of language called machine language.Each type of computer has its own machinelanguage,and the computer can directly execute a program only if the program is expressed inthat language.(It can execute programs written in other languages if they are ﬁrst translatedinto machine language.)When the CPU executes a program,that program is stored in the computer’s main mem-ory (also called the RAM or random access memory).In addition to the program,memorycan also hold data that is being used or processed by the program.Main memory consists of asequence of locations.These locations are numbered,and the sequence number of a locationis called its address.An address provides a way of picking out one particular piece of informa-tion from among the millions stored in memory.When the CPU needs to access the programinstruction or data in a particular location,it sends the address of that information as a sig-nal to the memory;the memory responds by sending back the data contained in the speciﬁed1CHAPTER 1.THE MENTAL LANDSCAPE 2location.The CPU can also store information in memory by specifying the information to bestored and the address of the location where it is to be stored.On the level of machine language,the operation of the CPU is fairly straightforward (al-though it is very complicated in detail).The CPU executes a program that is stored as asequence of machine language instructions in main memory.It does this by repeatedly reading,or fetching,an instruction from memory and then carrying out,or executing,that instruc-tion.This process—fetch an instruction,execute it,fetch another instruction,execute it,and soon forever—is called the fetch-and-execute cycle.With one exception,which will be coveredin the next section,this is all that the CPU ever does.The details of the fetch-and-execute cycle are not terribly important,but there are a fewbasic things you should know.The CPU contains a few internal registers,which are smallmemory units capable of holding a single number or machine language instruction.The CPUuses one of these registers—the program counter,or PC—to keep track of where it is in theprogram it is executing.The PC stores the address of the next instruction that the CPU shouldexecute.At the beginning of each fetch-and-execute cycle,the CPU checks the PC to see whichinstruction it should fetch.During the course of the fetch-and-execute cycle,the number in thePC is updated to indicate the instruction that is to be executed in the next cycle.(Usually,but not always,this is just the instruction that sequentially follows the current instruction inthe program.)∗ ∗ ∗A computer executes machine language programs mechanically—that is without under-standing them or thinking about them—simply because of the way it is physically put together.This is not an easy concept.A computer is a machine built of millions of tiny switches calledtransistors,which have the property that they can be wired together in such a way that anoutput from one switch can turn another switch on or oﬀ.As a computer computes,theseswitches turn each other on or oﬀ in a pattern determined both by the way they are wiredtogether and by the program that the computer is executing.Machine language instructions are expressed as binary numbers.A binary number is madeup of just two possible digits,zero and one.So,a machine language instruction is just a sequenceof zeros and ones.Each particular sequence encodes some particular instruction.The data thatthe computer manipulates is also encoded as binary numbers.A computer can work directlywith binary numbers because switches can readily represent such numbers:Turn the switch onto represent a one;turn it oﬀ to represent a zero.Machine language instructions are storedin memory as patterns of switches turned on or oﬀ.When a machine language instructionis loaded into the CPU,all that happens is that certain switches are turned on or oﬀ in thepattern that encodes that particular instruction.The CPU is built to respond to this patternby executing the instruction it encodes;it does this simply because of the way all the otherswitches in the CPU are wired together.So,you should understand this much about how computers work:Main memory holdsmachine language programs and data.These are encoded as binary numbers.The CPU fetchesmachine language instructions from memory one after another and executes them.It doesthis mechanically,without thinking about or understanding what it does—and therefore theprogramit executes must be perfect,complete in all details,and unambiguous because the CPUcan do nothing but execute it exactly as written.Here is a schematic view of this ﬁrst-stageunderstanding of the computer:CHAPTER 1.THE MENTAL LANDSCAPE 3Data to memoryData from memoryAddress forreading/writingdata1011100001Programcounter:CPUMemory(Location 0)(Location 1)(Location 2)(Location 3)(Location 10)00101110110100110101001100010000101111111010011011101001000001111010011000010001001111101.2 Asynchronous Events:Polling Loops and InterruptsThe CPU spends almost all of its time fetching instructions from memory and executing(online)them.However,the CPU and main memory are only two out of many components in a realcomputer system.A complete system contains other devices such as:• A hard disk for storing programs and data ﬁles.(Note that main memory holds only acomparatively small amount of information,and holds it only as long as the power is turnedon.A hard disk is necessary for permanent storage of larger amounts of information,butprograms have to be loaded from disk into main memory before they can actually beexecuted.)• A keyboard and mouse for user input.• A monitor and printer which can be used to display the computer’s output.• A modem that allows the computer to communicate with other computers over telephonelines.• A network interface that allows the computer to communicate with other computersthat are connected to it on a network.• A scanner that converts images into coded binary numbers that can be stored andmanipulated on the computer.The list of devices is entirely open ended,and computer systems are built so that they caneasily be expanded by adding new devices.Somehow the CPU has to communicate with andcontrol all these devices.The CPU can only do this by executing machine language instructions(which is all it can do,period).The way this works is that for each device in a system,thereis a device driver,which consists of software that the CPU executes when it has to dealwith the device.Installing a new device on a system generally has two steps:plugging thedevice physically into the computer,and installing the device driver software.Without thedevice driver,the actual physical device would be useless,since the CPU would not be able tocommunicate with it.CHAPTER 1.THE MENTAL LANDSCAPE 4∗ ∗ ∗A computer system consisting of many devices is typically organized by connecting thosedevices to one or more busses.A bus is a set of wires that carry various sorts of informationbetween the devices connected to those wires.The wires carry data,addresses,and controlsignals.An address directs the data to a particular device and perhaps to a particular registeror location within that device.Control signals can be used,for example,by one device to alertanother that data is available for it on the data bus.A fairly simple computer system mightbe organized like this:Input/OutputControllerData busAddress busControl busCPUEmpty Slotfor futureExpansionKeyboardNetworkInterface......Network CableVideoControllerandMonitorMemoryNow,devices such as keyboard,mouse,and network interface can produce input that needsto be processed by the CPU.How does the CPU know that the data is there?One simple idea,which turns out to be not very satisfactory,is for the CPU to keep checking for incoming dataover and over.Whenever it ﬁnds data,it processes it.This method is called polling,sincethe CPU polls the input devices continually to see whether they have any input data to report.Unfortunately,although polling is very simple,it is also very ineﬃcient.The CPU can wastean awful lot of time just waiting for input.To avoid this ineﬃciency,interrupts are often used instead of polling.An interrupt isa signal sent by another device to the CPU.The CPU responds to an interrupt signal byputting aside whatever it is doing in order to respond to the interrupt.Once it has handledthe interrupt,it returns to what it was doing before the interrupt occurred.For example,whenyou press a key on your computer keyboard,a keyboard interrupt is sent to the CPU.TheCPU responds to this signal by interrupting what it is doing,reading the key that you pressed,processing it,and then returning to the task it was performing before you pressed the key.Again,you should understand that this is a purely mechanical process:A device signals aninterrupt simply by turning on a wire.The CPU is built so that when that wire is turned on,the CPU saves enough information about what it is currently doing so that it can return tothe same state later.This information consists of the contents of important internal registerssuch as the program counter.Then the CPU jumps to some predetermined memory locationand begins executing the instructions stored there.Those instructions make up an interrupthandler that does the processing necessary to respond to the interrupt.(This interrupt handleris part of the device driver software for the device that signalled the interrupt.) At the end ofCHAPTER 1.THE MENTAL LANDSCAPE 5the interrupt handler is an instruction that tells the CPU to jump back to what it was doing;it does that by restoring its previously saved state.Interrupts allow the CPU to deal with asynchronous events.In the regular fetch-and-execute cycle,things happen in a predetermined order;everything that happens is “synchro-nized” with everything else.Interrupts make it possible for the CPU to deal eﬃciently withevents that happen “asynchronously,” that is,at unpredictable times.As another example of how interrupts are used,consider what happens when the CPU needsto access data that is stored on the hard disk.The CPU can access data directly only if it isin main memory.Data on the disk has to be copied into memory before it can be accessed.Unfortunately,on the scale of speed at which the CPU operates,the disk drive is extremelyslow.When the CPU needs data from the disk,it sends a signal to the disk drive telling itto locate the data and get it ready.(This signal is sent synchronously,under the control of aregular program.) Then,instead of just waiting the long and unpredictalble amount of timethat the disk drive will take to do this,the CPU goes on with some other task.When the diskdrive has the data ready,it sends an interrupt signal to the CPU.The interrupt handler canthen read the requested data.∗ ∗ ∗Now,you might have noticed that all this only makes sense if the CPU actually has severaltasks to perform.If it has nothing better to do,it might as well spend its time polling for inputor waiting for disk drive operations to complete.All modern computers use multitasking toperformseveral tasks at once.Some computers can be used by several people at once.Since theCPU is so fast,it can quickly switch its attention from one user to another,devoting a fractionof a second to each user in turn.This application of multitasking is called timesharing.But amodern personal computer with just a single user also uses multitasking.For example,the usermight be typing a paper while a clock is continuously displaying the time and a ﬁle is beingdownloaded over the network.Each of the individual tasks that the CPU is working on is called a thread.(Or a process;there are technical diﬀerences between threads and processes,but they are not important here.)At any given time,only one thread can actually be executed by a CPU.The CPU will continuerunning the same thread until one of several things happens:• The thread might voluntarily yield control,to give other threads a chance to run.• The thread might have to wait for some asynchronous event to occur.For example,thethread might request some data from the disk drive,or it might wait for the user to pressa key.While it is waiting,the thread is said to be blocked,and other threads have achance to run.When the event occurs,an interrupt will “wake up” the thread so that itcan continue running.• The thread might use up its allotted slice of time and be suspended to allow other threadsto run.Not all computers can “forcibly” suspend a thread in this way;those that canare said to use preemptive multitasking.To do preemptive multitasking,a computerneeds a special timer device that generates an interrupt at regular intervals,such as 100times per second.When a timer interrupt occurs,the CPU has a chance to switch fromone thread to another,whether the thread that is currently running likes it or not.Ordinary users,and indeed ordinary programmers,have no need to deal with interrupts andinterrupt handlers.They can concentrate on the diﬀerent tasks or threads that they want thecomputer to perform;the details of how the computer manages to get all those tasks done arenot important to them.In fact,most users,and many programmers,can ignore threads andCHAPTER 1.THE MENTAL LANDSCAPE 6multitasking altogether.However,threads have become increasingly important as computershave become more powerful and as they have begun to make more use of multitasking.Indeed,threads are built into the Java programming language as a fundamental programming concept.Just as important in Java and in modern programming in general is the basic concept ofasynchronous events.While programmers don’t actually deal with interrupts directly,theydo often ﬁnd themselves writing event handlers,which,like interrupt handlers,are calledasynchronously when speciﬁed events occur.Such “event-driven programming” has a verydiﬀerent feel from the more traditional straight-through,synchronous programming.We willbegin with the more traditional type of programming,which is still used for programmingindividual tasks,but we will return to threads and events later in the text.∗ ∗ ∗By the way,the software that does all the interrupt handling and the communication withthe user and with hardware devices is called the operating system.The operating system isthe basic,essential software without which a computer would not be able to function.Otherprograms,such as word processors and World Wide Web browsers,are dependent upon theoperating system.Common operating systems include Linux,DOS,Windows 2000,WindowsXP,and the Macintosh OS.1.3 The Java Virtual MachineMachine language consists of very simple instructions that can be executed directly by(online)the CPU of a computer.Almost all programs,though,are written in high-level programminglanguages such as Java,Pascal,or C++.A program written in a high-level language cannotbe run directly on any computer.First,it has to be translated into machine language.Thistranslation can be done by a programcalled a compiler.Acompiler takes a high-level-languageprogram and translates it into an executable machine-language program.Once the translationis done,the machine-language programcan be run any number of times,but of course it can onlybe run on one type of computer (since each type of computer has its own individual machinelanguage).If the program is to run on another type of computer it has to be re-translated,using a diﬀerent compiler,into the appropriate machine language.There is an alternative to compiling a high-level language program.Instead of using acompiler,which translates the programall at once,you can use an interpreter,which translatesit instruction-by-instruction,as necessary.An interpreter is a program that acts much like aCPU,with a kind of fetch-and-execute cycle.In order to execute a program,the interpreterruns in a loop in which it repeatedly reads one instruction from the program,decides what isnecessary to carry out that instruction,and then performs the appropriate machine-languagecommands to do so.One use of interpreters is to execute high-level language programs.For example,the pro-gramming language Lisp is usually executed by an interpreter rather than a compiler.However,interpreters have another purpose:they can let you use a machine-language program meant forone type of computer on a completely diﬀerent type of computer.For example,there is a pro-gram called “Virtual PC” that runs on Macintosh computers.Virtual PC is an interpreter thatexecutes machine-language programs written for IBM-PC-clone computers.If you run VirtualPC on your Macintosh,you can run any PC program,including programs written for Windows.(Unfortunately,a PC programwill run much more slowly than it would on an actual IBMclone.The problem is that Virtual PC executes several Macintosh machine-language instructions forCHAPTER 1.THE MENTAL LANDSCAPE 7each PC machine-language instruction in the program it is interpreting.Compiled programsare inherently faster than interpreted programs.)∗ ∗ ∗The designers of Java chose to use a combination of compilation and interpretation.Pro-grams written in Java are compiled into machine language,but it is a machine language fora computer that doesn’t really exist.This so-called “virtual” computer is known as the Javavirtual machine.The machine language for the Java virtual machine is called Java byte-code.There is no reason why Java bytecode could not be used as the machine language of areal computer,rather than a virtual computer.However,one of the main selling points of Java is that it can actually be used on anycomputer.All that the computer needs is an interpreter for Java bytecode.Such an interpretersimulates the Java virtual machine in the same way that Virtual PC simulates a PC computer.Of course,a diﬀerent Jave bytecode interpreter is needed for each type of computer,butonce a computer has a Java bytecode interpreter,it can run any Java bytecode program.Andthe same Java bytecode program can be run on any computer that has such an interpreter.This is one of the essential features of Java:the same compiled program can be run on manydiﬀerent types of computers.J a v aP r o g r a mCo m p i l e rJ a v aB y t e c o d eP r o g r a mJ a v a I n t e r p r e t e rf o r M a c O SJ a v a I n t e r p r e t e rf o r W i n d o w sJ a v a I n t e r p r e t e rf o r L i n u xWhy,you might wonder,use the intermediate Java bytecode at all?Why not just distributethe original Java program and let each person compile it into the machine language of whatevercomputer they want to run it on?There are many reasons.First of all,a compiler has tounderstand Java,a complex high-level language.The compiler is itself a complex program.AJava bytecode interpreter,on the other hand,is a fairly small,simple program.This makes iteasy to write a bytecode interpreter for a newtype of computer;once that is done,that computercan run any compiled Java program.It would be much harder to write a Java compiler for thesame computer.Furthermore,many Java programs are meant to be downloaded over a network.This leadsto obvious security concerns:you don’t want to download and run a program that will damageyour computer or your ﬁles.The bytecode interpreter acts as a buﬀer between you and theprogram you download.You are really running the interpreter,which runs the downloadedprogram indirectly.The interpreter can protect you from potentially dangerous actions on thepart of that program.I should note that there is no necessary connection between Java and Java bytecode.A pro-gram written in Java could certainly be compiled into the machine language of a real computer.And programs written in other languages could be compiled into Java bytecode.However,it isthe combination of Java and Java bytecode that is platform-independent,secure,and network-compatible while allowing you to program in a modern high-level object-oriented language.CHAPTER 1.THE MENTAL LANDSCAPE 8∗ ∗ ∗I should also note that the really hard part of platform-independence is providing a “Graph-ical User Interface”—with windows,buttons,etc.—that will work on all the platforms thatsupport Java.You’ll see more about this problem inSection 1.6.1.4 Fundamental Building Blocks of ProgramsThere are two basic aspects of programming:data and instructions.To work with(online)data,you need to understand variables and types;to work with instructions,you need tounderstand control structures and subroutines.You’ll spend a large part of the coursebecoming familiar with these concepts.A variable is just a memory location (or several locations treated as a unit) that has beengiven a name so that it can be easily referred to and used in a program.The programmer onlyhas to worry about the name;it is the compiler’s responsibility to keep track of the memorylocation.The programmer does need to keep in mind that the name refers to a kind of “box”in memory that can hold data,even if the programmer doesn’t have to know where in memorythat box is located.In Java and most other languages,a variable has a type that indicates what sort of datait can hold.One type of variable might hold integers—whole numbers such as 3,-7,and 0—while another holds ﬂoating point numbers—numbers with decimal points such as 3.14,-2.7,or 17.0.(Yes,the computer does make a distinction between the integer 17 and the ﬂoating-point number 17.0;they actually look quite diﬀerent inside the computer.) There could alsobe types for individual characters (’A’,’;’,etc.),strings (“Hello”,“A string can include manycharacters”,etc.),and less common types such as dates,colors,sounds,or any other type ofdata that a program might need to store.Programming languages always have commands for getting data into and out of variablesand for doing computations with data.For example,the following “assignment statement,”which might appear in a Java program,tells the computer to take the number stored in thevariable named “principal”,multiply that number by 0.07,and then store the result in thevariable named “interest”:interest = principal * 0.07;There are also “input commands” for getting data from the user or from ﬁles on the computer’sdisks and “output commands” for sending data in the other direction.These basic commands—for moving data from place to place and for performingcomputations—are the building blocks for all programs.These building blocks are combinedinto complex programs using control structures and subroutines.∗ ∗ ∗A program is a sequence of instructions.In the ordinary “ﬂow of control,” the computerexecutes the instructions in the sequence in which they appear,one after the other.However,this is obviously very limited:the computer would soon run out of instructions to execute.Control structures are special instructions that can change the ﬂow of control.There aretwo basic types of control structure:loops,which allow a sequence of instructions to be repeatedover and over,and branches,which allow the computer to decide between two or more diﬀerentcourses of action by testing conditions that occur as the program is running.For example,it might be that if the value of the variable “principal” is greater than 10000,then the “interest” should be computed by multiplying the principal by 0.05;if not,then theCHAPTER 1.THE MENTAL LANDSCAPE 9interest should be computed by multiplying the principal by 0.04.A program needs someway of expressing this type of decision.In Java,it could be expressed using the following “ifstatement”:if (principal > 10000)interest = principal * 0.05;elseinterest = principal * 0.04;(Don’t worry about the details for now.Just remember that the computer can test a conditionand decide what to do next on the basis of that test.)Loops are used when the same task has to be performed more than once.For example,if you want to print out a mailing label for each name on a mailing list,you might say,“Getthe ﬁrst name and address and print the label;get the second name and address and printthe label;get the third name and address and print the label—” But this quickly becomesridiculous—and might not work at all if you don’t know in advance how many names there are.What you would like to say is something like “While there are more names to process,get thenext name and address,and print the label.” A loop can be used in a program to express suchrepetition.∗ ∗ ∗Large programs are so complex that it would be almost impossible to write them if therewere not some way to break themup into manageable “chunks.” Subroutines provide one way todo this.A subroutine consists of the instructions for performing some task,grouped togetheras a unit and given a name.That name can then be used as a substitute for the whole set ofinstructions.For example,suppose that one of the tasks that your program needs to performis to draw a house on the screen.You can take the necessary instructions,make them intoa subroutine,and give that subroutine some appropriate name—say,“drawHouse()”.Thenanyplace in your program where you need to draw a house,you can do so with the singlecommand:drawHouse();This will have the same eﬀect as repeating all the house-drawing instructions in each place.The advantage here is not just that you save typing.Organizing your program into sub-routines also helps you organize your thinking and your program design eﬀort.While writingthe house-drawing subroutine,you can concentrate on the problem of drawing a house withoutworrying for the moment about the rest of the program.And once the subroutine is written,you can forget about the details of drawing houses—that problem is solved,since you have asubroutine to do it for you.A subroutine becomes just like a built-in part of the language whichyou can use without thinking about the details of what goes on “inside” the subroutine.∗ ∗ ∗Variables,types,loops,branches,and subroutines are the basis of what might be called“traditional programming.” However,as programs become larger,additional structure is neededto help deal with their complexity.One of the most eﬀective tools that has been found is object-oriented programming,which is discussed in the next section.1.5 Objects and Object-oriented ProgrammingPrograms must be designed.No one can just sit down at the computer and compose a(online)CHAPTER 1.THE MENTAL LANDSCAPE 10program of any complexity.The discipline called software engineering is concerned withthe construction of correct,working,well-written programs.The software engineer tends touse accepted and proven methods for analyzing the problem to be solved and for designing aprogram to solve that problem.During the 1970s and into the 80s,the primary software engineering methodology wasstructured programming.The structured programming approach to program design wasbased on the following advice:To solve a large problem,break the problem into several piecesand work on each piece separately;to solve each piece,treat it as a new problemwhich can itselfbe broken down into smaller problems;eventually,you will work your way down to problemsthat can be solved directly,without further decomposition.This approach is called top-downprogramming.There is nothing wrong with top-down programming.It is a valuable and often-used ap-proach to problem-solving.However,it is incomplete.For one thing,it deals almost entirelywith producing the instructions necessary to solve a problem.But as time went on,peoplerealized that the design of the data structures for a program was as least as important as thedesign of subroutines and control structures.Top-down programming doesn’t give adequateconsideration to the data that the program manipulates.Another problem with strict top-down programming is that it makes it diﬃcult to reusework done for other projects.By starting with a particular problem and subdividing it intoconvenient pieces,top-down programming tends to produce a design that is unique to thatproblem.It is unlikely that you will be able to take a large chunk of programming from anotherprogram and ﬁt it into your project,at least not without extensive modiﬁcation.Producinghigh-quality programs is diﬃcult and expensive,so programmers and the people who employthem are always eager to reuse past work.∗ ∗ ∗So,in practice,top-down design is often combined with bottom-up design.In bottom-updesign,the approach is to start “at the bottom,” with problems that you already know how tosolve (and for which you might already have a reusable software component at hand).Fromthere,you can work upwards towards a solution to the overall problem.The reusable components should be as “modular” as possible.Amodule is a component of alarger systemthat interacts with the rest of the systemin a simple,well-deﬁned,straightforwardmanner.The idea is that a module can be “plugged into” a system.The details of what goes oninside the module are not important to the system as a whole,as long as the module fulﬁlls itsassigned role correctly.This is called information hiding,and it is one of the most importantprinciples of software engineering.One common format for software modules is to contain some data,along with some sub-routines for manipulating that data.For example,a mailing-list module might contain a list ofnames and addresses along with a subroutine for adding a new name,a subroutine for printingmailing labels,and so forth.In such modules,the data itself is often hidden inside the module;a program that uses the module can then manipulate the data only indirectly,by calling thesubroutines provided by the module.This protects the data,since it can only be manipulatedin known,well-deﬁned ways.And it makes it easier for programs to use the module,since theydon’t have to worry about the details of how the data is represented.Information about therepresentation of the data is hidden.Modules that could support this kind of information-hiding became common in program-ming languages in the early 1980s.Since then,a more advanced form of the same idea hasmore or less taken over software engineering.This latest approach is called object-orientedCHAPTER 1.THE MENTAL LANDSCAPE 11programming,often abbreviated as OOP.The central concept of object-oriented programming is the object,which is a kind of modulecontaining data and subroutines.The point-of-view in OOP is that an object is a kind of self-suﬃcient entity that has an internal state (the data it contains) and that can respond tomessages (calls to its subroutines).A mailing list object,for example,has a state consistingof a list of names and addresses.If you send it a message telling it to add a name,it willrespond by modifying its state to reﬂect the change.If you send it a message telling it to printitself,it will respond by printing out its list of names and addresses.The OOP approach to software engineering is to start by identifying the objects involved ina problem and the messages that those objects should respond to.The program that results isa collection of objects,each with its own data and its own set of responsibilities.The objectsinteract by sending messages to each other.There is not much “top-down” in such a program,and people used to more traditional programs can have a hard time getting used to OOP.However,people who use OOP would claim that object-oriented programs tend to be bettermodels of the way the world itself works,and that they are therefore easier to write,easier tounderstand,and more likely to be correct.∗ ∗ ∗You should think of objects as “knowing” how to respond to certain messages.Diﬀerentobjects might respond to the same message in diﬀerent ways.For example,a “print” messagewould produce very diﬀerent results,depending on the object it is sent to.This property ofobjects—that diﬀerent objects can respond to the same message in diﬀerent ways—is calledpolymorphism.It is common for objects to bear a kind of “family resemblance” to one another.Objectsthat contain the same type of data and that respond to the same messages in the same waybelong to the same class.(In actual programming,the class is primary;that is,a class iscreated and then one or more objects are created using that class as a template.) But objectscan be similar without being in exactly the same class.For example,consider a drawing program that lets the user draw lines,rectangles,ovals,polygons,and curves on the screen.In the program,each visible object on the screen could berepresented by a software object in the program.There would be ﬁve classes of objects in theprogram,one for each type of visible object that can be drawn.All the lines would belong toone class,all the rectangles to another class,and so on.These classes are obviously related;all of them represent “drawable objects.” They would,for example,all presumably be able torespond to a “draw yourself” message.Another level of grouping,based on the data neededto represent each type of object,is less obvious,but would be very useful in a program:Wecan group polygons and curves together as “multipoint objects,” while lines,rectangles,andovals are “two-point objects.” (A line is determined by its endpoints,a rectangle by two of itscorners,and an oval by two corners of the rectangle that contains it.) We could diagram theserelationships as follows:CHAPTER 1.THE MENTAL LANDSCAPE 12D r a w a b l e O b j e c tM u l t i p o i n t O b j e c tT w o P o i n t O b j e c tP o l y g o nC u r v eL i n eR e c t a n g l eO v a lDrawableObject,MultipointObject,and TwoPointObject would be classes in the program.MultipointObject and TwoPointObject would be subclasses of DrawableObject.The classLine would be a subclass of TwoPointObject and (indirectly) of DrawableObject.A subclass ofa class is said to inherit the properties of that class.The subclass can add to its inheritance andit can even “override” part of that inheritance (by deﬁning a diﬀerent response to some method).Nevertheless,lines,rectangles,and so on are drawable objects,and the class DrawableObjectexpresses this relationship.Inheritance is a powerful means for organizing a program.It is also related to the problemof reusing software components.A class is the ultimate reusable component.Not only can itbe reused directly if it ﬁts exactly into a program you are trying to write,but if it just almostﬁts,you can still reuse it by deﬁning a subclass and making only the small changes necessaryto adapt it exactly to your needs.So,OOP is meant to be both a superior program-development tool and a partial solutionto the software reuse problem.Objects,classes,and object-oriented programming will beimportant themes throughout the rest of this text.1.6 The Modern User InterfaceWhen computers were first introduced,ordinary people—including most programmers—(online)couldn’t get near them.They were locked up in rooms with white-coated attendants who wouldtake your programs and data,feed them to the computer,and return the computer’s responsesome time later.When timesharing—where the computer switches its attention rapidly fromone person to another—was invented in the 1960s,it became possible for several people tointeract directly with the computer at the same time.On a timesharing system,users sit at“terminals” where they type commands to the computer,and the computer types back its re-sponse.Early personal computers also used typed commands and responses,except that therewas only one person involved at a time.This type of interaction between a user and a computeris called a command-line interface.Today,of course,most people interact with computers in a completely diﬀerent way.Theyuse a Graphical User Interface,or GUI.The computer draws interface components on thescreen.The components include things like windows,scroll bars,menus,buttons,and icons.Usually,a mouse is used to manipulate such components.Assuming that you have not justbeen teleported in fromthe 1970s,you are no doubt already familiar with the basics of graphicaluser interfaces!A lot of GUI interface components have become fairly standard.That is,they have similarappearance and behavior on many diﬀerent computer platforms including Macintosh,Windows,CHAPTER 1.THE MENTAL LANDSCAPE 13and Linux.Java programs,which are supposed to run on many diﬀerent platforms withoutmodiﬁcation to the program,can use all the standard GUI components.They might vary alittle in appearance from platform to platform,but their functionality should be identical onany computer on which the program runs.Shown below is an image of a very simple Java program—actually an “applet”,since it ismeant to appear on a Web page—that shows a few standard GUI interface components.Thereare four components that the user can interact with:a button,a checkbox,a text ﬁeld,and apop-up menu.These components are labeled.There are a few other components in the applet.The labels themselves are components (even though you can’t interact with them).The righthalf of the applet is a text area component,which can display multiple lines of text,and ascrollbar component appears alongside the text area when the number of lines of text becomeslarger than will ﬁt in the text area.And in fact,in Java terminology,the whole applet is itselfconsidered to be a “component.”Now,Java actually has two complete sets of GUI components.One of these,the AWT orAbstract Windowing Toolkit,was available in the original version of Java.The other,whichis known as Swing,is included in Java version 1.2 or later,and is used in preference to theAWT in most modern Java programs.The applet that is shown above uses components thatare part of Swing.If your Web browser uses an old version of Java,you might get an errorwhen the browser tries to load the applet.Remember that most of the applets in this textbookrequire Java 5.0 (or higher).When a user interacts with the GUI components in this applet,an “event” is generated.For example,clicking a push button generates an event,and pressing return while typing in atext ﬁeld generates an event.Each time an event is generated,a message is sent to the applettelling it that the event has occurred,and the applet responds according to its program.Infact,the program consists mainly of “event handlers” that tell the applet how to respond tovarious types of events.In this example,the applet has been programmed to respond to eachevent by displaying a message in the text area.The use of the term “message” here is deliberate.Messages,as you saw in the previous sec-tion,are sent to objects.In fact,Java GUI components are implemented as objects.Javaincludes many predeﬁned classes that represent various types of GUI components.Some ofthese classes are subclasses of others.Here is a diagram showing some of Swing’s GUI classesand their relationships:CHAPTER 1.THE MENTAL LANDSCAPE 14J C o m p o n e n tJ L a b e lJ A b s t r a c t B u t t o nJ C o m b o B o xJ T e x t C o m p o n e n tJ B u t t o nJ T o g g l e B u t t o nJ C h e c k B o xJ R a d i o B u t t o nJ S c r o l l b a rJ T e x t F i e l dJ T e x t A r e aDon’t worry about the details for now,but try to get some feel about how object-orientedprogramming and inheritance are used here