• No results found

Thinking. Java. Third Edition. Bruce Eckel. President, MindView, Inc.

N/A
N/A
Protected

Academic year: 2021

Share "Thinking. Java. Third Edition. Bruce Eckel. President, MindView, Inc."

Copied!
11
0
0

Loading.... (view fulltext now)

Full text

(1)

Thinking

in

Java

Third Edition

Bruce Eckel

(2)

Thinking

in

Java

Third Edition

Bruce Eckel

President, MindView, Inc.

PRENTICE HALL

Professional Technical Reference

Upper Saddle River, New Jersey 07458

www.phptr.com

PRENTICE HALL PTR

(3)

What's Inside

Preface 1

Preface to the 3

rd

edition 4

Java 2, JDK 1.4 6

Introduction 9

Prerequisites 10

Learning Java 10

Goals 11

JDK HTML

documentation 12

Chapters 13

Exercises 20

The CD ROM 20

Source code 22

Coding standards 24

Java versions 24

Errors 25

Note on the cover design .... 25

Acknowledgements 26

1: Introduction

to Objects 31

The progress

of abstraction 32

An object

has an interface 34

An object

provides services 37

The hidden

implementation 38

Reusing

the implementation 40

Inheritance: reusing

the interface 41

Is-a vs. is-like-a relationships 45

Interchangeable objects

with polymorphism 47

Abstract base classes

and interfaces 51

Object creation,

use & lifetimes 51

Collections and iterators 53 The singly rooted hierarchy 55 Downcasting vs.

templates/generics 56 Ensuring proper cleanup 57

Exception handling:

dealing with errors 59

Concurrency 60

Persistence 61

Java and the Internet 61

What is the Web? 61 Client-side programming 64 Server-side programming 71 Applications 72

Why Java succeeds 72

Systems are easier to

express and understand 72 Maximal leverage

with libraries 73 Error handling 73 Programming in the large 73

Java vs. C++? 74

Summary 75

2: Everything

is an Object 77

You manipulate objects

(4)

You must create

all the objects 79

Where storage lives 79 Special case: primitive types 80 Arrays in Java 82

You never need to

destroy an object 83

Scoping 83 Scope of objects 84

Creating new

data types: class 85

Fields and methods 85

Methods, arguments,

and return values 87

The argument list 89

Building a Java program 90

Name visibility go Using other components 91 The static keyword 92

Your first Java program 94

Compiling and running 95

Comments and embedded

documentation 97

Comment documentation 97 Syntax 98 Embedded HTML 99 Some example tags 100 Documentation example 102

Coding style 103

Summary 104

Exercises 104

3: Controlling

Program Flow 107

Using Java operators 107

Precedence 108 Assignment 108 Mathematical operators ill Auto increment and decrement 115 Relational operators 117 Logical operators 119 Bitwise operators 122 Shift operators 123 Ternary if-else operator 127 The comma operator 128

String operator + 128

Common pitfalls when

using operators 129 Casting operators 130 Java has no "sizeof ' 133 Precedence revisited 133 A compendium of operators 134

Execution control 144

true and false 144 if-else 145 return 146 Iteration 147 do-while 148 for 148 break and continue 151 switch 157

Summary 162

Exercises 162

4: Initialization

& Cleanup 165

Guaranteed initialization

with the constructor 165

Method overloading 168

Distinguishing

overloaded methods 171 Overloading with primitives 172 Overloading on return values 177 Default constructors 178 The this keyword 179

Cleanup: finalization

and garbage collection 183

What is finalize( ) for? 184 You must perform cleanup 185

(5)

The termination condition 186 How a garbage collector works 188

Member initialization 191

Specifying initialization 193 Constructor initialization 194

Array initialization 202

Multidimensional arrays 208

Summary 211

Exercises 212

5: Hiding the

Implementation 215

package: the library unit....216

Creating unique

package names 218 A custom tool library 222 Using imports

to change behavior 224 Package caveat 224

Java access specifiers 224

Package access 225

public: interface access 226 private:

you can't touch that! 228

protected: inheritance access 229

Interface

and implementation 231

Class access 232

Summary 236

Exercises 237

6: Reusing Classes 241

Composition syntax 241

Inheritance syntax 245

Initializing the base class 248

Combining composition

and inheritance 250

Guaranteeing proper cleanup.... 252

Name hiding 256

Choosing composition

vs. inheritance 258

protected 260

Incremental

development 261

Upcasting 262

Why "upcasting"? 263

The final keyword 264

Final data 264 Final methods 269 Final classes 271 Final caution 272

Initialization

and class loading 273

Initialization with inheritance....274

Summary 275

Exercises 276

7: Polymorphism 279

Upcasting revisited 279

Forgetting the object type 282

The twist 283

Method-call binding 284 Producing the right behavior 284 Extensibility 288 Pitfall: "overriding" private methods 292

Abstract classes

and methods 293

Constructors and

polymorphism 297

Order of constructor calls 298 Inheritance and cleanup 300 Behavior of polymorphic

methods inside constructors 303

Designing

with inheritance 306

Pure inheritance

(6)

Downcasting and

run-time type identification 310

Summary 312

Exercises 313

8: Interfaces

& Inner Classes 315

Interfaces 315

"Multiple inheritance" in Java....3ig Extending an interface with inheritance 323 Grouping constants 324 Initializing fields in interfaces 327 Nesting interfaces 328

Inner classes 331

Inner classes and upcasting 333 Inner classes in methods

and scopes 335 Anonymous inner classes 338 The link to the outer class 342 Nested classes 344 Referring to the

outer class object 347 Reaching outward from a

multiply-nested class 348 Inheriting from inner classes 349 Can inner classes

be overridden? 350 Local inner classes 352 Inner class identifiers 354

Why inner classes? 354

Closures & Callbacks 357 Inner classes

& control frameworks 360

Summary 367

Exercises 367

9: Error Handling

with Exceptions 371

Basic exceptions 372

Exception arguments 373

Catching an exception 374

The try block 374 Exception handlers 375

Creating your

own exceptions 376

The exception

specification 381

Catching any exception 382

Rethrowing an exception 384 Exception chaining 388

Standard

Java exceptions 392

The special case of

RuntimeException 392

Performing cleanup

with finally 394

What's finally for? 396 Pitfall: the lost exception 399

Exception restrictions 400

Constructors 404

Exception matching 408

Alternative approaches 409

History 410 Perspectives 412 Passing exceptions to the console 415 Converting checked to unchecked exceptions 416

Exception guidelines 418

Summary 419

Exercises 419

10: Detecting Types 423

The need for RTTI 423

The Class object 426 Checking before a cast 429

(7)

RTTI syntax 441

Reflection: run time

class information 444

A class method extractor 446

Summary 450

Exercises 451

11: Collections

of Objects 453

Arrays 453

Arrays are first-class objects 455 Returning an array 458 The Arrays class 460 Filling an array 469 Copying an array 470 Comparing arrays 472 Array element comparisons 473 Sorting an array 476 Searching a sorted array 478 Array summary 480

Introduction

to containers 481

Printing containers 482 Filling containers 484

Container disadvantage:

unknown type 491

Sometimes it works anyway 493 Making a type-conscious ArrayList 495

Iterators 497

Container taxonomy 501

Collection functionality.. 505

List functionality 509

Making a stack from a LinkedList 513 Making a queue from a LinkedList 514

Set functionality 515

SortedSet 519

Map functionality 520

SortedMap 525 LinkedHashMap 527

Hashing and hash codes 529 Overriding hashCode( ) 540

Holding references 545

The WeakHashMap 547

Iterators revisited 549

Choosing

an implementation 550

Choosing between Lists 551 Choosing between Sets 554 Choosing between Maps 557

Sorting and

searching Lists 560

Utilities 561

Making a Collection or Map unmodifiable 564 Synchronizing a Collection or Map 566

Unsupported operations... 567

Java 1.0/1.1 containers 570

Vector & Enumeration 570 Hashtable 571 Stack 572 BitSet 573

Summary 575

Exercises 576

12: The Java

I/O System 583

The File class 584

A directory lister 584 Checking for and

creating directories 588

Input and output 590

Types of InputStream 591 Types of OutputStream 593

Adding attributes

(8)

Reading from an InputStream with FilterlnputStream 595 Writing to an OutputStream with FilterOutputStream 597

Readers & Writers 598

Sources and sinks of data 599 Modifying stream behavior 600 Unchanged Classes 601

Off by itself:

RandomAccessFile 602

Typical uses

of I/O streams 603

Input streams 605 Output streams 608 Piped streams 610

File reading

& writing utilities 610

Standard I/O 612

Reading from standard input 612 Changing System.out

to a PrintWriter 613 Redirecting standard I/O 613

New I/O 615

Converting data 619 Fetching primitives 623 View buffers 625 Data manipulation with buffers 630 Buffer details 632 Memory-mapped files 636 File locking 640

Compression 643

Simple compression with GZIP 644 Multifile storage with Zip 645 Java ARchives (JARs) 648

Object serialization 650

Finding the class 654 Controlling serialization 656

Using persistence 665

Preferences 673

Regular expressions 675

Creating regular expressions 675 Quantifiers 677 Pattern and Matcher 679 splitO 688 Replace operations 689 reset( ) 691 Regular expressions

and Java I/O 692 Is StringTokenizer needed? 693

Summary 694

Exercises 695

13: Concurrency 699

Motivation 700

Basic threads 701

Yielding 704 Sleeping 705 Priority 708 Daemon threads 710 Joining a thread 713 Coding variations 715 Creating responsive user interfaces 722

Sharing

limited resources 723

Improperly accessing resources 723 Colliding over resources 729 Resolving shared resource contention 731 Critical sections 738

Thread states 744

Becoming blocked 745

Cooperation

between threads 745

Wait and notify 745

(9)

Using Pipes for I/O

between threads 750 More sophisticated

cooperation 752

Deadlock 752

The proper way to stop 758

Interrupting a

blocked thread 759

Thread groups 760

Summary 761

Exercises 762

14: Creating

Windows & Applets 765

The basic applet 768

Applet restrictions 768 Applet advantages 769 Application frameworks 770 Running applets inside

a Web browser 771 Using Appletviewer 773 Testing applets 774

Running applets

from the command line 775

A display framework 777

Making a button 779

Capturing an event 780

Text areas 783

Controlling layout 785

BorderLayout 786 FlowLayout 787 GridLayout 788 GridBagLayout 788 Absolute positioning 789 BoxLayout 789 The best approach? 793

The Swing event model 793

Event and listener types 794 Tracking multiple events 801

A catalog of

Swing components 804

Buttons 805 Icons 808 Tool tips 810 Textfelds 810 Borders 812 JScrollPanes 814 A mini-editor 816 Check boxes 817 Radio buttons 819 Combo boxes (drop-down lists) 820 List boxes 821 Tabbed panes 824 Message boxes 825 Menus 827 Pop-up menus 834 Drawing 835 Dialog Boxes 838 File dialogs 843 HTML on Swing components ....845 Sliders and progress bars 846 Trees 847 Tables 850 Selecting Look & Feel 852 The clipboard 854

Packaging an applet

into a JAR file 857

Signing applets 858

JNLP and

Java Web Start 863

Programming

techniques 869

Binding events dynamically 870 Separating business logic

from UI logic 872 A canonical form 874

Concurrency & Swing 875

(10)

Runnable revisited 875 Managing concurrency 878

Visual programming

and JavaBeans 882

What is a JavaBean? 883 Extracting Beanlnfo

with the Introspector 886 A more sophisticated Bean 892 JavaBeans

and synchronization 896 Packaging a Bean 901 More complex Bean support 902 More to Beans 903

Summary 904

Exercises 905

15: Discovering

Problems 909

Unit Testing 911

A Simple Testing Framework 913 JUnit 925

Improving reliability

with assertions 930

Assertion syntax 931 Using Assertions for

Design by Contract 934

Example: DBC +

white-box unit testing 938

Building with Ant 944

Automate everything 944 Problems with make 945 Ant: the defacto standard 946 Version control with CVS 950 Daily builds 953

Logging 954

Logging Levels 956 LogRecords 959 Handlers 961 Filters 966 Formatters 968

Example: Sending email

to report log messages 969 Controlling Logging Levels through Namespaces 972 Logging Practices

for Large Projects 974 Summary 978

Debugging 978

Debugging with JDB 978 Graphical debuggers 984

Profiling and optimizing... 985

Tracking

memory consumption 985 Tracking CPU usage 986 Coverage testing 986 JVM Profiling Interface 986 Using HPROF 987 Thread performance 989 Optimization guidelines 990

Doclets 991

Summary 993

Exercises 995

16: Analysis

and Design 997

Methodology 997

Phase o: Make a plan 1000

The mission statement 1000

Phase 1:

What are we making? 1001

Phase 2:

How will we build it? 1005

Five stages of object design 1007 Guidelines for

object development 1008

Phase 3: Build the core.... 1009

Phase 4:

Iterate the use cases 1010

Phase 5: Evolution 1010

Plans pay off 1012

(11)

Extreme Programming ....1013

Write tests first 1013 Pair programming 1015

Strategies for transition... 1016

Guidelines 1017 Management obstacles 1018

Summary 1020

A: Passing

& Returning Objects 1021

Passing references

around 1022

Aliasing 1022

Making local copies 1025

Pass by value 1026 Cloning objects 1026 Adding cloneability to a class 1028 Successful cloning 1030 The effect of Object.clone( ) 1032

Cloning a composed object 1035 A deep copy

with ArrayList 1038 Deep copy via serialization 1040 Adding cloneability

farther down a hierarchy 1042 Why this strange design? 1043

Controlling

cloneability 1044

The copy constructor 1049

Read-only classes 1054

Creating read-only classes 1056 The drawback

to immutability 1057 Immutable Strings 1060

The String and

StringBuffer classes 1063 Strings are special 1067

Summary 1067

Exercises 1069

B: Java Programming

Guidelines 1071

Design 1071

Implementation 1078

C: Supplements 1085

Foundations for Java

seminar-on-CD 1085

Thinking in Java

seminar 1085

Hands-On Java

seminar-on-CD 3

rd

edition 1086

Designing Objects &

Systems seminar 1086

Thinking in

Enterprise Java 1087

The J2EE seminar 1088

Thinking in Patterns

(with Java) 1088

Thinking in Patterns

seminar 1089

Design consulting

and reviews 1089

D: Resources 1091

Software 1091

Books 1091

Analysis & design 1092 Python 1095 My own list of books 1095

References

Related documents

Although these blueberry credence attributes (Non-GMO, fair trade product, and organic) were considered slightly important, consumers valued other credence attributes more

These no-action letters address investment advisers’ duties under Investment Advisers Act Rule 206(4)-6 to vote client securities in the best interests of clients. The Egan-

Create a control for the stop and your block diagram should look like the one pictured in Figure 15.. We are almost ready to gather some data, but we need to close

On the second course use the other AB Dublin half (1/2) length piece with the split side facing out and toward the next section of the wall panel.. Step 5:

sequences were correctly repaired, and that the repair efficiency is approximately 8.3% of edited cells (Figure 2.8). From these data, we can conclude that the CRISPR/Cas9 system

There were three types of unstudied words that were seen in the recognition task: (a) words that were random and unassociated to the list known as “unrelated” (b) words loosely

201 The Guidance also does not mention the two other times in FCPA history that the enforcement agency’s position that payments outside the context of foreign