1. Trang chủ
  2. » Công Nghệ Thông Tin

java for programmeras 2nd edition

1,2K 1K 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.164
Dung lượng 22,15 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Features Here are the key features of Java for Programmers, 2/e: Java Standard Edition SE 7 • Easy to use as a Java SE 6 or Java SE 7 book.. Software Used in Java for Programmers, 2/e Al

Trang 2

J AVA ™ FOR P ROGRAMMERS

Trang 3

been printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty

of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests For more information, please contact:

U S Corporate and Government Sales

Visit us on the Web: informit.com/ph

Library of Congress Cataloging-in-Publication Data

On file

© 2012 Pearson Education, Inc.

All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmis- sion in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information re- garding permissions, write to:

Pearson Education, Inc.

Rights and Contracts Department

501 Boylston Street, Suite 900

Boston, MA 02116

Fax (617) 671-3447

ISBN-13: 978-0-13282154-4

ISBN-10: 0-13-282154-0

Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.

First printing, March 2012

Trang 4

J AVA ™ FOR P ROGRAMMERS

Deitel & Associates, Inc.

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City

Trang 5

Oracle and Java are registered trademarks of Oracle and/or its affiliates Other names may be trademarks

of their respective owners.

Microsoft, Internet Explorer and the Windows logo are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

UNIX is a registered trademark of The Open Group.

Apache is a trademark of The Apache Software Foundation.

CSS, XHTML and XML are registered trademarks of the World Wide Web Consortium.

Firefox is a registered trademark of the Mozilla Foundation.

Google is a trademark of Google, Inc.

Web 2.0 is a service mark of CMP Media.

Throughout this book, trademarks are used Rather than put a trademark symbol in every occurrence of

a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit

of the trademark owner, with no intention of infringement of the trademark.

Trang 6

In memory of Clifford “Spike” Stephens,

A dear friend who will be greatly missed.

Paul and Harvey Deitel

Trang 8

Preface xxi

3.2 Declaring a Class with a Method and Instantiating an Object of a Class 40

Contents

Trang 9

3.7 Floating-Point Numbers and Typedouble 56

Trang 10

Contents ix

8.4 Referring to the Current Object’s Members with thethisReference 193

9.4.3 Creating aCommissionEmployee–BasePlusCommissionEmployee

Trang 11

9.4.4 CommissionEmployee–BasePlusCommissionEmployeeInheritance

9.4.5 CommissionEmployee–BasePlusCommissionEmployeeInheritance

10.5.6 Polymorphic Processing, Operatorinstanceofand Downcasting 27310.5.7 Summary of the Allowed Assignments Between Superclass and

11.3 Example: HandlingArithmeticExceptions and

11.7 Stack Unwinding and Obtaining Information from an Exception Object 308

Trang 12

Contents xi

12 ATM Case Study, Part 1:

13 ATM Case Study Part 2:

Trang 13

14.3 Simple GUI-Based Input/Output withJOptionPane 401

14.6 Text Fields and an Introduction to Event Handling with Nested Classes 410

Trang 14

Contents xiii

17.5.1 Creating a Sequential-Access File Using Object Serialization 56317.5.2 Reading and Deserializing Data from a Sequential-Access File 569

17.6.2 Interfaces and Classes for Character-Based Input and Output 573

Trang 15

19.4 Additional Compile-Time Translation Issues: Methods That

20.7.1 Packaging theDrawTestApplet for Use with Java Web Start 661

Trang 16

Contents xv

23.9 Producer/Consumer Relationship: TheLockandConditionInterfaces 776

Trang 17

24 Networking 801

Trang 18

Contents xvii

28.6.1 Creating a Web Application Project and Adding a

28.6.4 Testing theWelcomeSOAPWeb Service with GlassFish

28.6.5 Describing a Web Service with the Web Service Description

28.6.6 Creating a Client to Consume theWelcomeSOAPWeb Service 973

Trang 19

28.9 Session Tracking in a SOAP Web Service 987

28.10.2 Creating a Web Application to Interact with the

F.4 Controlling Execution Using thestep,step upandnextCommands 1043

Trang 20

Contents xix

Trang 22

Live in fragments no longer, only connect.

—Edgar Morgan Foster

Welcome to Java and Java for Programmers, Second Edition! This book presents

leading-edge computing technologies for software developers

We focus on software engineering best practices At the heart of the book is the Deitelsignature “live-code approach”—concepts are presented in the context of completeworking programs, rather than in code snippets Each complete code example is accompa-nied by live sample executions All the source code is available at

As you read the book, if you have questions, send an e-mail todeitel@deitel.com;we’ll respond promptly For updates on this book, visit the website shown above, follow

us on Facebook (www.facebook.com/DeitelFan) and Twitter (@deitel), and subscribe to

the Deitel®Buzz Online newsletter (www.deitel.com/newsletter/subscribe.html)

Features

Here are the key features of Java for Programmers, 2/e:

Java Standard Edition (SE) 7

Easy to use as a Java SE 6 or Java SE 7 book We cover the new Java SE 7 features

in modular sections Here’s some of the new functionality:Strings inswitch

statements, the try-with-resources statement for managing AutoClosable jects, multi-catchfor defining a single exception handler to replace multiple ex-ception handlers that perform the same task and inferring the types of genericobjects from the variable they’re assigned to by using the<>notation We alsooverview the new concurrency API features

ob-• Java SE 7’s AutoClosable versions of Connection , Statement and ResultSet

With the source code for Chapter 25, Accessing Databases with JDBC, we vide a version of the chapter’s first example that’s implemented using Java SE 7’s

pro-AutoClosable versions of Connection, Statement andResultSet ableobjects reduce the likelihood of resource leaks when you use them with Java

AutoClos-SE 7’stry-with-resources statement, which automatically closes the ableobjects allocated in the parentheses following thetrykeyword

AutoClos-Object Technology

Object-oriented programming and design We review the basic concepts and

ter-minology of object technology in Chapter 1 Readers develop their first ized classes and objects in Chapter 3

custom-www.deitel.com/books/javafp2/

Preface

Trang 23

Exception handling We integrate basic exception handling early in the book and

cover it in detail in Chapter 11, Exception Handling: A Deeper Look

Class Arrays and ArrayList Chapter 7 covers class Arrays—which containsmethods for performing common array manipulations—and classArrayList—which implements a dynamically resizable array-like data structure

OO case studies The early classes and objects presentation featuresTime,

Employ-eeandGradeBookclass case studies that weave their way through multiple tions and chapters, gradually introducing deeper OO concepts

sec-• Case Study: Using the UML to Develop an Object-Oriented Design and Java plementation of an ATM The UML™ (Unified Modeling Language™) is the

Im-industry-standard graphical language for modeling object-oriented systems.Chapters 12–13 include a case study on object-oriented design using the UML

We design and implement the software for a simple automated teller machine(ATM) We analyze a typical requirements document that specifies the system to

be built We determine the classes needed to implement that system, the butes the classes need to have, the behaviors the classes need to exhibit and specifyhow the classes must interact with one another to meet the system requirements

attri-From the design we produce a complete Java implementation Readers often report

having a “light-bulb moment”—the case study helps them “tie it all together” andreally understand object orientation in Java

Reordered generics presentation We begin with generic classArrayListin

Chap-ter 7 Because you’ll understand basic generics concepts early in the book, our laChap-ter

data structures discussions provide a deeper treatment of generic collections—showing how to use the built-in collections of the Java API We then show how

to implement generic methods and classes

Database and Web Development

JDBC 4 Chapter 25, Accessing Databases with JDBC, covers JDBC 4 and uses

the Java DB/Apache Derby and MySQL database management systems Thechapter features an OO case study on developing a database-driven address bookthat demonstrates prepared statements and JDBC 4’s automatic driver discovery

Java Server Faces (JSF) 2.0 Chapters 26–27 have been updated with JavaServer

Faces (JSF) 2.0 technology, which greatly simplifies building JSF web tions Chapter 26 includes examples on building web application GUIs, validat-ing forms and session tracking Chapter 27 discusses data-driven and Ajax-enabled JSF applications The chapter features a database-driven multitier webaddress book that allows users to add and search for contacts

applica-• Web services Chapter 28, Web Services, demonstrates creating and consuming

SOAP- and REST-based web services Case studies include developing blackjack

and airline reservation web services

Java Web Start and the Java Network Launch Protocol (JNLP) We introduce

Java Web Start and JNLP, which enable applets and applications to be launched

via a web browser Users can install locally for later execution Programs can alsorequest the user’s permission to access local system resources such as files—en-

Trang 24

Teaching Approach xxiii

abling you to develop more robust applets and applications that execute safely ing Java’s sandbox security model, which applies to downloaded code

us-Multithreading

Multithreading We completely reworked Chapter 23, Multithreading [special

thanks to the guidance of Brian Goetz and Joseph Bowbeer—two of the

co-au-thors of Java Concurrency in Practice, Addison-Wesley, 2006].

SwingWorker class We use classSwingWorkerto create multithreaded user interfaces.

GUI and Graphics

GUI and graphics presentation Chapters 14, 15 and 22, and Appendix H

pres-ent Java GUI and Graphics programming

GroupLayout layout manager We discuss theGroupLayoutlayout manager in thecontext of the GUI design tool in the NetBeans IDE

JTable sorting and filtering capabilities Chapter 25 uses these capabilities to sort

the data in aJTableand filter it by regular expressions

Other Features

Android Because of the tremendous interest in Android-based smartphones and

tablets, we’ve included a three-chapter introduction to Android app developmentonline atwww.deitel.com/books/javafp These chapters are from our new Dei-

tel Developer Series book Android for Programmers: An App-Driven Approach After

you learn Java, you’ll find it straightforward to develop and run Android apps onthe free Android emulator that you can download fromdeveloper.android.com

Software engineering community concepts We discuss agile software

develop-ment, refactoring, design patterns, LAMP, SaaS (Software as a Service), PaaS(Platform as a Service), cloud computing, open-source software and more

Teaching Approach

Java for Programmers, 2/e, contains hundreds of complete working examples We stress

program clarity and concentrate on building well-engineered software

Syntax Shading For readability, we syntax shade the code, similar to the way most

inte-grated-development environments and code editors syntax color the code Our shading conventions are:

syntax-Code Highlighting We place gray rectangles around each program’s key code.

Using Fonts for Emphasis We place the key terms and the index’s page reference for each

defining occurrence in bold text for easier reference On-screen components are

empha-sized in thebold Helveticafont (e.g., theFilemenu) and Java program text in theLucida

font (e.g.,int x = 5;)

comments appear like this

keywords appear like this

constants and literal values appear like this

all other code appears in black

Trang 25

Web Access All of the source-code examples can be downloaded from:

Objectives The chapter opening quotations are followed by a list of chapter objectives Illustrations/Figures Abundant tables, line drawings, UML diagrams, programs and pro-

gram outputs are included

Programming Tips We include programming tips to help you focus on important aspects

of program development These tips and practices represent the best we’ve gleaned from acombined eight decades of programming and teaching experience

Thousands of Index Entries We’ve included a comprehensive index, which is especially

useful when you use the book as a reference

Software Used in Java for Programmers, 2/e

All the software you’ll need for this book is available free for download from the web Seethe Before You Begin section that follows the Preface for links to each download

www.deitel.com/books/javafp2

www.pearsonhighered.com/deitel

Good Programming Practice

The Good Programming Practices call attention to techniques that will help you duce programs that are clearer, more understandable and more maintainable.

pro-Common Programming Error

Pointing out these Common Programming Errors reduces the likelihood that you’ll make the same errors.

Error-Prevention Tip

These tips contain suggestions for exposing and removing bugs from your programs; many

of the tips describe aspects of Java that prevent bugs from getting into programs.

Performance Tip

These tips highlight opportunities for making your programs run faster or minimizing the amount of memory that they occupy.

Portability Tip

The Portability Tips help you write code that will run on a variety of platforms.

Software Engineering Observation

The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems.

Look-and-Feel Observation

These observations help you design attractive, user-friendly graphical user interfaces that conform to industry norms.

Trang 26

Discounts on Deitel Developer Series Books xxv

We wrote most of the examples in Java for Programmers, 2/e, using the free Java

Stan-dard Edition Development Kit (JDK) 6 For the Java SE 7 modules, we used theOpenJDK’s early access version of JDK 7 (download.java.net/jdk7/) In Chapters 26–

28, we also used the Netbeans IDE, and in Chapter 25, we used MySQL and MySQLConnector/J You can find additional resources and software downloads in our JavaResource Centers at:

Discounts on Deitel Developer Series Books

If you’d like to receive information on professional Deitel Developer Series titles, including

Android for Programmers: An App-Driven Approach, please register your copy of Java for Programmers, 2/e atinformit.com/register You’ll receive information on how to pur-

chase Android for Programmers at a discount.

Java Fundamentals: Parts I, II and III, Second Edition LiveLessons

Video Training Product

Our Java Fundamentals: Parts I, II and III, Second Edition LiveLessons video training

prod-uct shows you what you need to know to start building robust, powerful software with Java

It includes 20+ hours of expert training synchronized with Java for Programmers, 2/e Check

out our growing list of LiveLessons video products:

• Java Fundamentals I and II

• C# 2010 Fundamentals I, II, and III

• C# 2008 Fundamentals I and II

• C++ Fundamentals I and II

• iPhone App-Development Fundamentals I and II

• JavaScript Fundamentals I and II

• Visual Basic 2010 Fundamentals I and II

Coming Soon

• Java Fundamentals I, II and III, Second Edition

• C Fundamentals I and II

• Android App Development Fundamentals I and II

• iPhone and iPad App-Development Fundamentals I and II, Second Edition

For additional information about Deitel LiveLessons video products, visit:

Acknowledgments

We’d like to thank Abbey Deitel and Barbara Deitel for long hours devoted to this project.Barbara devoted long hours to Internet research to support our writing efforts Abbey wrotethe new engaging Chapter 1 and the new cover copy We’re fortunate to have worked onthis project with the dedicated team of publishing professionals at Pearson We appreciate

www.deitel.com/ResourceCenters.html

www.deitel.com/livelessons

Trang 27

the guidance, savvy and energy of Mark Taub, Editor-in-Chief of Computer Science JohnFuller managed the book’s production Sandra Schroeder did the cover design.

Reviewers

We wish to acknowledge the efforts of the reviewers who contributed to the recent editions

of this content They scrutinized the text and the programs and provided countless gestions for improving the presentation: Lance Andersen (Oracle), Soundararajan An-gusamy (Sun Microsystems), Joseph Bowbeer (Consultant), William E Duncan(Louisiana State University), Diana Franklin (University of California, Santa Barbara),Edward F Gehringer (North Carolina State University), Huiwei Guan (NorthshoreCommunity College), Ric Heishman (George Mason University), Dr Heinz Kabutz(JavaSpecialists.eu), Patty Kraft (San Diego State University), Lawrence Premkumar (SunMicrosystems), Tim Margush (University of Akron), Sue McFarland Metzger (VillanovaUniversity), Shyamal Mitra (The University of Texas at Austin), Peter Pilgrim (JavaChampion, Consultant), Manjeet Rege, Ph.D (Rochester Institute of Technology), Man-fred Riem (Java Champion, Consultant, Robert Half), Simon Ritter (Oracle), Susan Rod-ger (Duke University), Amr Sabry (Indiana University), José Antonio González Seco(Parliament of Andalusia), Sang Shin (Sun Microsystems), S Sivakumar (Astra InfotechPrivate Limited), Raghavan “Rags” Srinivas (Intuit), Monica Sweat (Georgia Tech), Vi-nod Varma (Astra Infotech Private Limited) and Alexander Zuev (Sun Microsystems).Well, there you have it! As you read the book, we’d appreciate your comments, criti-cisms, corrections and suggestions for improvement Please address all correspondence to:

sug-We’ll respond promptly We hope you enjoy working with Java for Programmers, 2/e.

Good luck!

Paul and Harvey Deitel

About the Authors

Paul J Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate

of MIT, where he studied Information Technology He holds the Sun (now Oracle) fied Java Programmer and Certified Java Developer certifications, and is an Oracle JavaChampion Through Deitel & Associates, Inc., he has delivered Java, C#, Visual Basic, C++,

Certi-C and Internet programming courses to industry clients, including Certi-Cisco, IBM, Sun systems, Dell, Siemens, Lucent Technologies, Fidelity, NASA at the Kennedy Space Center,the National Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software,Boeing, SunGard Higher Education, Stratus, Cambridge Technology Partners, One Wave,Hyperion Software, Adra Systems, Entergy, CableData Systems, Nortel Networks, Puma,iRobot, Invensys and many more He and his co-author, Dr Harvey M Deitel, are theworld’s best-selling programming-language textbook/professional book authors

Micro-Dr Harvey M Deitel, Chairman and Chief Strategy Officer of Deitel & Associates,

Inc., has 50 years of experience in the computer field Dr Deitel earned B.S and M.S.degrees from MIT and a Ph.D from Boston University He has extensive industry andacademic experience, including earning tenure and serving as the Chairman of the Com-puter Science Department at Boston College before founding Deitel & Associates, Inc.,

deitel@deitel.com

Trang 28

About Deitel & Associates, Inc xxvii

with his son, Paul J Deitel He and Paul are the co-authors of dozens of books and media packages and they are writing many more With translations published in Japanese,German, Russian, Chinese, Spanish, Korean, French, Polish, Italian, Portuguese, Greek,Urdu and Turkish, the Deitels’ texts have earned international recognition Dr Deitel hasdelivered hundreds of professional seminars to major corporations, academic institutions,government organizations and the military

multi-About Deitel & Associates, Inc.

Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationallyrecognized authoring, corporate training and software development organization specializ-ing in computer programming languages, object technology, Android and iPhone app de-velopment, and Internet and web software technology The company offers instructor-ledtraining courses delivered at client sites worldwide on major programming languages andplatforms, such as Java™, C, C++, Visual C#®, Visual Basic®, Objective-C, and iPhone andiPad app development, Android app development, XML®, Python®, object technology, In-ternet and web programming, and a growing list of additional programming and softwaredevelopment courses The company’s clients include many of the world’s largest companies,government agencies, branches of the military, and academic institutions

Through its 35-year publishing partnership with Prentice Hall/Pearson, Deitel &Associates, Inc., publishes leading-edge programming professional books, college text-

books, and LiveLessons DVD- and web-based video courses Deitel & Associates, Inc and

the authors can be reached at:

To learn more about Deitel’s Dive Into ® Series Corporate Training curriculum, visit:

subscribe to the free Deitel ® Buzz Online e-mail newsletter at:

and follow the authors on Facebook

and Twitter

To request a proposal for on-site, instructor-led training at your company or organization,e-mail

Individuals wishing to purchase Deitel books and LiveLessons DVD training courses

can do so throughwww.deitel.com Bulk orders by corporations, the government, themilitary and academic institutions should be placed directly with Pearson For more infor-mation, visitwww.pearsoned.com/professional/index.htm

Trang 30

This section contains information you should review before using this book and tions to ensure that your computer is set up properly for use with this book We’ll postupdates (if any) to the Before You Begin section on the book’s website:

instruc-Font and Naming Conventions

We use fonts to distinguish between on-screen components (such as menu names andmenu items) and Java code or commands Our convention is to emphasize on-screen com-ponents in a sans-serif boldHelveticafont (for example,Filemenu) and to emphasize Javacode and commands in a sans-serifLucidafont (for example,System.out.println())

Software Used in the Book

All the software you’ll need for this book is available free for download from the web

Java SE Software Development Kit (JDK) 6 and 7

We wrote most of the examples in Java for Programmers, 2/e, using the free Java Standard

Edition Development Kit (JDK) 6, which is available from:

For the Java SE 7 modules, we used the OpenJDK’s early access version of JDK 7, which

is available from:

Java DB, MySQL and MySQL Connector/J

In Chapter 25, we use the Java DB and MySQL Community Edition database ment systems Java DB is part of the JDK installation At the time of this writing, theJDK’s 64-bit installer was not properly installing Java DB If you are using the 64-bit ver-sion of Java, you may need to install Java DB separately You can download Java DB from:

manage-At the time of this writing, the latest release of MySQL Community Edition was5.5.8 To install MySQL Community Edition on Windows, Linux or Mac OS X, see theinstallation overview for your platform at:

Trang 31

Carefully follow the instructions for downloading and installing the software on your form The downloads are available from:

plat-You also need to install MySQL Connector/J (the J stands for Java), which allows grams to use JDBC to interact with MySQL MySQL Connector/J can be downloadedfrom

pro-At the time of this writing, the current generally available release of MySQL Connector/J

is 5.1.14 The documentation for Connector/J is located at

To install MySQL Connector/J, carefully follow the installation instructions at:

We do not recommend modifying your system’sCLASSPATHenvironment variable, which

is discussed in the installation instructions Instead, we’ll show you how use MySQL nector/J by specifying it as a command-line option when you execute your applications

Con-Obtaining the Code Examples

The examples for Java for Programmers, 2/e are available for download at

If you’re not already registered at our website, go towww.deitel.comand click theRegister

link below our logo in the upper-left corner of the page Fill in your information There’s

no charge to register, and we do not share your information with anyone We send you

only account-management e-mails unless you register separately for our free Deitel ® Buzz Online e-mail newsletter atwww.deitel.com/newsletter/subscribe.html After regis-

tering for the site, you’ll receive a confirmation e-mail with your verification code Click

the link in the confirmation e-mail to complete your registration Configure your e-mail client

to allow e-mails fromdeitel.comto ensure that the confirmation email is not filtered asjunk mail

Next, go towww.deitel.comand sign in using theLoginlink below our logo in theupper-left corner of the page Go to www.deitel.com/books/javafp2/ You’ll find thelink to download the examples under the headingDownload Code Examples and Other Pre- mium Content for Registered Users Write down the location where you choose to save theZIP file on your computer We assume the examples are located atC:\Exampleson yourcomputer

Setting the PATH Environment Variable

ThePATHenvironment variable on your computer designates which directories the puter searches when looking for applications, such as the applications that enable you tocompile and run your Java applications (calledjavacandjava, respectively) Carefully fol-

com-low the installation instructions for Java on your platform to ensure that you set the PATH ronment variable correctly.

Trang 32

Setting the CLASSPATH Environment Variable xxxi

If you do not set the PATHvariable correctly, when you use the JDK’s tools, you’llreceive a message like:

In this case, go back to the installation instructions for setting thePATHand recheck yoursteps If you’ve downloaded a newer version of the JDK, you may need to change the name

of the JDK’s installation directory in thePATHvariable

Setting the CLASSPATH Environment Variable

If you attempt to run a Java program and receive a message like

then your system has aCLASSPATHenvironment variable that must be modified To fix thepreceding error, follow the steps in setting thePATHenvironment variable, to locate the

CLASSPATHvariable, then edit the variable’s value to include the local directory—typicallyrepresented as a dot (.) On Windows add

at the beginning of theCLASSPATH’s value (with no spaces before or after these characters)

On other platforms, replace the semicolon with the appropriate path separator ters—often a colon (:)

charac-Java’s Nimbus Look-and-Feel

Java comes bundled with an elegant, cross-platform look-and-feel known as Nimbus Forprograms with graphical user interfaces, we’ve configured our systems to use Nimbus asthe default look-and-feel

To set Nimbus as the default for all Java applications, you must create a text filenamedswing.propertiesin thelibfolder of both your JDK installation folder and yourJRE installation folder Place the following line of code in the file:

For more information on locating these installation folders visitjava.sun.com/javase/ 6/webnotes/install/index.html [Note: In addition to the standalone JRE, there’s a

JRE nested in your JDK’s installation folder If you’re using an IDE that depends on theJDK (e.g., NetBeans), you may also need to place theswing.propertiesfile in the nested

jrefolder’slibfolder.]

'java' is not recognized as an internal or external command,

operable program or batch file.

Exception in thread "main" java.lang.NoClassDefFoundError: YourClass

.;

swing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel

Trang 34

1 Introduction

O b j e c t i v e s

In this chapter you’ll learn:

I Exciting recent developments in the computer field

I Basic object-technology concepts

I A typical Java program-development environment

I To test-drive a Java application

I Some key recent software technologies

Man is still the most

How wonderful it is that

nobody need wait a single

moment before starting to

improve the world.

—Anne Frank

Trang 35

1.1 Introduction

Welcome to Java—the world’s most widely used computer programming language In this

book, you’ll learn object-oriented programming—today’s key programming methodology You’ll create and work with many software objects in this text.

Java is the preferred language for meeting many organizations’ enterprise ming needs Java has also become the language of choice for implementing Internet-basedapplications and software for devices that communicate over a network

program-In use today are more than a billion general-purpose computers and billions moreJava-enabled cell phones, smartphones and handheld devices (such as tablet computers).According to a study by eMarketer, the number of mobile Internet users will reach approx-imately 134 million by 2013.1Other studies have projected smartphone sales to surpasspersonal computer sales in 20112and tablet sales to account for over 20% of all personalcomputer sales by 2015.3By 2014, the smartphone applications market is expected toexceed $40 billion,4which is creating significant opportunities for programming mobileapplications

Java Editions: SE, EE and ME

Java for Programmers, Second Edition is based on Java Standard Edition 6 (Java SE 6) and

Java SE 7 Java is used in such a broad spectrum of applications that it has two other editions The Java Enterprise Edition (Java EE), which we use later in the book, is geared toward de-

veloping large-scale, distributed networking applications and web-based applications

The Java Micro Edition (Java ME) is geared toward developing applications for

small, memory-constrained devices, such as BlackBerry smartphones Google’s Androidoperating system—used on numerous smartphones, tablets (small, lightweight mobilecomputers with touch screens), e-readers and other devices—uses a customized version ofJava not based on Java ME

1.2 Introduction to Object Technology

Building software quickly, correctly and economically remains an elusive goal at a time

when demands for new and more powerful software are soaring Objects, or more ly—as we’ll see in Chapter 3—the classes objects come from, are essentially reusable soft-

precise-ware components There are date objects, time objects, audio objects, video objects,

1.1 Introduction

1.2 Introduction to Object Technology

1.3 Open Source Software

1.4 Java and a Typical Java Development

Environment

1.5 Test-Driving a Java Application

1.6 Web 2.0: Going Social

Trang 36

1.2 Introduction to Object Technology 3

automobile objects, people objects, etc Almost any noun can be reasonably represented as

a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g.,

cal-culating, moving and communicating) Software developers are discovering that using amodular, object-oriented design and implementation approach can make software-devel-opment groups much more productive than was possible with earlier popular techniqueslike “structured programming”—object-oriented programs are often easier to understand,correct and modify

The Automobile as an Object

To help you understand objects and their contents, let’s begin with a simple analogy

Sup-pose you want to drive a car and make it go faster by pressing its accelerator pedal What must happen before you can do this? Well, before you can drive a car, someone has to design it.

A car typically begins as engineering drawings, similar to the blueprints that describe the

design of a house These drawings include the design for an accelerator pedal The pedal

hides from the driver the complex mechanisms that actually make the car go faster, just as

the brake pedal hides the mechanisms that slow the car, and the steering wheel “hides” themechanisms that turn the car This enables people with little or no knowledge of how en-gines, braking and steering mechanisms work to drive a car easily

Just as you cannot cook meals in the kitchen of a blueprint, you cannot drive a car’s

engineering drawings Before you can drive a car, it must be built from the engineering drawings that describe it A completed car has an actual accelerator pedal to make the car

go faster, but even that’s not enough—the car won’t accelerate on its own (hopefully!), so

the driver must press the pedal to accelerate the car.

Methods and Classes

Let’s use our car example to introduce some key object-oriented programming concepts

Performing a task in a program requires a method The method houses the program

state-ments that actually perform its tasks The method hides these statestate-ments from its user, just

as the accelerator pedal of a car hides from the driver the mechanisms of making the car

go faster In Java, we create a program unit called a class to house the set of methods that

perform the class’s tasks For example, a class that represents a bank account might contain

one method to deposit money to an account, another to withdraw money from an account and a third to inquire what the account’s current balance is A class is similar in concept to

a car’s engineering drawings, which house the design of an accelerator pedal, steeringwheel, and so on

Instantiation

Just as someone has to build a car from its engineering drawings before you can actually drive a car, you must build an object of a class before a program can perform the tasks that the class’s methods define The process of doing this is called instantiation An object is

then referred to as an instance of its class.

Reuse

Just as a car’s engineering drawings can be reused many times to build many cars, you can

reuse a class many times to build many objects Reuse of existing classes when building new

classes and programs saves time and effort Reuse also helps you build more reliable andeffective systems, because existing classes and components often have gone through exten-

Trang 37

sive testing, debugging and performance tuning Just as the notion of interchangeable parts

was crucial to the Industrial Revolution, reusable classes are crucial to the software tion that has been spurred by object technology

revolu-Messages and Methods Calls

When you drive a car, pressing its gas pedal sends a message to the car to perform a task— that is, to go faster Similarly, you send messages to an object Each message is implemented

as a method call that tells a method of the object to perform its task For example, a

pro-gram might call a particular bank account object’s deposit method to increase the account’s

balance

Attributes and Instance Variables

A car, besides having capabilities to accomplish tasks, also has attributes, such as its color,

its number of doors, the amount of gas in its tank, its current speed and its record of totalmiles driven (i.e., its odometer reading) Like its capabilities, the car’s attributes are repre-sented as part of its design in its engineering diagrams (which, for example, include anodometer and a fuel gauge) As you drive an actual car, these attributes are carried along

with the car Every car maintains its own attributes For example, each car knows how much gas is in its own gas tank, but not how much is in the tanks of other cars.

An object, similarly, has attributes that it carries along as it’s used in a program Theseattributes are specified as part of the object’s class For example, a bank account object has

a balance attribute that represents the amount of money in the account Each bank account object knows the balance in the account it represents, but not the balances of the other

accounts in the bank Attributes are specified by the class’s instance variables.

Encapsulation

Classes encapsulate (i.e., wrap) attributes and methods into objects—an object’s attributes

and methods are intimately related Objects may communicate with one another, butthey’re normally not allowed to know how other objects are implemented—implementa-

tion details are hidden within the objects themselves This information hiding, as we’ll see,

is crucial to good software engineering

Inheritance

A new class of objects can be created quickly and conveniently by inheritance—the new

class absorbs the characteristics of an existing class, possibly customizing them and addingunique characteristics of its own In our car analogy, an object of class “convertible” cer-

tainly is an object of the more general class “automobile,” but more specifically, the roof can

be raised or lowered

Object-Oriented Analysis and Design (OOAD)

Soon you’ll be writing programs in Java How will you create the code (i.e., the program

instructions) for your programs? Perhaps, like many programmers, you’ll simply turn onyour computer and start typing This approach may work for small programs (like the ones

Software Engineering Observation 1.1

Use a building-block approach to creating your programs Avoid reinventing the wheel— use existing pieces wherever possible This software reuse is a key benefit of object-oriented programming.

Trang 38

1.3 Open Source Software 5

we present in the early chapters of the book), but what if you were asked to create a ware system to control thousands of automated teller machines for a major bank? Or sup-pose you were asked to work on a team of 1,000 software developers building the next U.S.air traffic control system? For projects so large and complex, you should not simply sitdown and start writing programs

soft-To create the best solutions, you should follow a detailed analysis process for

deter-mining your project’s requirements (i.e., defining what the system is supposed to do) and developing a design that satisfies them (i.e., deciding how the system should do it) Ideally,

you’d go through this process and carefully review the design (and have your designreviewed by other software professionals) before writing any code If this process involvesanalyzing and designing your system from an object-oriented point of view, it’s called an

object-oriented analysis and design (OOAD) process Languages like Java are object ented Programming in such a language, called object-oriented programming (OOP),

ori-allows you to implement an object-oriented design as a working system

The UML (Unified Modeling Language)

Many different OOAD processes exist, but a single graphical language for communicating

the results of any OOAD process has come into wide use This language, known as the

Uni-fied Modeling Language (UML), is now the most widely used graphical scheme for ing object-oriented systems We present our first UML diagrams in Chapters 3 and 4, thenuse them in our deeper treatment of object-oriented programming through Chapter 11 Inour ATM Software Engineering Case Study in Chapters 12–13 we present a simple subset

model-of the UML’s features as we guide you through an object-oriented design experience

1.3 Open Source Software

The Linux operating system is perhaps the greatest success of the open-source movement.

Open-source software is a software development style that departs from the proprietary

de-velopment that dominated software’s early years With open-source dede-velopment, uals and companies contribute their efforts in developing, maintaining and evolvingsoftware in exchange for the right to use that software for their own purposes, typically at

individ-no charge Open-source code is often scrutinized by a much larger audience than etary software, so errors often get removed faster Open source also encourages more in-novation Sun open sourced its implementation of the Java Development Kit and many

propri-of its related Java technologies

Some organizations in the open-source community are the Eclipse Foundation (theEclipse Integrated Development Environment helps Java programmers convenientlydevelop software), the Mozilla Foundation (creators of the Firefox web browser), theApache Software Foundation (creators of the Apache web server used to develop web-based applications) and SourceForge (which provides the tools for managing open sourceprojects—it has over 260,000 of them under development) Rapid improvements to com-puting and communications, decreasing costs and open-source software have made itmuch easier and more economical to create a software-based business now than just a fewdecades ago A great example is Facebook, which was launched from a college dorm roomand built with open-source software.5

5 developers.facebook.com/opensource/

Trang 39

The Linux kernel is the core of the operating system It’s developed by a loosely

orga-nized team of volunteers, and is popular in servers, personal computers and embedded tems Unlike that of proprietary operating systems like Microsoft’s Windows and Apple’sMac OS X, Linux source code (the program code) is available to the public for examina-tion and modification and is free to download and install As a result, users of the operatingsystem benefit from a community of developers actively debugging and improving thekernel, an absence of licensing fees and restrictions, and the ability to completely cus-tomize the operating system to meet specific needs

sys-A variety of issues—such as Microsoft’s market power, the small number of friendly Linux applications and the diversity of Linux distributions, such as Red HatLinux, Ubuntu Linux and many others—have prevented widespread Linux use ondesktop computers But Linux has become extremely popular on servers and in embeddedsystems, such as Google’s Android-based smartphones

user-Android

Android—the fastest growing mobile and smartphone operating system—is based on the

Linux kernel and Java Experienced Java programmers can quickly dive into Android velopment One benefit of developing Android apps is the openness of the platform Theoperating system is open source and free

de-The Android operating system was developed by Android, Inc., which was acquired

by Google in 2005 In 2007, the Open Handset Alliance™—a consortium of 34 nies initially and 79 by 2010—was formed to continue developing Android As ofDecember 2010, more than 300,000 Android smartphones were being activated eachday!6Android smartphones are now outselling iPhones.7The Android operating system isused in numerous smartphones (such as the Motorola Droid, HTC EVO™ 4G, SamsungVibrant™ and many more), e-reader devices (such as the Barnes and Noble Nook™),tablet computers (such as the Motorola Xoom, the Dell Streak, the Samsung Galaxy Taband more), in-store touch-screen kiosks, cars, robots and multimedia players

compa-Android smartphones include the functionality of a mobile phone, Internet client (forweb browsing and Internet communication), MP3 player, gaming console, digital camera

and more, wrapped into handheld devices with full-color multitouch screens—these allow you to control the device with gestures involving one touch or multiple simultaneous

touches You can download apps directly onto your Android device through AndroidMarket and other app marketplaces As of early 2011, there were over 280,000 apps inGoogle’s Android Market

Android App-Development Chapters on the Companion Website

Because of the tremendous interest in Android-based devices and apps, we’ve included onthe book’s website a three-chapter introduction to Android app development from our

new book, Android for Programmers: An App-Driven Approach After you learn Java, you’ll

find it straightforward to begin developing and running Android apps You can place yourapps on the online Android Market (www.market.android.com)

6 www.pcmag.com/article2/0,2817,2374076,00.asp

7 mashable.com/2010/08/02/android-outselling-iphone-2/

Trang 40

1.4 Java and a Typical Java Development Environment 7

1.4 Java and a Typical Java Development Environment

The microprocessor revolution’s most important contribution to date is that it made sible the development of personal computers Microprocessors are having a profound im-pact in intelligent consumer-electronic devices Recognizing this, Sun Microsystems in

pos-1991 funded an internal corporate research project led by James Gosling, which resulted

in a C++-based object-oriented programming language Sun called Java

A key goal of Java is to be able to write programs that will run on a great variety ofcomputer systems and computer-control devices This is sometimes called “write once,run anywhere.”

The web exploded in popularity in 1993, and Sun saw the potential of using Java to

add dynamic content, such as interactivity and animations, to web pages Java garnered the

attention of the business community because of the phenomenal interest in the web Java

is now used to develop large-scale enterprise applications, to enhance the functionality ofweb servers (the computers that provide the content we see in our web browsers), to pro-vide applications for consumer devices (e.g., cell phones, smartphones, television set-topboxes and more) and for many other purposes Sun Microsystems was acquired by Oracle

in 2009 At the JavaOne 2010 conference, Oracle announced that 97% of enterprise tops, three billion handsets, and 80 million television devices run Java There are currentlyover 9 million Java developers, up from 4.5 million in 2005.8Java is now the most widelyused software development language in the world

desk-Java Class Libraries

You can create each class and method you need to form your Java programs However,most Java programmers take advantage of the rich collections of existing classes and meth-

ods in the Java class libraries, which are also known as the Java APIs (Application gramming Interfaces).

Pro-We now explain the commonly used steps in creating and executing a Java applicationusing a Java development environment (illustrated in Figs 1.1–1.5) Java programs nor-

mally go through five phases—edit, compile, load, verify and execute We discuss these

phases in the context of the Java SE Development Kit (JDK) You can download the mostup-to-date JDK and its documentation from www.oracle.com/technetwork/java/ javase/downloads/index.html Read the Before You Begin section of this book to ensure that

8 jaxenter.com/how-many-java-developers-are-there-10462.html

Performance Tip 1.1

Using Java API classes and methods instead of writing your own versions can improve gram performance, because they’re carefully written to perform efficiently This also short- ens program development time.

pro-Portability Tip 1.1

Although it’s easier to write portable programs (i.e., programs that can run on many ferent types of computers) in Java than in most other programming languages, differences between compilers, JVMs and computers can make portability difficult to achieve Simply writing programs in Java does not guarantee portability.

Ngày đăng: 27/10/2014, 00:52

TỪ KHÓA LIÊN QUAN