100% found this document useful (9 votes)
212 views75 pages

Core Java Volume I Fundamentals 10th Edition by Cay S Horstmann ISBN 9780134177335 Instant Download

The document provides information about various editions of 'Core Java' by Cay S. Horstmann, including links to download the books in different formats. It also includes details about the content structure of the 10th edition, covering fundamental programming concepts in Java. Additionally, it outlines the author's credentials and the publication's copyright information.

Uploaded by

negcrtmak0760
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (9 votes)
212 views75 pages

Core Java Volume I Fundamentals 10th Edition by Cay S Horstmann ISBN 9780134177335 Instant Download

The document provides information about various editions of 'Core Java' by Cay S. Horstmann, including links to download the books in different formats. It also includes details about the content structure of the 10th edition, covering fundamental programming concepts in Java. Additionally, it outlines the author's credentials and the publication's copyright information.

Uploaded by

negcrtmak0760
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Core Java Volume I Fundamentals 10th Edition by

Cay S Horstmann ISBN 9780134177335 download

https://ebookball.com/product/core-java-volume-i-
fundamentals-10th-edition-by-cay-s-horstmann-
isbn-9780134177335-16166/

Download more ebook instantly today - Get yours now at ebookball.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Core Java 2 Volume 1 Fundamentals 1st Edition by Cay Horstmann, Gary


Cornell ISBN 0131482025 9780131482029

https://ebookball.com/product/core-
java-2-volume-1-fundamentals-1st-edition-by-cay-horstmann-gary-
cornell-isbn-0131482025-9780131482029-12110/

Core Java 1 2 Volume 1 Fundamentals 1st Edition by Cay Horstmann, Gary


Cornell ISBN 0130819336 9780130819338

https://ebookball.com/product/core-
java-1-2-volume-1-fundamentals-1st-edition-by-cay-horstmann-gary-
cornell-isbn-0130819336-9780130819338-12612/

Core Java Volume II Advanced Features 9th Edition by Horstmann Cay,


Gary Cornell ISBN 9780137081608

https://ebookball.com/product/core-java-volume-ii-advanced-
features-9th-edition-by-horstmann-cay-gary-cornell-
isbn-9780137081608-16174/

Core Java 2 Volume II Advanced Features 7th Edition by Cay Horstmann,


Gary Cornell ISBN 0131118269 9780131118263

https://ebookball.com/product/core-java-2-volume-ii-advanced-
features-7th-edition-by-cay-horstmann-gary-cornell-
isbn-0131118269-9780131118263-12622/
Java SE 8 for the Really Impatient 1st Edition by Cay S Horstmann ISBN
0321927761 978-0321927767

https://ebookball.com/product/java-se-8-for-the-really-
impatient-1st-edition-by-cay-s-horstmann-
isbn-0321927761-978-0321927767-12112/

Java I O Tips and Techniques for Putting I O to Work 2nd Edition by


Elliotte Rusty Harold ISBN 1449391540 9781449391546

https://ebookball.com/product/java-i-o-tips-and-techniques-for-
putting-i-o-to-work-2nd-edition-by-elliotte-rusty-harold-
isbn-1449391540-9781449391546-10732/

Java The Fundamentals of Objects and Classes 1st Edition by David


Etheridge ISBN

https://ebookball.com/product/java-the-fundamentals-of-objects-
and-classes-1st-edition-by-david-etheridge-isbn-12864/

Java How to Program 10th edition by Harvey Deitel, Paul Deitel ISBN
0133807800 978-0133807806

https://ebookball.com/product/java-how-to-program-10th-edition-
by-harvey-deitel-paul-deitel-
isbn-0133807800-978-0133807806-16282/

China’s Belt and Road Initiative in a Global Context Volume I A


Business and Management Perspective 1st edition by Jawad Syed, Yung
Hsiang Ying ISBN‎ 3030147215 978-3030147211

https://ebookball.com/product/chinaaeurtms-belt-and-road-
initiative-in-a-global-context-volume-i-a-business-and-
management-perspective-1st-edition-by-jawad-syed-yung-hsiang-
ying-isbnaeurz-3030147215-978-3030147211-24508/
Core Java ®

Volume I—Fundamentals
Tenth Edition
This page intentionally left blank
Core Java ®

Volume I—Fundamentals
Tenth Edition

Cay S. Horstmann

Boston • Columbus • Indianapolis • New York • San Francisco • Amsterdam • Cape Town
Dubai • London • Madrid • Milan • Munich • Paris • Montreal • Toronto • Delhi • Mexico City
Sao Paulo • Sidney • Hong Kong • Seoul • Singapore • Taipei • Tokyo
The author 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.

For information about buying this title in bulk quantities, or for special sales opportunities
(which may include electronic versions; custom cover designs; and content particular to
your business, training goals, marketing focus, or branding interests), please contact our
corporate sales department at [email protected] or (800) 382-3419.

For government sales inquiries, please contact [email protected].

For questions about sales outside the United States, please contact
[email protected].

Visit us on the Web: informit.com/ph

Library of Congress Cataloging-in-Publication Data


Names: Horstmann, Cay S., 1959- author.
Title: Core Java / Cay S. Horstmann.
Description: Tenth edition. | New York : Prentice Hall, [2016] | Includes
index.
Identifiers: LCCN 2015038763| ISBN 9780134177304 (volume 1 : pbk. : alk.
paper) | ISBN 0134177304 (volume 1 : pbk. : alk. paper)
Subjects: LCSH: Java (Computer program language)
Classification: LCC QA76.73.J38 H6753 2016 | DDC 005.13/3—dc23
LC record available at http://lccn.loc.gov/2015038763

Copyright © 2016 Oracle and/or its affiliates. All rights reserved.


500 Oracle Parkway, Redwood Shores, CA 94065

Portions © Cay S. Horstmann

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 transmission in any form or by any means,
electronic, mechanical, photocopying, recording, or likewise. For information regarding
permissions, request forms and the appropriate contacts within the Pearson Education
Global Rights & Permissions Department, please visit www.pearsoned.com/permissions/.

Oracle America Inc. does not make any representations or warranties as to the accuracy,
adequacy or completeness of any information contained in this work, and is not responsible
for any errors or omissions.

ISBN-13: 978-0-13-417730-4
ISBN-10: 0-13-417730-4

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


Indiana.
First printing, December 2015
Contents
Preface .......................................................................................................... xix
Acknowledgments ......................................................................................... xxv

Chapter 1: An Introduction to Java ............................................................... 1


1.1 Java as a Programming Platform ............................................................... 1
1.2 The Java “White Paper” Buzzwords .......................................................... 2
1.2.1 Simple ............................................................................................. 3
1.2.2 Object-Oriented ............................................................................. 4
1.2.3 Distributed ..................................................................................... 4
1.2.4 Robust ............................................................................................. 4
1.2.5 Secure .............................................................................................. 4
1.2.6 Architecture-Neutral ..................................................................... 5
1.2.7 Portable ........................................................................................... 6
1.2.8 Interpreted ...................................................................................... 7
1.2.9 High-Performance ......................................................................... 7
1.2.10 Multithreaded ................................................................................ 7
1.2.11 Dynamic .......................................................................................... 8
1.3 Java Applets and the Internet ..................................................................... 8
1.4 A Short History of Java ............................................................................. 10
1.5 Common Misconceptions about Java ..................................................... 13

Chapter 2: The Java Programming Environment ....................................... 17


2.1 Installing the Java Development Kit ....................................................... 18
2.1.1 Downloading the JDK ................................................................. 18
2.1.2 Setting up the JDK ....................................................................... 20
2.1.3 Installing Source Files and Documentation ............................. 22
2.2 Using the Command-Line Tools .............................................................. 23
2.3 Using an Integrated Development Environment .................................. 26
2.4 Running a Graphical Application ........................................................... 30
2.5 Building and Running Applets ................................................................ 33

v
vi Contents

Chapter 3: Fundamental Programming Structures in Java ....................... 41


3.1 A Simple Java Program ............................................................................. 42
3.2 Comments ................................................................................................... 46
3.3 Data Types ................................................................................................... 47
3.3.1 Integer Types ................................................................................ 47
3.3.2 Floating-Point Types ................................................................... 48
3.3.3 The char Type ................................................................................ 50
3.3.4 Unicode and the char Type .......................................................... 51
3.3.5 The boolean Type ............................................................................ 52
3.4 Variables ...................................................................................................... 53
3.4.1 Initializing Variables ................................................................... 54
3.4.2 Constants ...................................................................................... 55
3.5 Operators .................................................................................................... 56
3.5.1 Mathematical Functions and Constants ................................... 57
3.5.2 Conversions between Numeric Types ...................................... 59
3.5.3 Casts .............................................................................................. 60
3.5.4 Combining Assignment with Operators .................................. 61
3.5.5 Increment and Decrement Operators ....................................... 61
3.5.6 Relational and boolean Operators ................................................ 62
3.5.7 Bitwise Operators ........................................................................ 63
3.5.8 Parentheses and Operator Hierarchy ....................................... 64
3.5.9 Enumerated Types ...................................................................... 65
3.6 Strings .......................................................................................................... 65
3.6.1 Substrings ..................................................................................... 66
3.6.2 Concatenation .............................................................................. 66
3.6.3 Strings Are Immutable ................................................................ 67
3.6.4 Testing Strings for Equality ........................................................ 68
3.6.5 Empty and Null Strings .............................................................. 69
3.6.6 Code Points and Code Units ...................................................... 70
3.6.7 The String API ................................................................................ 71
3.6.8 Reading the Online API Documentation ................................. 74
3.6.9 Building Strings ........................................................................... 77
3.7 Input and Output ....................................................................................... 78
3.7.1 Reading Input .............................................................................. 79
3.7.2 Formatting Output ...................................................................... 82
Contents vii

3.7.3 File Input and Output ................................................................. 87


3.8 Control Flow ............................................................................................... 89
3.8.1 Block Scope ................................................................................... 89
3.8.2 Conditional Statements .............................................................. 90
3.8.3 Loops ............................................................................................. 94
3.8.4 Determinate Loops ...................................................................... 99
3.8.5 Multiple Selections—The switch Statement ............................. 103
3.8.6 Statements That Break Control Flow ...................................... 106
3.9 Big Numbers ............................................................................................. 108
3.10 Arrays ........................................................................................................ 111
3.10.1 The “for each” Loop .................................................................. 113
3.10.2 Array Initializers and Anonymous Arrays ............................ 114
3.10.3 Array Copying ........................................................................... 114
3.10.4 Command-Line Parameters ..................................................... 116
3.10.5 Array Sorting ............................................................................. 117
3.10.6 Multidimensional Arrays ......................................................... 120
3.10.7 Ragged Arrays ........................................................................... 124

Chapter 4: Objects and Classes ................................................................ 129


4.1 Introduction to Object-Oriented Programming .................................. 130
4.1.1 Classes ......................................................................................... 131
4.1.2 Objects ......................................................................................... 132
4.1.3 Identifying Classes .................................................................... 133
4.1.4 Relationships between Classes ................................................ 133
4.2 Using Predefined Classes ....................................................................... 135
4.2.1 Objects and Object Variables .................................................... 136
4.2.2 The LocalDate Class of the Java Library ..................................... 139
4.2.3 Mutator and Accessor Methods .............................................. 141
4.3 Defining Your Own Classes ................................................................... 145
4.3.1 An Employee Class ......................................................................... 145
4.3.2 Use of Multiple Source Files .................................................... 149
4.3.3 Dissecting the Employee Class ...................................................... 149
4.3.4 First Steps with Constructors .................................................. 150
4.3.5 Implicit and Explicit Parameters ............................................. 152
4.3.6 Benefits of Encapsulation ......................................................... 153
4.3.7 Class-Based Access Privileges .................................................. 156
viii Contents

4.3.8 Private Methods ......................................................................... 156


4.3.9 Final Instance Fields .................................................................. 157
4.4 Static Fields and Methods ....................................................................... 158
4.4.1 Static Fields ................................................................................. 158
4.4.2 Static Constants .......................................................................... 159
4.4.3 Static Methods ............................................................................ 160
4.4.4 Factory Methods ........................................................................ 161
4.4.5 The main Method ......................................................................... 161
4.5 Method Parameters .................................................................................. 164
4.6 Object Construction ................................................................................. 171
4.6.1 Overloading ................................................................................ 172
4.6.2 Default Field Initialization ....................................................... 172
4.6.3 The Constructor with No Arguments ..................................... 173
4.6.4 Explicit Field Initialization ....................................................... 174
4.6.5 Parameter Names ...................................................................... 175
4.6.6 Calling Another Constructor ................................................... 176
4.6.7 Initialization Blocks ................................................................... 177
4.6.8 Object Destruction and the finalize Method ........................... 181
4.7 Packages .................................................................................................... 182
4.7.1 Class Importation ...................................................................... 183
4.7.2 Static Imports ............................................................................. 185
4.7.3 Addition of a Class into a Package ......................................... 185
4.7.4 Package Scope ............................................................................ 189
4.8 The Class Path ........................................................................................... 190
4.8.1 Setting the Class Path ................................................................ 193
4.9 Documentation Comments .................................................................... 194
4.9.1 Comment Insertion ................................................................... 194
4.9.2 Class Comments ........................................................................ 195
4.9.3 Method Comments ................................................................... 195
4.9.4 Field Comments ........................................................................ 196
4.9.5 General Comments ................................................................... 196
4.9.6 Package and Overview Comments ......................................... 198
4.9.7 Comment Extraction ................................................................. 198
4.10 Class Design Hints .................................................................................. 200
Contents ix

Chapter 5: Inheritance ................................................................................ 203


5.1 Classes, Superclasses, and Subclasses .................................................. 204
5.1.1 Defining Subclasses ................................................................... 204
5.1.2 Overriding Methods ................................................................. 206
5.1.3 Subclass Constructors ............................................................... 207
5.1.4 Inheritance Hierarchies ............................................................ 212
5.1.5 Polymorphism ............................................................................ 213
5.1.6 Understanding Method Calls .................................................. 214
5.1.7 Preventing Inheritance: Final Classes and Methods ............ 217
5.1.8 Casting ........................................................................................ 219
5.1.9 Abstract Classes ......................................................................... 221
5.1.10 Protected Access ........................................................................ 227
5.2 Object: The Cosmic Superclass ................................................................. 228
5.2.1 The equals Method ...................................................................... 229
5.2.2 Equality Testing and Inheritance ............................................. 231
5.2.3 The hashCode Method .................................................................... 235
5.2.4 The toString Method .................................................................... 238
5.3 Generic Array Lists .................................................................................. 244
5.3.1 Accessing Array List Elements ................................................ 247
5.3.2 Compatibility between Typed and Raw Array Lists ............ 251
5.4 Object Wrappers and Autoboxing ......................................................... 252
5.5 Methods with a Variable Number of Parameters ................................ 256
5.6 Enumeration Classes ............................................................................... 258
5.7 Reflection .................................................................................................. 260
5.7.1 The Class Class ............................................................................ 261
5.7.2 A Primer on Catching Exceptions ........................................... 263
5.7.3 Using Reflection to Analyze the Capabilities of Classes ...... 265
5.7.4 Using Reflection to Analyze Objects at Runtime .................. 271
5.7.5 Using Reflection to Write Generic Array Code ..................... 276
5.7.6 Invoking Arbitrary Methods ................................................... 279
5.8 Design Hints for Inheritance .................................................................. 283

Chapter 6: Interfaces, Lambda Expressions, and Inner Classes ............ 287


6.1 Interfaces ................................................................................................... 288
6.1.1 The Interface Concept ............................................................... 288
x Contents

6.1.2 Properties of Interfaces ............................................................. 295


6.1.3 Interfaces and Abstract Classes ............................................... 297
6.1.4 Static Methods ............................................................................ 298
6.1.5 Default Methods ........................................................................ 298
6.1.6 Resolving Default Method Conflicts ....................................... 300
6.2 Examples of Interfaces ............................................................................ 302
6.2.1 Interfaces and Callbacks ........................................................... 302
6.2.2 The Comparator Interface ................................................................ 305
6.2.3 Object Cloning ........................................................................... 306
6.3 Lambda Expressions ............................................................................... 314
6.3.1 Why Lambdas? .......................................................................... 314
6.3.2 The Syntax of Lambda Expressions ........................................ 315
6.3.3 Functional Interfaces ................................................................. 318
6.3.4 Method References .................................................................... 319
6.3.5 Constructor References ............................................................. 321
6.3.6 Variable Scope ............................................................................ 322
6.3.7 Processing Lambda Expressions ............................................. 324
6.3.8 More about Comparators ......................................................... 328
6.4 Inner Classes ............................................................................................. 329
6.4.1 Use of an Inner Class to Access Object State ......................... 331
6.4.2 Special Syntax Rules for Inner Classes ................................... 334
6.4.3 Are Inner Classes Useful? Actually Necessary? Secure? ...... 335
6.4.4 Local Inner Classes .................................................................... 339
6.4.5 Accessing Variables from Outer Methods .............................. 339
6.4.6 Anonymous Inner Classes ....................................................... 342
6.4.7 Static Inner Classes .................................................................... 346
6.5 Proxies ....................................................................................................... 350
6.5.1 When to Use Proxies ................................................................. 350
6.5.2 Creating Proxy Objects ............................................................. 350
6.5.3 Properties of Proxy Classes ...................................................... 355

Chapter 7: Exceptions, Assertions, and Logging ..................................... 357


7.1 Dealing with Errors ................................................................................. 358
7.1.1 The Classification of Exceptions .............................................. 359
7.1.2 Declaring Checked Exceptions ................................................ 361
7.1.3 How to Throw an Exception .................................................... 364
Contents xi

7.1.4 Creating Exception Classes ...................................................... 365


7.2 Catching Exceptions ................................................................................ 367
7.2.1 Catching an Exception .............................................................. 367
7.2.2 Catching Multiple Exceptions ................................................. 369
7.2.3 Rethrowing and Chaining Exceptions ................................... 370
7.2.4 The finally Clause ....................................................................... 372
7.2.5 The Try-with-Resources Statement ......................................... 376
7.2.6 Analyzing Stack Trace Elements .............................................. 377
7.3 Tips for Using Exceptions ....................................................................... 381
7.4 Using Assertions ...................................................................................... 384
7.4.1 The Assertion Concept .............................................................. 384
7.4.2 Assertion Enabling and Disabling .......................................... 385
7.4.3 Using Assertions for Parameter Checking ............................. 386
7.4.4 Using Assertions for Documenting Assumptions ................ 387
7.5 Logging ..................................................................................................... 389
7.5.1 Basic Logging ............................................................................. 389
7.5.2 Advanced Logging .................................................................... 390
7.5.3 Changing the Log Manager Configuration ........................... 392
7.5.4 Localization ................................................................................ 393
7.5.5 Handlers ..................................................................................... 394
7.5.6 Filters ........................................................................................... 398
7.5.7 Formatters .................................................................................. 399
7.5.8 A Logging Recipe ...................................................................... 399
7.6 Debugging Tips ........................................................................................ 409

Chapter 8: Generic Programming .............................................................. 415


8.1 Why Generic Programming? .................................................................. 416
8.1.1 The Advantage of Type Parameters ......................................... 416
8.1.2 Who Wants to Be a Generic Programmer? ............................. 417
8.2 Defining a Simple Generic Class ........................................................... 418
8.3 Generic Methods ...................................................................................... 421
8.4 Bounds for Type Variables ...................................................................... 422
8.5 Generic Code and the Virtual Machine ................................................ 425
8.5.1 Type Erasure .............................................................................. 425
8.5.2 Translating Generic Expressions ............................................. 426
8.5.3 Translating Generic Methods .................................................. 427
xii Contents

8.5.4 Calling Legacy Code ................................................................. 429


8.6 Restrictions and Limitations .................................................................. 430
8.6.1 Type Parameters Cannot Be Instantiated with Primitive
Types ........................................................................................... 430
8.6.2 Runtime Type Inquiry Only Works with Raw Types ........... 431
8.6.3 You Cannot Create Arrays of Parameterized Types ............ 431
8.6.4 Varargs Warnings ...................................................................... 432
8.6.5 You Cannot Instantiate Type Variables .................................. 433
8.6.6 You Cannot Construct a Generic Array ................................. 434
8.6.7 Type Variables Are Not Valid in Static Contexts of Generic
Classes ......................................................................................... 436
8.6.8 You Cannot Throw or Catch Instances of a Generic Class ... 436
8.6.9 You Can Defeat Checked Exception Checking ..................... 437
8.6.10 Beware of Clashes after Erasure .............................................. 439
8.7 Inheritance Rules for Generic Types ..................................................... 440
8.8 Wildcard Types ........................................................................................ 442
8.8.1 The Wildcard Concept .............................................................. 442
8.8.2 Supertype Bounds for Wildcards ............................................ 444
8.8.3 Unbounded Wildcards ............................................................. 447
8.8.4 Wildcard Capture ...................................................................... 448
8.9 Reflection and Generics .......................................................................... 450
8.9.1 The Generic Class Class .............................................................. 450
8.9.2 Using Class<T> Parameters for Type Matching ........................ 452
8.9.3 Generic Type Information in the Virtual Machine ................ 452

Chapter 9: Collections ................................................................................ 459


9.1 The Java Collections Framework ........................................................... 460
9.1.1 Separating Collection Interfaces and Implementation ......... 460
9.1.2 The Collection Interface ................................................................ 463
9.1.3 Iterators ....................................................................................... 463
9.1.4 Generic Utility Methods ........................................................... 466
9.1.5 Interfaces in the Collections Framework ............................... 469
9.2 Concrete Collections ................................................................................ 472
9.2.1 Linked Lists ................................................................................ 474
9.2.2 Array Lists .................................................................................. 484
9.2.3 Hash Sets .................................................................................... 485
Contents xiii

9.2.4 Tree Sets ...................................................................................... 489


9.2.5 Queues and Deques .................................................................. 494
9.2.6 Priority Queues .......................................................................... 495
9.3 Maps .......................................................................................................... 497
9.3.1 Basic Map Operations ............................................................... 497
9.3.2 Updating Map Entries .............................................................. 500
9.3.3 Map Views .................................................................................. 502
9.3.4 Weak Hash Maps ....................................................................... 504
9.3.5 Linked Hash Sets and Maps .................................................... 504
9.3.6 Enumeration Sets and Maps .................................................... 506
9.3.7 Identity Hash Maps .................................................................. 507
9.4 Views and Wrappers ............................................................................... 509
9.4.1 Lightweight Collection Wrappers ........................................... 509
9.4.2 Subranges ................................................................................... 510
9.4.3 Unmodifiable Views ................................................................. 511
9.4.4 Synchronized Views .................................................................. 512
9.4.5 Checked Views .......................................................................... 513
9.4.6 A Note on Optional Operations .............................................. 514
9.5 Algorithms ................................................................................................ 517
9.5.1 Sorting and Shuffling ................................................................ 518
9.5.2 Binary Search ............................................................................. 521
9.5.3 Simple Algorithms .................................................................... 522
9.5.4 Bulk Operations ......................................................................... 524
9.5.5 Converting between Collections and Arrays ........................ 525
9.5.6 Writing Your Own Algorithms ................................................ 526
9.6 Legacy Collections ................................................................................... 528
9.6.1 The Hashtable Class ....................................................................... 528
9.6.2 Enumerations ............................................................................. 528
9.6.3 Property Maps ........................................................................... 530
9.6.4 Stacks ........................................................................................... 531
9.6.5 Bit Sets ......................................................................................... 532

Chapter 10: Graphics Programming .......................................................... 537


10.1 Introducing Swing ................................................................................... 538
10.2 Creating a Frame ...................................................................................... 543
10.3 Positioning a Frame ................................................................................. 546
xiv Contents

10.3.1 Frame Properties ....................................................................... 549


10.3.2 Determining a Good Frame Size ............................................. 549
10.4 Displaying Information in a Component ............................................. 554
10.5 Working with 2D Shapes ........................................................................ 560
10.6 Using Color ............................................................................................... 569
10.7 Using Special Fonts for Text ................................................................... 573
10.8 Displaying Images ................................................................................... 582

Chapter 11: Event Handling ........................................................................ 587


11.1 Basics of Event Handling ........................................................................ 587
11.1.1 Example: Handling a Button Click ......................................... 591
11.1.2 Specifying Listeners Concisely ................................................ 595
11.1.3 Example: Changing the Look-and-Feel .................................. 598
11.1.4 Adapter Classes ......................................................................... 603
11.2 Actions ....................................................................................................... 607
11.3 Mouse Events ........................................................................................... 616
11.4 The AWT Event Hierarchy ..................................................................... 624
11.4.1 Semantic and Low-Level Events ............................................. 626

Chapter 12: User Interface Components with Swing ............................... 629


12.1 Swing and the Model-View-Controller Design Pattern ..................... 630
12.1.1 Design Patterns .......................................................................... 630
12.1.2 The Model-View-Controller Pattern ....................................... 632
12.1.3 A Model-View-Controller Analysis of Swing Buttons ......... 636
12.2 Introduction to Layout Management .................................................... 638
12.2.1 Border Layout ............................................................................ 641
12.2.2 Grid Layout ................................................................................ 644
12.3 Text Input .................................................................................................. 648
12.3.1 Text Fields ................................................................................... 649
12.3.2 Labels and Labeling Components .......................................... 651
12.3.3 Password Fields ......................................................................... 652
12.3.4 Text Areas ................................................................................... 653
12.3.5 Scroll Panes ................................................................................. 654
12.4 Choice Components ................................................................................ 657
12.4.1 Checkboxes ................................................................................. 657
12.4.2 Radio Buttons ............................................................................. 660
Contents xv

12.4.3 Borders ........................................................................................ 664


12.4.4 Combo Boxes .............................................................................. 668
12.4.5 Sliders .......................................................................................... 672
12.5 Menus ........................................................................................................ 678
12.5.1 Menu Building ........................................................................... 679
12.5.2 Icons in Menu Items .................................................................. 682
12.5.3 Checkbox and Radio Button Menu Items .............................. 683
12.5.4 Pop-Up Menus ........................................................................... 684
12.5.5 Keyboard Mnemonics and Accelerators ................................ 686
12.5.6 Enabling and Disabling Menu Items ...................................... 689
12.5.7 Toolbars ....................................................................................... 694
12.5.8 Tooltips ........................................................................................ 696
12.6 Sophisticated Layout Management ....................................................... 699
12.6.1 The Grid Bag Layout ................................................................. 701
12.6.1.1 The gridx, gridy, gridwidth, and gridheight Parameters ... 703
12.6.1.2 Weight Fields .............................................................. 703
12.6.1.3 The fill and anchor Parameters .................................. 704
12.6.1.4 Padding ....................................................................... 704
12.6.1.5 Alternative Method to Specify the gridx, gridy,
gridwidth, and gridheight Parameters ............................ 705
12.6.1.6 A Helper Class to Tame the Grid Bag
Constraints .................................................................. 706
12.6.2 Group Layout ............................................................................. 713
12.6.3 Using No Layout Manager ...................................................... 723
12.6.4 Custom Layout Managers ........................................................ 724
12.6.5 Traversal Order .......................................................................... 729
12.7 Dialog Boxes ............................................................................................. 730
12.7.1 Option Dialogs ........................................................................... 731
12.7.2 Creating Dialogs ........................................................................ 741
12.7.3 Data Exchange ............................................................................ 746
12.7.4 File Dialogs ................................................................................. 752
12.7.5 Color Choosers .......................................................................... 764
12.8 Troubleshooting GUI Programs ............................................................. 770
12.8.1 Debugging Tips ......................................................................... 770
12.8.2 Letting the AWT Robot Do the Work ..................................... 774
xvi Contents

Chapter 13: Deploying Java Applications ................................................. 779


13.1 JAR Files .................................................................................................... 780
13.1.1 Creating JAR files ...................................................................... 780
13.1.2 The Manifest ............................................................................... 781
13.1.3 Executable JAR Files ................................................................. 782
13.1.4 Resources .................................................................................... 783
13.1.5 Sealing ......................................................................................... 787
13.2 Storage of Application Preferences ....................................................... 788
13.2.1 Property Maps ........................................................................... 788
13.2.2 The Preferences API .................................................................. 794
13.3 Service Loaders ........................................................................................ 800
13.4 Applets ...................................................................................................... 802
13.4.1 A Simple Applet ........................................................................ 803
13.4.2 The applet HTML Tag and Its Attributes ................................. 808
13.4.3 Use of Parameters to Pass Information to Applets ............... 810
13.4.4 Accessing Image and Audio Files ........................................... 816
13.4.5 The Applet Context ................................................................... 818
13.4.6 Inter-Applet Communication .................................................. 818
13.4.7 Displaying Items in the Browser ............................................. 819
13.4.8 The Sandbox ............................................................................... 820
13.4.9 Signed Code ............................................................................... 822
13.5 Java Web Start ........................................................................................... 824
13.5.1 Delivering a Java Web Start Application ................................ 824
13.5.2 The JNLP API ............................................................................. 829

Chapter 14: Concurrency ........................................................................... 839


14.1 What Are Threads? .................................................................................. 840
14.1.1 Using Threads to Give Other Tasks a Chance ....................... 846
14.2 Interrupting Threads ............................................................................... 851
14.3 Thread States ............................................................................................. 855
14.3.1 New Threads .............................................................................. 855
14.3.2 Runnable Threads ...................................................................... 855
14.3.3 Blocked and Waiting Threads .................................................. 856
14.3.4 Terminated Threads .................................................................. 857
14.4 Thread Properties ..................................................................................... 858
14.4.1 Thread Priorities ........................................................................ 858
Contents xvii

14.4.2 Daemon Threads ........................................................................ 859


14.4.3 Handlers for Uncaught Exceptions ........................................ 860
14.5 Synchronization ....................................................................................... 862
14.5.1 An Example of a Race Condition ............................................ 862
14.5.2 The Race Condition Explained ................................................ 866
14.5.3 Lock Objects ............................................................................... 868
14.5.4 Condition Objects ...................................................................... 872
14.5.5 The synchronized Keyword ............................................................ 878
14.5.6 Synchronized Blocks ................................................................. 882
14.5.7 The Monitor Concept ................................................................ 884
14.5.8 Volatile Fields ............................................................................. 885
14.5.9 Final Variables ............................................................................ 886
14.5.10 Atomics ....................................................................................... 886
14.5.11 Deadlocks ................................................................................... 889
14.5.12 Thread-Local Variables ............................................................. 892
14.5.13 Lock Testing and Timeouts ...................................................... 893
14.5.14 Read/Write Locks ..................................................................... 895
14.5.15 Why the stop and suspend Methods Are Deprecated ............... 896
14.6 Blocking Queues ...................................................................................... 898
14.7 Thread-Safe Collections .......................................................................... 905
14.7.1 Efficient Maps, Sets, and Queues ............................................ 905
14.7.2 Atomic Update of Map Entries ................................................ 907
14.7.3 Bulk Operations on Concurrent Hash Maps ......................... 909
14.7.4 Concurrent Set Views ............................................................... 912
14.7.5 Copy on Write Arrays ............................................................... 912
14.7.6 Parallel Array Algorithms ........................................................ 912
14.7.7 Older Thread-Safe Collections ................................................. 914
14.8 Callables and Futures .............................................................................. 915
14.9 Executors ................................................................................................... 920
14.9.1 Thread Pools ............................................................................... 921
14.9.2 Scheduled Execution ................................................................. 926
14.9.3 Controlling Groups of Tasks .................................................... 927
14.9.4 The Fork-Join Framework ........................................................ 928
14.9.5 Completable Futures ................................................................. 931
14.10 Synchronizers ........................................................................................... 934
xviii Contents

14.10.1 Semaphores ................................................................................ 935


14.10.2 Countdown Latches .................................................................. 936
14.10.3 Barriers ........................................................................................ 936
14.10.4 Exchangers ................................................................................. 937
14.10.5 Synchronous Queues ................................................................ 937
14.11 Threads and Swing .................................................................................. 937
14.11.1 Running Time-Consuming Tasks ............................................ 939
14.11.2 Using the Swing Worker .......................................................... 943
14.11.3 The Single-Thread Rule ............................................................ 951
Appendix ...................................................................................................... 953

Index ............................................................................................................. 957


Preface

To the Reader
In late 1995, the Java programming language burst onto the Internet scene and
gained instant celebrity status. The promise of Java technology was that it would
become the universal glue that connects users with information wherever it comes
from—web servers, databases, information providers, or any other imaginable
source. Indeed, Java is in a unique position to fulfill this promise. It is an extremely
solidly engineered language that has gained wide acceptance. Its built-in security
and safety features are reassuring both to programmers and to the users of Java
programs. Java has built-in support for advanced programming tasks, such as
network programming, database connectivity, and concurrency.
Since 1995, nine major revisions of the Java Development Kit have been released.
Over the course of the last 20 years, the Application Programming Interface (API)
has grown from about 200 to over 4,000 classes. The API now spans such diverse
areas as user interface construction, database management, internationalization,
security, and XML processing.
The book you have in your hands is the first volume of the tenth edition of Core
Java®. Each edition closely followed a release of the Java Development Kit, and
each time, we rewrote the book to take advantage of the newest Java features.
This edition has been updated to reflect the features of Java Standard Edition
(SE) 8.
As with the previous editions of this book, we still target serious programmers who
want to put Java to work on real projects. We think of you, our reader, as a program-
mer with a solid background in a programming language other than Java, and
we assume that you don’t like books filled with toy examples (such as toasters,
zoo animals, or “nervous text”). You won’t find any of these in our book. Our
goal is to enable you to fully understand the Java language and library, not to
give you an illusion of understanding.
In this book you will find lots of sample code demonstrating almost every language
and library feature that we discuss. We keep the sample programs purposefully
simple to focus on the major points, but, for the most part, they aren’t fake and
they don’t cut corners. They should make good starting points for your own code.

xix
xx Preface

We assume you are willing, even eager, to learn about all the advanced features
that Java puts at your disposal. For example, we give you a detailed treatment of

• Object-oriented programming
• Reflection and proxies
• Interfaces and inner classes
• Exception handling
• Generic programming
• The collections framework
• The event listener model
• Graphical user interface design with the Swing UI toolkit
• Concurrency
With the explosive growth of the Java class library, a one-volume treatment of
all the features of Java that serious programmers need to know is no longer pos-
sible. Hence, we decided to break up the book into two volumes. The first volume,
which you hold in your hands, concentrates on the fundamental concepts of the
Java language, along with the basics of user-interface programming. The second
volume, Core Java®, Volume II—Advanced Features, goes further into the enterprise
features and advanced user-interface programming. It includes detailed discus-
sions of

• The Stream API


• File processing and regular expressions
• Databases
• XML processing
• Annotations
• Internationalization
• Network programming
• Advanced GUI components
• Advanced graphics
• Native methods
When writing a book, errors and inaccuracies are inevitable. We’d very much
like to know about them. But, of course, we’d prefer to learn about each of them
only once. We have put up a list of frequently asked questions, bug fixes, and
workarounds on a web page at http://horstmann.com/corejava. Strategically placed at
the end of the errata page (to encourage you to read through it first) is a form you
can use to report bugs and suggest improvements. Please don’t be disappointed
if we don’t answer every query or don’t get back to you immediately. We do read
Preface xxi

all e-mail and appreciate your input to make future editions of this book clearer
and more informative.

A Tour of This Book


Chapter 1 gives an overview of the capabilities of Java that set it apart from other
programming languages. We explain what the designers of the language set out
to do and to what extent they succeeded. Then, we give a short history of how
Java came into being and how it has evolved.
In Chapter 2, we tell you how to download and install the JDK and the program
examples for this book. Then we guide you through compiling and running three
typical Java programs—a console application, a graphical application, and an
applet—using the plain JDK, a Java-enabled text editor, and a Java IDE.
Chapter 3 starts the discussion of the Java language. In this chapter, we cover the
basics: variables, loops, and simple functions. If you are a C or C++ programmer,
this is smooth sailing because the syntax for these language features is essentially
the same as in C. If you come from a non-C background such as Visual Basic, you
will want to read this chapter carefully.
Object-oriented programming (OOP) is now in the mainstream of programming
practice, and Java is an object-oriented programming language. Chapter 4 intro-
duces encapsulation, the first of two fundamental building blocks of object orien-
tation, and the Java language mechanism to implement it—that is, classes and
methods. In addition to the rules of the Java language, we also give advice on
sound OOP design. Finally, we cover the marvelous javadoc tool that formats your
code comments as a set of hyperlinked web pages. If you are familiar with C++,
you can browse through this chapter quickly. Programmers coming from a non-
object-oriented background should expect to spend some time mastering the OOP
concepts before going further with Java.
Classes and encapsulation are only one part of the OOP story, and Chapter 5 in-
troduces the other—namely, inheritance. Inheritance lets you take an existing class
and modify it according to your needs. This is a fundamental technique for pro-
gramming in Java. The inheritance mechanism in Java is quite similar to that in
C++. Once again, C++ programmers can focus on the differences between the
languages.
Chapter 6 shows you how to use Java’s notion of an interface. Interfaces let you
go beyond the simple inheritance model of Chapter 5. Mastering interfaces allows
you to have full access to the power of Java’s completely object-oriented approach
to programming. After we cover interfaces, we move on to lambda expressions, a
xxii Preface

concise way for expressing a block of code that can be executed at a later point
in time. We then cover a useful technical feature of Java called inner classes.
Chapter 7 discusses exception handling—Java’s robust mechanism to deal with the
fact that bad things can happen to good programs. Exceptions give you an efficient
way of separating the normal processing code from the error handling. Of course,
even after hardening your program by handling all exceptional conditions, it still
might fail to work as expected. In the final part of this chapter, we give you a
number of useful debugging tips.
Chapter 8 gives an overview of generic programming. Generic programming
makes your programs easier to read and safer. We show you how to use strong
typing and remove unsightly and unsafe casts, and how to deal with the complex-
ities that arise from the need to stay compatible with older versions of Java.
The topic of Chapter 9 is the collections framework of the Java platform. When-
ever you want to collect multiple objects and retrieve them later, you should use
a collection that is best suited for your circumstances, instead of just tossing the
elements into an array. This chapter shows you how to take advantage of
the standard collections that are prebuilt for your use.
Chapter 10 starts the coverage of GUI programming. We show how you can make
windows, how to paint on them, how to draw with geometric shapes, how to
format text in multiple fonts, and how to display images.
Chapter 11 is a detailed discussion of the event model of the AWT, the abstract
window toolkit. You’ll see how to write code that responds to events, such as mouse
clicks or key presses. Along the way you’ll see how to handle basic GUI elements
such as buttons and panels.
Chapter 12 discusses the Swing GUI toolkit in great detail. The Swing toolkit al-
lows you to build cross-platform graphical user interfaces. You’ll learn all about
the various kinds of buttons, text components, borders, sliders, list boxes, menus,
and dialog boxes. However, some of the more advanced components are discussed
in Volume II.
Chapter 13 shows you how to deploy your programs, either as applications or
applets. We describe how to package programs in JAR files, and how to deliver
applications over the Internet with the Java Web Start and applet mechanisms.
We also explain how Java programs can store and retrieve configuration
information once they have been deployed.
Chapter 14 finishes the book with a discussion of concurrency, which enables
you to program tasks to be done in parallel. This is an important and exciting
Preface xxiii

application of Java technology in an era where most processors have multiple


cores that you want to keep busy.
The Appendix lists the reserved words of the Java language.

Conventions
As is common in many computer books, we use monospace type to represent
computer code.

NOTE: Notes are tagged with “note” icons that look like this.

TIP: Tips are tagged with “tip” icons that look like this.

CAUTION: When there is danger ahead, we warn you with a “caution” icon.

C++ NOTE: There are many C++ notes that explain the differences between
Java and C++. You can skip over them if you don’t have a background in C++
or if you consider your experience with that language a bad dream of which
you’d rather not be reminded.

Java comes with a large programming library, or Application Programming In-


terface (API). When using an API call for the first time, we add a short summary
description at the end of the section. These descriptions are a bit more informal
but, we hope, also a little more informative than those in the official online API
documentation. The names of interfaces are in italics, just like in the official doc-
umentation. The number after a class, interface, or method name is the JDK version
in which the feature was introduced, as shown in the following example:

Application Programming Interface 1.2


xxiv Preface

Programs whose source code is on the book’s companion web site are presented
as listings, for instance:

Listing 1.1 InputTest/InputTest.java

Sample Code
The web site for this book at http://horstmann.com/corejava contains all sample code
from the book, in compressed form. You can expand the file either with one of
the familiar unzipping programs or simply with the jar utility that is part of the
Java Development Kit. See Chapter 2 for more information on installing
the Java Development Kit and the sample code.
Acknowledgments
Writing a book is always a monumental effort, and rewriting it doesn’t seem to
be much easier, especially with the continuous change in Java technology. Making
a book a reality takes many dedicated people, and it is my great pleasure to
acknowledge the contributions of the entire Core Java team.
A large number of individuals at Prentice Hall provided valuable assistance but
managed to stay behind the scenes. I’d like them all to know how much I appre-
ciate their efforts. As always, my warm thanks go to my editor, Greg Doench, for
steering the book through the writing and production process, and for allowing
me to be blissfully unaware of the existence of all those folks behind the scenes.
I am very grateful to Julie Nahil for production support, and to Dmitry Kirsanov
and Alina Kirsanova for copyediting and typesetting the manuscript. My thanks
also to my coauthor of earlier editions, Gary Cornell, who has since moved on to
other ventures.
Thanks to the many readers of earlier editions who reported embarrassing errors
and made lots of thoughtful suggestions for improvement. I am particularly
grateful to the excellent reviewing team who went over the manuscript with an
amazing eye for detail and saved me from many embarrassing errors.
Reviewers of this and earlier editions include Chuck Allison (Utah Valley Univer-
sity), Lance Andersen (Oracle), Paul Anderson (Anderson Software Group), Alec
Beaton (IBM), Cliff Berg, Andrew Binstock (Oracle), Joshua Bloch, David Brown,
Corky Cartwright, Frank Cohen (PushToTest), Chris Crane (devXsolution),
Dr. Nicholas J. De Lillo (Manhattan College), Rakesh Dhoopar (Oracle), David
Geary (Clarity Training), Jim Gish (Oracle), Brian Goetz (Oracle), Angela Gordon,
Dan Gordon (Electric Cloud), Rob Gordon, John Gray (University of Hartford),
Cameron Gregory (olabs.com), Marty Hall (coreservlets.com, Inc.), Vincent Hardy
(Adobe Systems), Dan Harkey (San Jose State University), William Higgins (IBM),
Vladimir Ivanovic (PointBase), Jerry Jackson (CA Technologies), Tim Kimmet
(Walmart), Chris Laffra, Charlie Lai (Apple), Angelika Langer, Doug Langston,
Hang Lau (McGill University), Mark Lawrence, Doug Lea (SUNY Oswego),
Gregory Longshore, Bob Lynch (Lynch Associates), Philip Milne (consultant),
Mark Morrissey (The Oregon Graduate Institute), Mahesh Neelakanta (Florida
Atlantic University), Hao Pham, Paul Philion, Blake Ragsdell, Stuart Reges
(University of Arizona), Rich Rosen (Interactive Data Corporation), Peter Sanders
(ESSI University, Nice, France), Dr. Paul Sanghera (San Jose State University and

xxv
xxvi Acknowledgments

Brooks College), Paul Sevinc (Teamup AG), Devang Shah (Sun Microsystems),
Yoshiki Shibata, Bradley A. Smith, Steven Stelting (Oracle), Christopher Taylor,
Luke Taylor (Valtech), George Thiruvathukal, Kim Topley (StreamingEdge), Janet
Traub, Paul Tyma (consultant), Peter van der Linden, Christian Ullenboom, Burt
Walsh, Dan Xu (Oracle), and John Zavgren (Oracle).

Cay Horstmann
Biel/Bienne, Switzerland
November 2015
CHAPTER 6
Interfaces, Lambda
Expressions, and Inner Classes
In this chapter
• 6.1 Interfaces, page 288
• 6.2 Examples of Interfaces, page 302
• 6.3 Lambda Expressions, page 314
• 6.4 Inner Classes, page 329
• 6.5 Proxies, page 350

You have now seen all the basic tools for object-oriented programming in Java.
This chapter shows you several advanced techniques that are commonly used.
Despite their less obvious nature, you will need to master them to complete your
Java tool chest.
The first technique, called interfaces, is a way of describing what classes should
do, without specifying how they should do it. A class can implement one or more
interfaces. You can then use objects of these implementing classes whenever
conformance to the interface is required. After we cover interfaces, we move on
to lambda expressions, a concise way for expressing a block of code that can be

287
288 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

executed at a later point in time. Using lambda expressions, you can express code
that uses callbacks or variable behavior in an elegant and concise fashion.
We then discuss the mechanism of inner classes. Inner classes are technically
somewhat complex—they are defined inside other classes, and their methods can
access the fields of the surrounding class. Inner classes are useful when you design
collections of cooperating classes.
This chapter concludes with a discussion of proxies, objects that implement arbi-
trary interfaces. A proxy is a very specialized construct that is useful for building
system-level tools. You can safely skip that section on first reading.

6.1 Interfaces
In the following sections, you will learn what Java interfaces are and how to use
them. You will also find out how interfaces have been made more powerful in
Java SE 8.

6.1.1 The Interface Concept


In the Java programming language, an interface is not a class but a set of
requirements for the classes that want to conform to the interface.
Typically, the supplier of some service states: “If your class conforms to a partic-
ular interface, then I’ll perform the service.” Let’s look at a concrete example. The
sort method of the Arrays class promises to sort an array of objects, but under
one condition: The objects must belong to classes that implement the Comparable
interface.
Here is what the Comparable interface looks like:
public interface Comparable
{
int compareTo(Object other);
}

This means that any class that implements the Comparable interface is required to
have a compareTo method, and the method must take an Object parameter and return
an integer.
6.1 Interfaces 289

NOTE: As of Java SE 5.0, the Comparable interface has been enhanced to be a


generic type.
public interface Comparable<T>
{
int compareTo(T other); // parameter has type T
}
For example, a class that implements Comparable<Employee> must supply a method
int compareTo(Employee other)
You can still use the “raw” Comparable type without a type parameter. Then the
compareTo method has a parameter of type Object, and you have to manually cast
that parameter of the compareTo method to the desired type. We will do just that
for a little while so that you don’t have to worry about two new concepts at the
same time.

All methods of an interface are automatically public. For that reason, it is not
necessary to supply the keyword public when declaring a method in an interface.
Of course, there is an additional requirement that the interface cannot spell out:
When calling x.compareTo(y), the compareTo method must actually be able to compare
the two objects and return an indication whether x or y is larger. The method is
supposed to return a negative number if x is smaller than y, zero if they are equal,
and a positive number otherwise.
This particular interface has a single method. Some interfaces have multiple
methods. As you will see later, interfaces can also define constants. What is more
important, however, is what interfaces cannot supply. Interfaces never have in-
stance fields. Before Java SE 8, methods were never implemented in interfaces.
(As you will see in Section 6.1.4, “Static Methods,” on p. 298 and Section 6.1.5,
“Default Methods,” on p. 298, it is now possible to supply simple methods in in-
terfaces. Of course, those methods cannot refer to instance fields—interfaces don’t
have any.)
Supplying instance fields and methods that operate on them is the job of the
classes that implement the interface. You can think of an interface as being similar
to an abstract class with no instance fields. However, there are some differences
between these two concepts—we look at them later in some detail.
290 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

Now suppose we want to use the sort method of the Arrays class to sort an array
of Employee objects. Then the Employee class must implement the Comparable interface.
To make a class implement an interface, you carry out two steps:

1. You declare that your class intends to implement the given interface.
2. You supply definitions for all methods in the interface.
To declare that a class implements an interface, use the implements keyword:
class Employee implements Comparable

Of course, now the Employee class needs to supply the compareTo method. Let’s suppose
that we want to compare employees by their salary. Here is an implementation
of the compareTo method:
public int compareTo(Object otherObject)
{
Employee other = (Employee) otherObject;
return Double.compare(salary, other.salary);
}

Here, we use the static Double.compare method that returns a negative if the first ar-
gument is less than the second argument, 0 if they are equal, and a positive value
otherwise.

CAUTION: In the interface declaration, the compareTo method was not declared
public because all methods in an interface are automatically public. However,
when implementing the interface, you must declare the method as public. Other-
wise, the compiler assumes that the method has package visibility—the default
for a class. The compiler then complains that you’re trying to supply a more
restrictive access privilege.

We can do a little better by supplying a type parameter for the generic Comparable
interface:
class Employee implements Comparable<Employee>
{
public int compareTo(Employee other)
{
return Double.compare(salary, other.salary);
}
...
}

Note that the unsightly cast of the Object parameter has gone away.
6.1 Interfaces 291

TIP: The compareTo method of the Comparable interface returns an integer. If the
objects are not equal, it does not matter what negative or positive value you re-
turn. This flexibility can be useful when you are comparing integer fields. For
example, suppose each employee has a unique integer id and you want to sort
by the employee ID number. Then you can simply return id - other.id. That value
will be some negative value if the first ID number is less than the other, 0 if they
are the same ID, and some positive value otherwise. However, there is one
caveat: The range of the integers must be small enough so that the subtraction
does not overflow. If you know that the IDs are not negative or that their absolute
value is at most (Integer.MAX_VALUE - 1) / 2, you are safe. Otherwise, call the static
Integer.compare method.

Of course, the subtraction trick doesn’t work for floating-point numbers. The
difference salary - other.salary can round to 0 if the salaries are close together
but not identical. The call Double.compare(x, y) simply returns -1 if x < y or 1 if x > y.

NOTE: The documentation of the Comparable interface suggests that the compareTo
method should be compatible with the equals method.That is, x.compareTo(y) should
be zero exactly when x.equals(y). Most classes in the Java API that implement
Comparable follow this advice. A notable exception is BigDecimal. Consider x = new
BigDecimal("1.0") and y = new BigDecimal("1.00"). Then x.equals(y) is false because
the numbers differ in precision. But x.compareTo(y) is zero. Ideally, it shouldn’t be,
but there was no obvious way of deciding which one should come first.

Now you saw what a class must do to avail itself of the sorting service—it must
implement a compareTo method. That’s eminently reasonable. There needs to be
some way for the sort method to compare objects. But why can’t the Employee class
simply provide a compareTo method without implementing the Comparable interface?
The reason for interfaces is that the Java programming language is strongly typed.
When making a method call, the compiler needs to be able to check that the
method actually exists. Somewhere in the sort method will be statements like this:
if (a[i].compareTo(a[j]) > 0)
{
// rearrange a[i] and a[j]
...
}

The compiler must know that a[i] actually has a compareTo method. If a is an array
of Comparable objects, then the existence of the method is assured because every class
that implements the Comparable interface must supply the method.
292 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

NOTE: You would expect that the sort method in the Arrays class is defined to
accept a Comparable[] array so that the compiler can complain if anyone ever calls
sort with an array whose element type doesn’t implement the Comparable interface.
Sadly, that is not the case. Instead, the sort method accepts an Object[] array
and uses a clumsy cast:
// Approach used in the standard library--not recommended
if (((Comparable) a[i]).compareTo(a[j]) > 0)
{
// rearrange a[i] and a[j]
...
}
If a[i] does not belong to a class that implements the Comparable interface, the
virtual machine throws an exception.

Listing 6.1 presents the full code for sorting an array of instances of the class
Employee (Listing 6.2) for sorting an employee array.

Listing 6.1 interfaces/EmployeeSortTest.java

1 package interfaces;
2
3 import java.util.*;
4
5 /**
6 * This program demonstrates the use of the Comparable interface.
7 * @version 1.30 2004-02-27
8 * @author Cay Horstmann
9 */
10 public class EmployeeSortTest
11 {
12 public static void main(String[] args)
13 {
14 Employee[] staff = new Employee[3];
15
16 staff[0] = new Employee("Harry Hacker", 35000);
17 staff[1] = new Employee("Carl Cracker", 75000);
18 staff[2] = new Employee("Tony Tester", 38000);
19
20 Arrays.sort(staff);
21
22 // print out information about all Employee objects
23 for (Employee e : staff)
24 System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
25 }
26 }
6.1 Interfaces 293

Listing 6.2 interfaces/Employee.java

1 package interfaces;
2
3 public class Employee implements Comparable<Employee>
4 {
5 private String name;
6 private double salary;
7
8 public Employee(String name, double salary)
9 {
10 this.name = name;
11 this.salary = salary;
12 }
13
14 public String getName()
15 {
16 return name;
17 }
18
19 public double getSalary()
20 {
21 return salary;
22 }
23
24 public void raiseSalary(double byPercent)
25 {
26 double raise = salary * byPercent / 100;
27 salary += raise;
28 }
29
30 /**
31 * Compares employees by salary
32 * @param other another Employee object
33 * @return a negative value if this employee has a lower salary than
34 * otherObject, 0 if the salaries are the same, a positive value otherwise
35 */
36 public int compareTo(Employee other)
37 {
38 return Double.compare(salary, other.salary);
39 }
40 }

java.lang.Comparable<T> 1.0

• int compareTo(T other)


compares this object with other and returns a negative integer if this object is less
than other, zero if they are equal, and a positive integer otherwise.
294 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

java.util.Arrays 1.2

• static void sort(Object[] a)


sorts the elements in the array a. All elements in the array must belong to classes
that implement the Comparable interface, and they must all be comparable to each
other.

java.lang.Integer 1.0

• static int compare(int x, int y) 7


returns a negative integer if x < y, zero if x and y are equal, and a positive integer
otherwise.

java.lang.Double 1.0

• static int compare(double x, double y) 1.4


returns a negative integer if x < y, zero if x and y are equal, and a positive integer
otherwise.

NOTE: According to the language standard: “The implementor must ensure


sgn(x.compareTo(y)) = -sgn(y.compareTo(x)) for all x and y. (This implies that
x.compareTo(y) must throw an exception if y.compareTo(x) throws an exception.)”
Here, sgn is the sign of a number: sgn(n) is –1 if n is negative, 0 if n equals 0,
and 1 if n is positive. In plain English, if you flip the parameters of compareTo, the
sign (but not necessarily the actual value) of the result must also flip.

As with the equals method, problems can arise when inheritance comes into play.

Since Manager extends Employee, it implements Comparable<Employee> and not


Comparable<Manager>. If Manager chooses to override compareTo, it must be prepared to
compare managers to employees. It can’t simply cast an employee to a manager:
class Manager extends Employee
{
public int compareTo(Employee other)
{
Manager otherManager = (Manager) other; // NO
...
}
...
}
6.1 Interfaces 295

That violates the “antisymmetry” rule. If x is an Employee and y is a Manager, then


the call x.compareTo(y) doesn’t throw an exception—it simply compares x and y
as employees. But the reverse, y.compareTo(x), throws a ClassCastException.

This is the same situation as with the equals method that we discussed in
Chapter 5, and the remedy is the same. There are two distinct scenarios.

If subclasses have different notions of comparison, then you should outlaw


comparison of objects that belong to different classes. Each compareTo method
should start out with the test
if (getClass() != other.getClass()) throw new ClassCastException();
If there is a common algorithm for comparing subclass objects, simply provide
a single compareTo method in the superclass and declare it as final.

For example, suppose you want managers to be better than regular employees,
regardless of salary.What about other subclasses such as Executive and Secretary?
If you need to establish a pecking order, supply a method such as rank in the
Employee class. Have each subclass override rank, and implement a single compareTo
method that takes the rank values into account.

6.1.2 Properties of Interfaces


Interfaces are not classes. In particular, you can never use the new operator to
instantiate an interface:
x = new Comparable(. . .); // ERROR

However, even though you can’t construct interface objects, you can still declare
interface variables.
Comparable x; // OK

An interface variable must refer to an object of a class that implements the


interface:
x = new Employee(. . .); // OK provided Employee implements Comparable

Next, just as you use instanceof to check whether an object is of a specific class, you
can use instanceof to check whether an object implements an interface:
if (anObject instanceof Comparable) { . . . }

Just as you can build hierarchies of classes, you can extend interfaces. This allows
for multiple chains of interfaces that go from a greater degree of generality to a
greater degree of specialization. For example, suppose you had an interface called
Moveable.
296 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

public interface Moveable


{
void move(double x, double y);
}

Then, you could imagine an interface called Powered that extends it:
public interface Powered extends Moveable
{
double milesPerGallon();
}

Although you cannot put instance fields or static methods in an interface, you
can supply constants in them. For example:
public interface Powered extends Moveable
{
double milesPerGallon();
double SPEED_LIMIT = 95; // a public static final constant
}

Just as methods in an interface are automatically public, fields are always public
static final.

NOTE: It is legal to tag interface methods as public, and fields as public static
final. Some programmers do that, either out of habit or for greater clarity. How-
ever, the Java Language Specification recommends that the redundant keywords
not be supplied, and we follow that recommendation.

Some interfaces define just constants and no methods. For example, the standard
library contains an interface SwingConstants that defines constants NORTH, SOUTH, HORIZONTAL,
and so on. Any class that chooses to implement the SwingConstants interface automat-
ically inherits these constants. Its methods can simply refer to NORTH rather than
the more cumbersome SwingConstants.NORTH. However, this use of interfaces seems
rather degenerate, and we do not recommend it.
While each class can have only one superclass, classes can implement multiple
interfaces. This gives you the maximum amount of flexibility in defining a class’s
behavior. For example, the Java programming language has an important interface
built into it, called Cloneable. (We will discuss this interface in detail in Section 6.2.3,
“Object Cloning,” on p. 306.) If your class implements Cloneable, the clone method
in the Object class will make an exact copy of your class’s objects. If you want both
cloneability and comparability, simply implement both interfaces. Use commas
to separate the interfaces that you want to implement:
class Employee implements Cloneable, Comparable
6.1 Interfaces 297

6.1.3 Interfaces and Abstract Classes


If you read the section about abstract classes in Chapter 5, you may wonder why
the designers of the Java programming language bothered with introducing the
concept of interfaces. Why can’t Comparable simply be an abstract class:
abstract class Comparable // why not?
{
public abstract int compareTo(Object other);
}

The Employee class would then simply extend this abstract class and supply the
compareTo method:

class Employee extends Comparable // why not?


{
public int compareTo(Object other) { . . . }
}

There is, unfortunately, a major problem with using an abstract base class to ex-
press a generic property. A class can only extend a single class. Suppose the
Employee class already extends a different class, say, Person. Then it can’t extend a
second class.
class Employee extends Person, Comparable // Error

But each class can implement as many interfaces as it likes:


class Employee extends Person implements Comparable // OK

Other programming languages, in particular C++, allow a class to have more


than one superclass. This feature is called multiple inheritance. The designers of
Java chose not to support multiple inheritance, because it makes the language
either very complex (as in C++) or less efficient (as in Eiffel).
Instead, interfaces afford most of the benefits of multiple inheritance while
avoiding the complexities and inefficiencies.

C++ NOTE: C++ has multiple inheritance and all the complications that come
with it, such as virtual base classes, dominance rules, and transverse pointer
casts. Few C++ programmers use multiple inheritance, and some say it should
never be used. Other programmers recommend using multiple inheritance only
for the “mix-in” style of inheritance. In the mix-in style, a primary base class de-
scribes the parent object, and additional base classes (the so-called mix-ins)
may supply auxiliary characteristics. That style is similar to a Java class with a
single superclass and additional interfaces.
298 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

6.1.4 Static Methods


As of Java SE 8, you are allowed to add static methods to interfaces. There was
never a technical reason why this should be outlawed. It simply seemed to be
against the spirit of interfaces as abstract specifications.
Up to now, it has been common to place static methods in companion classes. In
the standard library, you find pairs of interfaces and utility classes such as
Collection/Collections or Path/Paths.

Have a look at the Paths class. It only has a couple of factory methods. You can
construct a path to a file or directory from a sequence of strings, such as
Paths.get("jdk1.8.0", "jre", "bin"). In Java SE 8, one could have added this method to
the Path interface:
public interface Path
{
public static Path get(String first, String... more) {
return FileSystems.getDefault().getPath(first, more);
}
...
}

Then the Paths class is no longer necessary.


It is unlikely that the Java library will be refactored in this way, but when you
implement your own interfaces, there is no longer a reason to provide a separate
companion class for utility methods.

6.1.5 Default Methods


You can supply a default implementation for any interface method. You must tag
such a method with the default modifier.
public interface Comparable<T>
{
default int compareTo(T other) { return 0; }
// By default, all elements are the same
}

Of course, that is not very useful since every realistic implementation of Comparable
would override this method. But there are other situations where default methods
can be useful. For example, as you will see in Chapter 11, if you want to be notified
when a mouse click happens, you are supposed to implement an interface that
has five methods:
6.1 Interfaces 299

public interface MouseListener


{
void mouseClicked(MouseEvent event);
void mousePressed(MouseEvent event);
void mouseReleased(MouseEvent event);
void mouseEntered(MouseEvent event);
void mouseExited(MouseEvent event);
}

Most of the time, you only care about one or two of these event types. As of Java
SE 8, you can declare all of the methods as default methods that do nothing.
public interface MouseListener
{
default void mouseClicked(MouseEvent event) {}
default void mousePressed(MouseEvent event) {}
default void mouseReleased(MouseEvent event) {}
default void mouseEntered(MouseEvent event) {}
default void mouseExited(MouseEvent event) {}
}

Then programmers who implement this interface only need to override the
listeners for the events they actually care about.
A default method can call other methods. For example, a Collection interface can
define a convenience method
public interface Collection
{
int size(); // An abstract method
default boolean isEmpty()
{
return size() == 0;
}
...
}

Then a programmer implementing Collection doesn’t have to worry about


implementing an isEmpty method.

NOTE: In the Java API, you will find a number of interfaces with companion
classes that implement some or all of its methods, such as Collection/
AbstractCollection or MouseListener/MouseAdapter. With Java SE 8, this technique is
obsolete. Just implement the methods in the interface.

An important use for default methods is interface evolution. Consider for example
the Collection interface that has been a part of Java for many years. Suppose that a
long time ago, you provided a class
300 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

public class Bag implements Collection

Later, in Java SE 8, a stream method was added to the interface.


Suppose the stream method was not a default method. Then the Bag class no longer
compiles since it doesn’t implement the new method. Adding a nondefault method
to an interface is not source compatible.
But suppose you don’t recompile the class and simply use an old JAR file contain-
ing it. The class will still load, even with the missing method. Programs can still
construct Bag instances, and nothing bad will happen. (Adding a method to an
interface is binary compatible.) However, if a program calls the stream method on a
Bag instance, an AbstractMethodError occurs.

Making the method a default method solves both problems. The Bag class will again
compile. And if the class is loaded without being recompiled and the stream method
is invoked on a Bag instance, the Collection.stream method is called.

6.1.6 Resolving Default Method Conflicts


What happens if the exact same method is defined as a default method in one
interface and then again as a method of a superclass or another interface? Lan-
guages such as Scala and C++ have complex rules for resolving such ambiguities.
Fortunately, the rules in Java are much simpler. Here they are:

1. Superclasses win. If a superclass provides a concrete method, default methods


with the same name and parameter types are simply ignored.
2. Interfaces clash. If a superinterface provides a default method, and another
interface supplies a method with the same name and parameter types (default
or not), then you must resolve the conflict by overriding that method.
Let’s look at the second rule. Consider another interface with a getName method:
interface Named
{
default String getName() { return getClass().getName() + "_" + hashCode(); }
}

What happens if you form a class that implements both of them?


class Student implements Person, Named
{
...
}

The class inherits two inconsistent getName methods provided by the Person and Named
interfaces. Instead of choosing one over the other, the Java compiler reports an
6.1 Interfaces 301

error and leaves it up to the programmer to resolve the ambiguity. Simply provide
a getName method in the Student class. In that method, you can choose one of the two
conflicting methods, like this:
class Student implements Person, Named
{
public String getName() { return Person.super.getName(); }
...
}

Now assume that the Named interface does not provide a default implementation
for getName:
interface Named
{
String getName();
}

Can the Student class inherit the default method from the Person interface? This
might be reasonable, but the Java designers decided in favor of uniformity. It
doesn’t matter how two interfaces conflict. If at least one interface provides an
implementation, the compiler reports an error, and the programmer must resolve
the ambiguity.

NOTE: Of course, if neither interface provides a default for a shared method,


then we are in the situation before Java SE 8, and there is no conflict. An imple-
menting class has two choices: implement the method, or leave it unimplemented.
In the latter case, the class is itself abstract.

We just discussed name clashes between two interfaces. Now consider a class
that extends a superclass and implements an interface, inheriting the same method
from both. For example, suppose that Person is a class and Student is defined as
class Student extends Person implements Named { . . . }

In that case, only the superclass method matters, and any default method from
the interface is simply ignored. In our example, Student inherits the getName method
from Person, and it doesn’t make any difference whether the Named interface provides
a default for getName or not. This is the “class wins” rule.
The “class wins” rule ensures compatibility with Java SE 7. If you add default
methods to an interface, it has no effect on code that worked before there were
default methods.
302 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

CAUTION: You can never make a default method that redefines one of the
methods in the Object class. For example, you can’t define a default method for
toString or equals, even though that might be attractive for interfaces such as List.
As a consequence of the “classes win” rule, such a method could never win
against Object.toString or Objects.equals.

6.2 Examples of Interfaces


In the next three sections, we give additional examples of interfaces so you can
see how they are used in practice.

6.2.1 Interfaces and Callbacks


A common pattern in programming is the callback pattern. In this pattern, you
specify the action that should occur whenever a particular event happens. For
example, you may want a particular action to occur when a button is clicked or
a menu item is selected. However, as you have not yet seen how to implement
user interfaces, we will consider a similar but simpler situation.
The javax.swing package contains a Timer class that is useful if you want to be notified
whenever a time interval has elapsed. For example, if a part of your program
contains a clock, you can ask to be notified every second so that you can update
the clock face.
When you construct a timer, you set the time interval and you tell it what it should
do whenever the time interval has elapsed.
How do you tell the timer what it should do? In many programming languages,
you supply the name of a function that the timer should call periodically. How-
ever, the classes in the Java standard library take an object-oriented approach.
You pass an object of some class. The timer then calls one of the methods on that
object. Passing an object is more flexible than passing a function because the object
can carry additional information.
Of course, the timer needs to know what method to call. The timer requires that
you specify an object of a class that implements the ActionListener interface of the
java.awt.event package. Here is that interface:

public interface ActionListener


{
void actionPerformed(ActionEvent event);
}

The timer calls the actionPerformed method when the time interval has expired.
6.2 Examples of Interfaces 303

Suppose you want to print a message “At the tone, the time is . . .”, followed by
a beep, once every 10 seconds. You would define a class that implements the
ActionListener interface. You would then place whatever statements you want to
have executed inside the actionPerformed method.
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is " + new Date());
Toolkit.getDefaultToolkit().beep();
}
}

Note the ActionEvent parameter of the actionPerformed method. This parameter gives
information about the event, such as the source object that generated it—see
Chapter 11 for more information. However, detailed information about the event
is not important in this program, and you can safely ignore the parameter.
Next, you construct an object of this class and pass it to the Timer constructor.
ActionListener listener = new TimePrinter();
Timer t = new Timer(10000, listener);

The first parameter of the Timer constructor is the time interval that must elapse
between notifications, measured in milliseconds. We want to be notified every
10 seconds. The second parameter is the listener object.
Finally, you start the timer.
t.start();

Every 10 seconds, a message like


At the tone, the time is Wed Apr 13 23:29:08 PDT 2016

is displayed, followed by a beep.


Listing 6.3 puts the timer and its action listener to work. After the timer is started,
the program puts up a message dialog and waits for the user to click the OK
button to stop. While the program waits for the user, the current time is displayed
at 10-second intervals.
Be patient when running the program. The “Quit program?” dialog box appears
right away, but the first timer message is displayed after 10 seconds.
Note that the program imports the javax.swing.Timer class by name, in addition to
importing javax.swing.* and java.util.*. This breaks the ambiguity between
javax.swing.Timer and java.util.Timer, an unrelated class for scheduling background
tasks.
304 Chapter 6 Interfaces, Lambda Expressions, and Inner Classes

Listing 6.3 timer/TimerTest.java

1 package timer;
2
3 /**
4 @version 1.01 2015-05-12
5 @author Cay Horstmann
6 */
7
8 import java.awt.*;
9 import java.awt.event.*;
10 import java.util.*;
11 import javax.swing.*;
12 import javax.swing.Timer;
13 // to resolve conflict with java.util.Timer
14
15 public class TimerTest
16 {
17 public static void main(String[] args)
18 {
19 ActionListener listener = new TimePrinter();
20
21 // construct a timer that calls the listener
22 // once every 10 seconds
23 Timer t = new Timer(10000, listener);
24 t.start();
25
26 JOptionPane.showMessageDialog(null, "Quit program?");
27 System.exit(0);
28 }
29 }
30
31 class TimePrinter implements ActionListener
32 {
33 public void actionPerformed(ActionEvent event)
34 {
35 System.out.println("At the tone, the time is " + new Date());
36 Toolkit.getDefaultToolkit().beep();
37 }
38 }

javax.swing.JOptionPane 1.2

• static void showMessageDialog(Component parent, Object message)


displays a dialog box with a message prompt and an OK button. The dialog is
centered over the parent component. If parent is null, the dialog is centered on the
screen.
Other documents randomly have
different content
ninguna palabra que Elicio dijo ó cantó, dejó de ser dellos oida y aun
notada. Estaba Eli 
LA GALATEA cío ©n compañía de su amigo Erastro, de
quien pocas veces se apartaba por el eiitreteniuiieuto y gusto que de
su buena conversación recebia, y todos ó los mas ratos
(loldiaencantary tañerse les pasaba; y á este punto, tocando su rabel
Elicioy su zampona Erastro, á estos \ersos dio principio Elicio. ,^
ELICIO. Rendido i un amoroso pensamiento Con mi dolor conten fo.
Sin esperar oías gloria , Sigo la que persigue mi memoria. Porque
con tino en ella se presenta De los brazos de amor libre y exenta.
Con los ojos del alma aun no es posible Ver el rostro apacible De la
enemiga niia, Gloria y honor de cuanto el cielo cria, Y los del cuerpo
quedan solo en vella Ciegos, por haber visto el sol en ella. ¡ Uh dura
servidumbre, aunque gustosa ! Oh mano poderosa De amor, que asi
pudiste Quitarme, ingiato, el bien que prometiste De hacerme,
cuando libre me burlaba De ti , del arco tuyo y de tu aljaba I ¡
Cuánta belleza , cuánta blanca mano Me mostraste tirano ! ¡Cuánto
te fatigaste Primero que á mi cuello el lazo echaste! Y aun quedaras
vencido en la pelea, Si no hubiera en el mundo Calatea. Ella fué sola
la que sola pudo Rendir el golpe crudo De corazón exento , Y'
avasallar el libre pensamiento. El cual , si á su querer no se rindiera ,
Por de mármol ó acero le tuviera. ¿Qué libertad puede mostrar su
fuero Ante el rostro severo Y mas que el sol hermoso De la que
turba y causa mi reposo? jAy rostro, que en el suelo Descubres
cuanto bien encierra el ciclo! ;Cómo pudo juntar naturaleza Tai rigor
y aspereza Con tanta hermosura , Tanto valor y condición tan dura?
Mas mi dicha consiente En mi daño juntarlo diferente. Esle tan fácil á
mi corla suerte Ver con la amarga muerte Junta la dulce vida , Y
estar su mal á do su bien anida , Que entre contrarios veo Que
mengua la esperanza , y no el deseo. No cantó mas el enamorado
pastor, ni quisieron mas detenerse Tirsi y Damon, antes haciendo
gallarda é improvisa muestra, hacia donde estaba EHcio se fueron, el
cual como los vio, conociendo á su amigo Damon, con increíble
alegría le salió á recebir, diciéndole : ¿Qué ventura ha ordenado,
discreto Damon, que la des tan buena con tu presencia á estas
riberas, que grandes tiempos ha que te desean? No puede ser sino
buena, respondió Damon, pues me ha traído á verte, ó Elicio, cosa
que yo estimo en tanto cuanto es el deseo que de ello tenia, y la
larga ausencia y la amistad que te tengo me obligaba; pero si por
alguna cosa puedes decirlo que has dicho, es porque tienes delante
al famoso Tirsi, gloria y honor del castellano suelo. Cuando Elicio oyó
decir que aquel era Tirsi , de él solamente por fama conocido,
recibiéndole con muciía cortesía, le dijo : Bien rouforma tu agradable
semblante, nombrado Tirsi, con lo que de tu valor y discreción en las
cercanas y apartadas tierras la parlera fama pregona; y así, á mí á
quien tusescritos han admirado é inclinado á desear conocerte y
servirte, puedes de hoy mas tener y tratar como verdadero amigo.
Es tan conocido lo que yo gano en eso, respondió Tirsi, qiie en vano
pregonaría la fama lo que la afición que me tienes te hace decir que
de mi pre, LIRRO II. 23 gona, si no conociese la merced que me
haces en querer ponerme en el número de tus amigos ; y porque
entre los que lo son, las palabras de comedimiento han de ser
excusadas, cesen las nuestras en este caso, y den las obras
testimonio de nuestras voluntades. La mía será contíno de servirte ,
replicó Elicio, como lo verás, ó Tirsi, si el tiempo ó la fortuna me
ponen en estado que valga algo para ello ; porque el que agora
tengo, puesto que no le trocaría con otro de mayores ventajas, es
tal, que apenas me deja con libertad de ofrecer el deseo. Teniendo
como tienes el tuyo en lugar tan alto, dijo Damon, por locura tendría
procurar bajarle á cosa que menos fuese; y así, amigo Elicio, no
digas mal del estado en que te hallas, porque yo te prometo, que
cuando se comparase con el mío, hallaría yo ocasión de tenerte mas
envidia que lástima. Bien parece, Damon, dijo Elicio, que ha muchos
días que faltas destas riberas, pues no sabes lo que en ellas amor
me hace sentir; y si esto no es, no debes conocer, ni tener
experiencia de la condición de Calatea, que si della tuvieses noticia,
trocarías en lástima la envidia que de mí tendrías. Quien ha gustado
de la condición de Amarili, ¿qué cosa nueva puede esperar de la de
Calatea? respondió Damon. Si la estada tuya en estas riberas, replicó
Elicio, fuere tan larga como yo deseo, tú, Damon, conocerás y vei\ás
en ellas, y oirás en otras cómo andan en igual balanza su crueldad y
gentileza : extremos que acaban la vida al que su desventura trujo á
términos de adorarla. En las riberas de nuestro Henares, dijo á esta
sazón Tirsi, mas fama tenía Calateada hermosa que de cruel; pero
sobre todo se dice que es discreta ; y si esta es la verdad , como lo
debe ser , de su discreción nace el conocerse, y de conocerse
estimarse, y de estimarse no querer perderse, y del no querer
perderse viene el no querer contentarte; y viendo tú , Elicio, cuan
mal coiTcsponde á tus deseos, das nombre de crueldad á lo que
debías llamar honroso recato; y no me maravillo, que en fin es
condición propia de los enamorados poco favorecidos. Razón
tendrías en lo que has dicho, ó Tirsi, replicó Elicio, cuando mis
deseos se desviaran del camino que á su honra y honestidad
conviene ; pero si van tan medidos como á su valory crédito se
debe, ¿de qué sirve tanto desden, tan amargas y desabridas
respuestas, y tan á la clara esconder el rostro al que tiene puesta
toda su gloria en solo verle? i Ay, Tirsi, Tirsi! respondió Elicio, ¡y
cómo te debe tener el amor puesto en lo alto de sus contentos, pues
con tan sosegado espíritu hablas de sus efectos ! No sé yo cómo
viene bien lo que tú agora dices, con loque un tiempo decías cuando
cantabas : ¡Ay de cuan ricas esperanzas vengo Al deseo mas pobre y
encogido ! con lo demás que á esto añadiste. Hasta este punto
había estado callando Erastro, mirándolo que éntrelos pastores
pasaba, admirado de ver su gentil donaire y apostura, con las
muestras que cada uno daba de la mucha discreción que tenía, Pero
viendo quede lance en lance á razonar de casos de amor se habían
rctiucido, como aquel que tan experimentado en ellos estaba,
rompió el silencio, y dijo : Bien creo, discretos pastores, que la larga
experiencia os habrá mostrado que no se puede reducir á
continuado término la condición de los enamorados corazones, los
cuales como se gobiernan
The text on this page is estimated to be only 28.81%
accurate

24 OBRAS DE por voluntad ajena, á mil contrarios


accidentes están sujetos; y así tú, famoso Tirsi, no tienes de qué
maravillarle de lo que Eiicio lia dicho, ni él tampoco de lo que tú
dices, ni traer por ejemplo aquello que el dice que cantabas, ni
menos lo que yo sé que cantaste cuando dijiste : La amarillez y la
flaqueza mía , donde claramente mostrabas el afligido estado que
enlÓMces posi'iiis, porque de alli á puco llegaron ;i nuestras cab;»
ñas las nuevas de tu contento, soleuizadas en aquellos versos tan
nombrados tuyos, que si mal no me acuerdo comenzaban : Sale el
aurora , y de su fértil mano. Por do claro se conoce la diferoucia que
iiay de tiempos á tiempos, y cómo con ellos suele miniar auior los
estados, liacitiudo que boy se ria el que ayer lloraba, y que mañana
llore el que iioy lie. Y por Lener yo lau conocida esla su condición, no
puede la aspereza y desdeu zahareño de Galaica acabar de derribar
mis esperanzas, puesto que yo no espero de ella olra cosa, sino es
que se coulonle de que yo la quiera. El que no esperase buen suceso
de un tan enamorado y medido deseo como el que has moslrado, ó
pastor, respondió Damou, renombre mas que de desesperado
merecía : por cierto quees gran cosa loque dcGalalea pretendes.
Perodime, pastor, así ella te la conceda : ¿es posible que tan á regla
tienes tu deseo, que no se adelanta á desear mas de loque has
dicho? Bien puedes creeile, amigo Üamon, dijo Elicio, porque el valor
de Calatea no da lugar á que de ella otra cosa se desee ni se espere,
y aun osla es tan dificil de obtenerse , que á veces á Eiaslro se
entibia la esperanza y á mí se enlVia, de manera que él tiene por
cierto, y yo por averiguado, que primero ha de llegar la muerte que
el cumplimiento dclla. Mas porque no es razón recebir tan honrados
huéspedes con los amargos cuentos de nuestras miserias, quédense
ellas aquí, y recojámonos al aldea, donde descansaréis del pesado
trabajo del camino, y con mas sosiego, si de ello gustáredes,
entenderéis el desasosiego nuestro. Holgaron todos de acomodarse
á la voluntad de Elicio, el cual y Erastro, recogiendo sus ganados,
puesto que era algunas lloras antes de lo acostinnbrado, en
compañía de los dos pastores, hablando en diversas cosas, aunque
todas enamoradas, hacia el aldea se eiicaminaion. Mas como todo el
pasatiempo de Erastro era tañer y cantar, asi por esto como por el
deseo que tenia de saber si los dos nuevos pastores lo hacían tan
bien como de ellos se sonaba, por moverlos y convidarlos á que otro
tanto hiciesen, rogó á Elicio que su rabel tocase, al son del cual así
comenzó á cantar. ERASTRO. Ante la luz de unos serenos ojos Que
al sol dan luz con que da luz ai suilo, Mi alma asi se encicndi.', que
rerelo Que presto tendr.is, muerte, sus despojos. (Ion la luz se
conciertan los manojos De aquellos rayos del señor de Délo : Tales
son los c;;bellos de quien suelo Adorar su beldad puesto de hinojos.
¡Oh clara luz, uli rayos del sol claro. Antes el mismo sol ! de vos
espero Solo que consintáis que Krastro os quiera. Si en esto el rielo
se me muestra avaro, Antes que acabe del dolor que muero , Haced,
ó rayos, que de un rayo muera. No les pareció mal el soneto á los
pastores, ni les descontentó la voz de Erastro, que puesto que no
era de las CERVANTES. muy extremadas, no dejaba de ser de las
acordadas, y luego Elicio, movido del ejemplo de Era>tro, le hizo
que tocase su zampona, al son de la cual este soneto dijo. ELICIO. I
At, que al alto designio qne se cría En mi amoroso (Irme
pensamiento. Contradicen el cielo, el fuego, el viento. La agua , la
tierra y la enemiga mia ! Ciintrarios son ric quien temer debria , Y
abandonar la empresa y sano intento; Mas ¿quién podrá eslnrbar lo
que el vioicnt* Hado iiniilarable (juiere , amor porfía? Kl alto cíelo,
amor, el viento, el fuego. La agua , la tierra y mi enemiga bella ,
Cada cual con fuerza , y con mi liado, Mi bien estorbe, esparza,
abrase, y luego Deshaga mi esperanza ; iiue aun sin ella Imposible
es dejar lo comenzado. En acabando Elicio, luego Damon al son de
la mesm;i zampona de Erastro, desta manera comenzó á cantar.
DAMOX. Mas blando fui que no la blanda cera, Cuando Imprimí en
mí alma la ligura De la bella Amaríli , esquiva y dura , Cuai lluro
mármol ó silvestre (lera. Amor me puso entonces en la esfera Mas
alta de su bien y su ventura ; Agora temo que la sepultura Ha de
acabar mí presunción primera. Arrimóse el amor á la esperanza ,
Cual vid al olmo, y fue subiendo apriesa , Mas fallóle el liuuior y cesó
el vuelo: No el de mis ojos, "que por larga usanza Fortuna sabe bien
, que jamas cesa De dar tributo al rostro, al pecho, al suelo. Acabó
Ü;imon, y comenzó Tirsi al son de los instrumeulüs de los tres
pastores á cantar este soneto. TIRSI. Por medio de los filos de la
muerte Rompió mi fe, y á tal punto he llegado. Que uo envidio el
mas alto y rico estado Que encierra humana venturosa suerte. Todo
este bien nació de solo verle, Fíermosa Fili , ó Fili , á quien el hado
Doló de un ser tan raro y extremado, Que en risa el llanto, el mal en
bien convierte Como amansa el rigor de la sentencia, Si el
condenado el rostro del rey mira , Y es ley que nunca tuerce su
derecho ; Asi ante lu hermosísima presencia La muerte huye, el
daño se retira, Y deja en su lugar vida y provecho. Al acabar Tirsi,
todos los instrumentos de los pastores formaron tan agradable
música , que causaba grande contento á quieu la oía, y mas
ayudándoles de entre las espesas ramas mil suertes de piulados
pajarillos, que con divina armonía parece que como á coros les iban
respondiendo. Desta suerte habian caminado un treclio, cuando
llegaron á una antigua ermita que en la ladera de un montecillo
estaba, no tan desviada del camino, que dejase de oírse el sonde
una arpa que dentro al parecer tañían, el cual oído porErastro, dijo
-.Deteneos, pastores, que según pienso, hoy oiremos todos lo que
lia días que yo deseo oír, quees la voz de un agraciado mozo que
dentro de aquella ermita habrá doce ó catorce días se ha venido á
vivir una vida mas áspera de lo que á mi me parece que puedan
llevar sus pocos años, y algunas veces que por aquí he pasado, he
sentido tocar un arpa y entonar una voz tan suave , que me ha
puesto en grandísimo deseo de escucharla; pero siempre he llegado
á punió que él le ponía en su canto; y aunque con hablarle be
procurado hacerme su amigo, ofreciéndole á su servicio todo lo que
valgo y puedo, nunca he podido acabar con él que me descubra
quién es, y las
The text on this page is estimated to be only 28.07%
accurate

LA CALATEA, UBRO U. 95 cansas que le han movido & venir


do tan pocos años A ponerse en tanta soledad y estreclicza. Lo que
Eiastro decia del mozo y nuevo ermitaño, puso en los pastores el
mismo deseo de conocerle que él tenia, y asi acordaron de llegarse á
la ermita de modo que sin ser sentidos pudiesen entender lo que
cantaba áiites que llegasen á liablarle ; y liaciéndulo asi , les sucedió
tan bien , que se pusieron en parte donde, sin ser vistos ni sentidos,
oyeron que al son de la arpa el que estaba dentro semejantes versos
decia. Si han sido el cielo, amor y la fortuna Sin ser de mí ofendidos,
Cunlenlos de ponerme en tal estado, Kn vano al aire envío mis
gemidos : Kn vano hasta la luna Se vio mi pensamiento levantado. ¡
Oh riguroso hado! ¡Por ouán extraíns desusadas vias Mis diilees
alegrías Han venido á parar en tal extremo Que estoy muriendo, y
aun la vida temo'. Contra mi mesmo estoy ardiendo en ira, Por ver
ijue sufro tanto Sin roni|>er e>te pecho, y d.ir al viento Ksta alma,
que en mitad del duro llanto Al corazón retira Las liliiiiias reliquias del
aliento ; Y alli de nuevo siento Que acude la esperanza á darme
fuerza, Y auni|ue Ungida á mi vivir es fuerza. Y no es piedad del
cielo, porque ordena A larga vida dar mas larjía pena. Del caro
amigo el lastimado pecho Enterneció este mió, Y la empresa ilificil
tomé ü cargo. ¡ Oh discreto Ungir de desvario ! Oh nunca visto
hecho! Olí caso gustosísimo y amargo! i Cuan dadivoso y largo Amor
se me mostró por bien ajeno, \ cuan avaro y lleno De temor y
lealtad para conmigo ! Pero á mas nos obliga un lirme amigo.
Injustas pagas, voluntades justas A cada paso vemos Dadas por
mano de fortuna esquiva , Y de ti, falso amor, de quien sabemos
Que le alegras y gustas De que un lirme amador muriendo viva ,
Abrasadora y viva Llama se encienda en tus lijcras alas, \ las buenas
y malas Saetas en cenizas se resuelvan , O al dispararlas contra ti se
vuelvan ¿Por qué camino, con qué fraude y mnüa , Por qué extraño
rodeo F-ntera posesión de mi tomaste? Y ¿cómo en mi piadoso alto
deseo, Y en mis limpias entrañas La sana voluntad, falso, trocaste?
¿Juicio habrá que baste A llevar en paciencia el ver, perjuro, Que
entré libre y seguro A tratar de tus sinrias y tus penas , Y agora al
cuello sienta tus cadenas? Mas no de ti, sino de mí seria Razón que
me quejase. Que á tu fuego no hice resistencia. Yo me entregué, yo
hice que soplase Kl viento que dormía De la ocasión con furia y
violencia : Justísima sentencia lia dado el cielo contra mi que muera,
Aunque solo se espera De mi infelice hado y desventura, Que no
acabe mi mal la sepultura. ¡Oh amigo dulce, nh dulce mi enemiga ,
Timbrio, y Nisida bella. Dichosos juntament(' y desdichados! ¿Cuál
dura , inicua , inexorable estrella De mi daño enemiga ; Cuál fuerza
injusta de implacables hados Nos tiene así apartados? ¡ Olí
miserable, humana , frágil suerte ! Cuan presto se convierte Kn
süi)ilo pesar una alegría, Y sigue escura noche al claro dia ! De la
ínslabili aprovecha. Yo como puedo, buen .Señor, levanto La una y
otra palma , Los ojos , la intención al cielo santo, Por quien espera el
alma Ver vuelto en risa su continuo llanto. Con un proluiulo suspiro
dio íiu al lastimado canto el recogido mozo, que dentro en la ermita
estaba ; y sintiendo los pastores que adelante no proseguía , sin
dele^ner.se mas, todos juntos entraron en ella , donde vieron á lili
cabo sentado encima de una dura piedra á im dispuesto y agraciado
mancebo, al parecer de edad de veinte y (lósanos, vestido de un
tosco buriel, con los pies descalzos y una íspera soga ceñida al
cuerpo, quo de cordón le servia. Estaba con la cabeza inclinada á un
lado, y la una mano asida de la parte de la túnica que solu-e el
corazón caia, y el otro brazo ¡i la otra parte llojameutc derribado; y
por verle desia manera, y por no liaber hecho movimiento al entrar
de los pastores, clarameule conocieron que desmayado estaba,
como era la verdad, porque la prorniiiia imaginación de sus miserias
muchas veces á semejante término le conduela. Llegóse á él Erastio,
y trabándole recio del brí:zo, le hizo volver en sí, aunque tan
desacoidado, que parecía que de un pesado sueño recordaba , las
cuales muestras de dolor, no pequeño le cansaron á los que lo veían,
y luego Erastro le dijo : ¿Qué es esto, señor, qué es lo que siente
vuestro fatigado pecho? No dejéis de decirlo, que presentes tenéis
quien no rehusarán fatiga algnun por dar remedio á la vuestra. No
son esos, respondió el mancebo con voz algo desmayada, los
primeros ofrecimientos que me has hecho, ni aun serían los últimos
que vo acertase á servir si pudiese; pero líame traído la fortuna á
términos, que ni ellos pueden aprovecharme, ni vo satisfacerlos mas
de con el deseo. Este [uiedes tomar en cuenta del bueno que me
ofreces; y sí otra cosa de mí deseas saber, el tiempo, que no encidjre
nada, le dirá mas de lo que yo quisiera. Si al tiempo dejas que me
.satisfaga de lo que me dices, respondió Erastro, poco debe
agradecerse tal paga; pues él á pesar nuestro echa en las plazas lo
mas secreto de nuestros corazones. A este tiempo todos los demás
pastores le rogaron que la ocasión de su tristeza les contase,
especialmente Tirsi, que con eficaces razones le persuadió y dio á
entender que no hay mal en esta vida que con ella su remedio no se
alcanza.se, si ya la miierle, atajadora de los humanos discursos , no
se opone á ellos ; y á esto añadió otras palabras, que al obstinado
mozo movieron á que con las suyas hiciese satisfechos á todos de lo
que del saber deseaban , y así les dijo : Puesto que á mí me fuera
mejor, ó agradable compañía, vivir lo poco que me queda de vida sin
ella , y haberme recogido á mayor soledad de la que tengo, todavía
por no mostrarme esquivo á la voluntad (itic me habéis mostrado,
determino de ( ontaros todo aquello que enliondo bastará, y los
términos por donde la mudable fortuna me ha traido al estrecho
estado en que me hallo ; pero porque me parece que es ya algo
tanle, y según mis desventuras son muchas, .sería posible que antes
de contároslas la noche sobreviniese, será bien que todos juntos á la
aldea nos vamos, pues á
26 OBRAS ÜE mi no mo liace otra descomoJidad de hacer
el camino esta noclie, que mañana tenia determinado, y esto me es
forzoso, pnesde vuestra aldea soy proveído de lo qne he menester
para mi sustento; y pur el camino, como mejor pudiéremos, os haré
ciertos de mis desgracias. A todos pareció bien lo que el mozo
ermitaño decia, y poniéndole en medio dellos , con vagarosos pasos
tornaron á seguir el camino de la aldea, y luego el alligido ermitaño
con muestras de mucho dolor desta manera al cuento de sus
miserias dio principio. En la antigua y fauíosa ciudad de Jerez, cuyos
moradores de Minerva y Marte son favorecidos, nació Timbrio, uu
valeroso caballero, del cual, si sus virtudes y generosidad de ánimo
hubiese de contar, á difícil empresa me pondría. Basta saber que, no
sé si por la muciiu bondad suya, ó por la fuerza de las estrellas que
á ello me inclinaban, yo procuré por todas las vias que pude serle
particular amigo, y fuéme en esto el cielo tan favorable, que casi
olvidándose á los que nos conociau el nombre deTiinI)rio y el
deSilerio, queesel mió, solamente los dos amigos nos llamaban,
haciendo nosotros con nuestra continua conversación y amigables
obras que tal opinión no fuese vana. Desta suerte los dos con
increíble gusto y contento los mozos años pasábamos, ora en el
campo en el ejercicio de la caza, ora en la ciudad en el del honroso
Marte entreteniéndonos, liasta que un dia (de los muchos aciagos
que el enemigo tiempo en el discurso de mi vida me ha hecho ver)
le sucedió á mi amigo Timbrio una pesada pendencia con un
poderoso caballero , vecino de la misma ciudad. Llegó á término la
cuestión, que el caballero quedó lastimado en la honra, yáTindjrio le
fué forzoso ausentarse, por dar lugar á que la furiosa discordia
cesase, que entre las dos parentelas se comenzaba á encender;
dejando escrita una carta á su enemigo dándole aviso que le hallaría
en Italia en la ciudad de Milano en JNápoles, todas las veces que,
como caballero, de su agravio satisfacerse quisiese. Con esto
cesaron los bandos entre los parientes de entrambos, y ordenóse
que á igual y mortal batalla el ofendido caballero, que Pransilesse
llamaba , áTimbrio desafiase, y que en hallando campo seguro para
la batalla se avisase áTimbrio. Ordenó mas mi desgraciada suerte,
que al tiempo que esto sucedió yo me hallase tan falto de salud, que
apenas del lecho levantarme podía, y por esta ocasión se me pasó la
de seguir á mi amigo donde quiera que fuese, el cual al partir se
despidió de mí con no pequeño descontento, encargándome que en
cobrando fuerzas le buscase, que en la ciudad de Ñapóles le haliaria,
dejándome con mas pena que yo sabré agora significaros. Mas al
cabo de pocos días (pudiendoenmí mas el deseo que de verle tenía,
que ñola flaqueza que me fatigaba) me puse luego en camino; y
para que con mas brevedad y mas seguro le hiciese, la ventura me
ofreció la comodidad de cuatro galeras, que en la f.unosa isla de
Cádiz de partida para Italia puestas y aparejadas estaban.
Embarquéme en una de ellas, y con próspero viento en tiem|)o
breve las riberas catalanas descubrimos; y liabieudo dado fondo en
un puerto dellas, yo que algo fatigado de la mar venia, asegurado
primero de que por aquella noche las galeras de allí no I>artían, me
desembarqué con solo un amigo y un criado mío : y no creo que
debía de sor la media noche cuando los marineros y los que á caigo
las galeras llevaban. CERVANTES. viendo que la serenidad del cielo
calma ó próspero viento señalaba , por no perder la buena ocasión
que se les ofrecía, á la segunda guardia liicieron la señal de partida;
y zarpando las áncoras, dieron con mucha presteza los remos al
sesgado mar, y las velas al sosegado viento, y fué como digo con
tanta diligencia hecho, que por nmcha que yo puse para volver á
endtarcanne, no fui á tiem|)0, y así me hube de quedaren la marina
con el enojo que podrá considerar quien por semejantes y ordinarios
casos habrá pasado; ponjue quedaba mal acomodado de todas las
cosas que para seguir mi viaje por tierra eran necesarias ; mas
considerando que de quedarme allí poco remedio se esperaba,
acordé de volverme á Barcelona, adonde como ciudad mas grande
podría ser hallar quien me acomodase de lo que me faltaba,
correspondiendo a Jerez ó á Sevilla con la paga dello. Amanecióme
en estos pensamientos, y con determinación de ponerlos en efeto
aguardaba á que el día mas se levantase, y estando á punto de
partirme, senti un grande estruendo por la tierra, y que toda la
gente corría ala calle mas principal del pueblo; y preguntando á uno
qué era aquello, me respondió ; Llegaos, señor, á aquella esquina,
que á voz de pregonero sabréis lo que deseáis. Híccioasí, y lo
primero en que puse los ojos fué en un alto crucifijo, y en mucho
tumulto de genle, señales que algún sentenciado á nmerte entre
ellos venía , todo lo que me certificó la voz del pregonero , que
declaraba que por haber sido salteador y bandolero, la justicia
mandaba ahorcar un hombre, que como á mi llegó, luegoconocí que
era el mi buenamigoTímbrio, el cual venia á pié con unas esposas á
las manos y una soga á la garganta, los ojos enclavados en el
crucíííjo que delante llevaba, diciendo y protestando á los clérigos
que con él iban , que por la cuenta que pensaba dar en breves horas
al verdadero Dios, cuyo retrato delante de los ojos tenia, que nunca,
en todo el discurso de su vida, habia cometido cosa por donde
públicamente mereciese recebir tan ignominiosa muerte, y que á
todos rogaba, rogasen á los jueces le diesen algún término para
probar cuan inocente estaba de lo que le acusaban. Considérese
aquí, si tanto la consideración pudo levantarse, cuál quedaría yo al
horrendo espectáculo que á los ojos se me ofrecía: no sé qué os
diga, señores, sino que quedé tan, embelesado y fuera de mí , y de
tal modo quedé ajeno de todos mis sentidos, que una estatua de
marmol debiera de parecer á quien en aquel punto me miraba. Pero
ya que el confuso rumor del pueblo, las levantadas vocesde los
pregoneros, las lastimosas palabras deTiinbrio, y las consoladoras de
los sacerdotes, y el verdadero conocimiento de mí buen amigo me
hubieron vuelto de aquel embelesamiento primero, y la alterada
sangre acudió á dar ayuda al desmayado curaztuí, y despertando en
él la cólera debida á la notoria venganza de la ofensa de Timbrio, sin
mirar al peligro que me. ponía, sino al de Timbrio, por ver si podía
librarle ó .seguirle hasta la otra vida, con poco temor de perder la
mía, eché mano á la espada, y con mas que ordinaria furia entré por
medio de la confusa turba, basta que llegué adonde Tind)rio iba, el
cual no sabiendo si cu provecho suyo tantas espadas se habían
desenvainado, con perplejo y angustiado ánimo estaba mirando lo
que pasaba, hasta que yo le dije : ¿Adonde eslá, ó Timbrio, el
esfuerzo de tu valeroso pecho? ¿Qué esperas ó
LA CALATEA qué aguardas? ¿Por qwé no te favoreces de la
ocasión presente? Procura, venladero amigo, salvar tu vida, en tanto
que esta niia hace escudo á la sinrazón que, según creo, aquí te es
lieclia. Estas palabras niias y e! conocerme Tinibrio, fué parte para
que, olvidatlo todo temor, rompiese las ataduras ó esposas de las
manos ; mas lodo su ardimiento fuera \)le , que de todos llevaban el
saco
The text on this page is estimated to be only 28.73%
accurate

28 OBRAS DE aquellos descreídos perros ; los cuales,


después de abrasadas las casas, robados los templos, desllorado las
vir{íenes, miierlo los defensores, mas cansados que satisfechos délo
lieclio, al tiempo qne el alba venía, sin impedimento alguno se
volvieron á sus bajeles, liabiéndolos ya cargado de lodo lo mejor qne
en el pueblo liabia, dejándole desolailo y sin gente, porque toda la
mas gente se llevaban, y la olraá la montaña se iiabia recogido.
¿Quién en tan triste especlácnlo pudiera tener quedas las manos y
enjutos los ojos? Mas ¡ay! que está tan \W.iu de miserias nuestra
vida, que tan doloroso suceso como el que os be contado, hubo
cristianos corazones que se alegraron; y estos fueron los de a(|nellos
qne en la cárcel estaban, que con la desdicha general cobráronla
dicha propia, porque en son de ir á defender el pueblo, rompieron
las puertas de la prisión y en libertad se pusieron, piocurando cada
uno no de ofenderá los contrarios, sino de salvará si niesmos; entre
los cuales yo gocé de la libertad tan caramente adquirida. Y viendo
que no bahia quien hiciese rostro á los enemigos, por no venir á su
poder ni tornar al de la prisión, desamparando el consumido pueblo,
con no muy pequeño doler de loque habia visto, y con el que mis
heridas me causaban, seguí á un hombre que me dijo, qne
seguramente me llevaría á un monasterio que en aquellas montañas
csUdxa, donde de mis llagas sería curado, y aun defendido, sí de
nuevo prenderme quisiesen : seguíle en íín, comoos he dicho, con
deseo de saber qué habría hecho la fortuna de mi amigo Timbrio, el
cual, como después supe , con algunas heridas se había escapado y
seguido por lu montaña otro camino diferente del que yo llevaba :
vino á parar al puerto de Rosas, donde estuvo algunos días,
procuiando saber qué suceso habría sido el mío; y qne en íin, sin
saber nuevas algunas se partí(» cu una nave, y con próspero viento
llegó á la gran ciudad de Ñapóles. Yo volví á Barcelona, y allí me
acomodé de lo qne menester había, y después ya sano de mis
heridas, tornea seguir mi viaje, y sin succderme revés alguno llegué
á Ñapóles, donde hallé enfermo á Timbrio ; y fué tal el contento que
en vernos losdos recebimos, que no me siento con fuerzas para
encarecérosle por agora. Allí nos dimos cuenta de nuestras vidas, y
de todo aquello que hasta aquel momento nos había sucedido; per»,
todo este placer mío seaguaba con ver á Timbrio no tan bueno como
yo quisiera, antes tan malo y de una enfermedad tan extraña, que si
yo á aquella sazón no llegara, pudiera llegar á tiempo de hacerle las
obsequias de su nnierte, y no solenizar las alegrías de su vista.
Después que él hubo sabido de mí ti do lo que quiso, con lágrimas
en los ojos me dijo : jAy, amigo Silerio! ; y cómo creo que el cielo
procura cargarla mano en mis desventinas, para que dándome la
salud por la vuestra, quede yo cada día con mas obligación de
serviros! Palabras fueron estas de Timbrio que me enternecieron ;
mas por parecerme de comedimientos tan poco usados entre
nosotros, me admiraron. Y por no cansaros en deciros punto por
punto lo que yo le respondí y lo que él mas replicó, solo os diré, que
el desdichado deTímbrio estaba enamorado de una señora principal
de aquella ciudad , cuyos padres eran españoles, aunque ella en
Ñapóles había nacido : su nombre era Nísida, y su hermosura lauta,
que me atrevo á decir que la naturaleza cifró en ella el extremo
desús perCERVANTES. I fecciones; y andaban tan auna en ella la
honestidad y belleza , que lo que la una encendía , la otra enfriaba ,
y los deseos que su gentileza basta el mas subido cielo Icj Yantaba,
su honesta gravedad hasta lomas bajo de la I tierra abatía. A esta
causa estaba Timbrio tan pobre de esperanza, cuan rico de
pensamientos, y sobre todo falto de salud , y en términos de acabar
la vida sin des¡ cubrirlos : tal era el temor y reverencia que iiabia
cobrado á la hermosa Nísida. Pero después (|ue tuve bien conocida
su enfermedad, y hube visto á Ni,>ída, y considerado la calidad y
nobleza de sus padres, determiné de posponer por él la hacienda, la
vida y la honra, y mas si mas tuviera y pudiera, y así usé de un
artíücio el mas extraño que hasta hoy se habrá oído ni leído; y fué
que acordé de vestirme como truhán, y con una guitarra entrarme
en casa de Nísida , que por ser, como ya he dicho , sus padres de
loa principales de la ciudad, de otros muchos truhanes era
continuada. Parecióle bien este acuerdo á Timbrio, y resignó luego
en las manos de mi industria todo su contento. Hice yo hacer luego
muchas y diferentes galas, y en vistiéndome comencé á ensayarme
en el nuevo olício delante de Timbrio, que no poco reía de verme tan
truhanamente vestido; y por ver si la habilidad correspondía al
hábito, me dijo que haciendo cuenta que él era un gran príncipe y
que yo de nuevo venia á visitarle, le dijese algo. Y si yo no me
acuerdo mal, y si vosotros, señores, no os cansáis de escucharme,
diréos lo que entonces le canté, con .ser la primera vez. Todos
dijeron que ninguna cosa les daría mas contento, que saber por
extenso todo el suceso de su negocio, y que así le rogaban que
ninguna cosa, por de poro momento que fuese, dejase decentarles.
Pues esa licencia me dais, dijo el crnñlaño, no quiero dejaros de
decir cómo comencé á dar muestras de mi locura, qne fué con estos
versos que á Timbrio canté, imaginando ser un gran señora quien
los decía. De principe que en el suelo Va por tan justo nivel , ¿ Qué
se ¡¡urde e^penir d(H, Que no sean ot/rua ílc¡ ciclo ? No se ve en la
edad presente Ni se vio en la cdud pasada República gobernada He
princii)e t,in prudente : Y del ([ue niule su celo Por tan cristiano nivel
, / Qiíc xe puede esperar del Que no sean obras del rielo .* [)el que
trae por bien ajeno, Sin codiciar mas despojo, Misericorilia en los
ojos, Y la justicia en el seno : Del ([ue lo mas deste suelo i;s lo
menos que hay en él , ¿ Qué se puede esperar del Que no sean
obras del cielo ? I,D liberal fama vuestra. Que ¡lasia el cielo se
levanta, De que leñéis alma santa Nos da indicio velara inui.'stra Del
(|ue no discrepa un pelo De ser al cielo i íel , / Qué se puede esperar
del Que nu sean obras del cielo? Del (jue con cristiano pecliú
Sieniiire en el ligor se l.ir.la , Y a la justicia le guarda Con clemencia
su di'reclio; De aquel que levanta el vuelo Do ninguno llega á él, ¿
Qué se puede esperar del Que no sean obras dcícielol Estas y otras
cosas de mas risa y juego canié entói.ccs á Timbrio, procurando
acomodar el biío y donaire del cuerpo á que en todo diese muestras
de ejercitado truhán ; y salí tan bien con ello, que en pocos días fui
conocido de toda la mas gente principal de la ciudad , y la fama del
truhán español por toda ella volaba : basta tanto que ya en casa del
padre de Nísida me deseaban ver, ei cual deseo les cumpliera yo con
mucha facilidad , si de industria no aguardara á ser rogado. .Mas en
lín , no me pude excusar que un dia de un banquete allá no fuese.
LA CALATEA donde vi mas cerca la justa causa que Timbrio
tenia de padecer , y la que el cielo me dio para quitarme el contento
lodos los días que en esta vida durare. ViáNísida, á ¡Nísida vi para no
ver nías, ni hay mas que ver después de haberla visto. ¡ Oh fuerza
poderosa de amor, contra quien valen poco las poderosas nuestras!
Y ¿es posible que en un punto, en un momento los reparos y
pertrechos de mi lealtad pusieses en términos de dar con todos ellos
por tierra? ¡ Ay , que si se tardara un poco en socorrerme la
consideración de quien yo era, la amistad que á Timbrio debia, el
mucho valor de Nísida, y el afrentoso hábito en que me hallaba, que
todo era impedimento á que con el nuevo y amoroso deseo que en
mí iiabia nacido, no naciese también la esperanza de alcanzarla, que
es el arrimo con que el amor camina ó vuelve atrás en los
enamorados principios! En fin, vi la belleza que os he dicho, y
porque me importaba tanto el verla, siempre procuré granjear el
amistad de sus padres y de todos los de su casa; y esto con hacer
del gracioso y bien criado, haciendo mi oficio con la mayor discreción
y gracia á mí posible. Y rogándome un caballero que aquel día á la
mesa estaba, que alguna cosa en loor de la hermosura de Nísida
cantase, quiso la ventura que me acordase de unos versos que
muchos dias antes para otra ocasión casi semejante yo habia hecho
, y sirviéndome para la presente , los dije , que eran estos. SILERIO.
Nisila, con quien el cielo Tan liberal se lia uioslrailo, Que en daros a
vos diii al suelo Una imagen y traslado De cuanto encubre su velo :
Si él no tuvo mas que os dar, Ni vos mas que desear, Con facilidad se
entiende Que lo imposible pretende Quien os pretende loar. De esa
beldad peregrina La perfección soberana Que al cielo nos encamina ,
I'ues no es posible la humana , Cante la lengua divina, Y diga , bien
se conviene. Que al alma que en si contiene Sor tan alto y
milagroso. Se le diese el velo hermoso Mas que el mundo tuvo ó
tiene. Tomó del sol los cabellos. Del sesgo cielo la frente, La luz de
los ojos bellos De ia estrella mas luciente. Que ya no da luz ante
ellos : Como quien puede y se atreve A la grana y á la nieve Robó
las colores bellas , Que lo mas perfeto dellas A sus mejillas se debe.
De marlil y de coral Formó los dientes y labios. Do sale rico caudal
De agudos dichos y sabios, Y armonía celestial : De duro mármol ha
hecho Kl blanco y hermoso pecho , Y de tal obra ha quedado Tanto
el suelo mejorado. Cuanto el cielo satisfecho. Con estas y otras
cosas que entonces canté, quedaron todos tan mis aficionados ,
especialmente los padres de Nísida, que me ofrecieron todo lo que
menester hubiese, y me rogaron que ningiin día dejase de visitarlos
• y así sin descubrirse ni imaginarse mi industria, vineá salir con mi
primer designio, que era facilitar la entrada en casa de Nísida, la cual
gustaba en extremo de mis desenvolturas. Pero ya que los muchos
dias, y la mucha conversación mia , y la grande amistad que todos
los de aquella casa me mostraban , hubieron quitado algunas
sombras al demasiado temor que de descubrir mi intento á Nísida
tenia, determiné ver á do llegaba la ventura de Timbrio , que solo de
mi solicitud la esperaba. Mas ¡ ay de mí! que yo estaba entonces
mas para pedir medicina para mi llaga, que salud para la ajena;
porque el donaire, belleza , discreción y gravedad de Nísida habían
hecho en mi alma tal efeto , que no estaba en menos extremo de
doloryde amor puesta, que la del lastimado Timbrio. A vuestra
consideración discreta dejo el imaginar lo que podia sentir un
corazón á quien de una parte combatían las Teyes de la amistad, y
de otra las inviolables de Cupido ; porque si las unas le obligaban á
no salir de lo quo LIBRO n. M ellas y la razón le pedían , las otras le
forzaban que tuviese cuenta con lo que á su contento era obligado.
Estos sobresaltosy combales me apretaban de manera, que sin
procurar la salud ajena , comencé á dudar de la propia , y á poiiernie
tan flaco y amaiillo, que catisaba general compasión á todos los que
me miraban , y los que mas la mosti aban eran los padres de Nísida
; y atuí ella mesma con limpias y cristianas entrai~ias me rogó
muchas veces que la causa de mi enfermedad le dijese,
ofreciéndome todo lo necesario para el remedio della. i Ay (decía yo
entre mí cuando Nísida tales ofrecimientos me hacia), ay, con cuánta
facilidad, hermosa Nísida, podría remediar vuestra mano el mal que
vuestra hermosura ha hecho! Pero precióme tanto de buen amigo,
que aunque tuviese tan cierto mi remedio como le tengo poi
imposible é incierto, imposible seria que le acetase. Y como estas
consideraciones en aquellos instantes me turbasen la fantasía , no
acertaba á responder á Nísida cosa alguna, de lo eual ella y otra
hermana suya, que Blanca se llamaba (de menos años, aunque no
de menos discreción y hermosura que Nísida), estaban maravilladas
; y con mas deseo de saber el origen de mi tristeza, con muchas
importunaciones me rogaban qii.e nada de mi dolor les encubriese.
Viendo pues yo que la ventiu'a me ofrecía la cotnodidad de poner en
efeto lo que hasta aquel punto mi industria había fabricado , una vez
que acaso la bella Nísida y su hermana á solas se hallaban, tornando
ellas de nuevo á pedirme lo que lanías veces, les dije : No penséis,
sei"ioras, que el silencio que hasta agora he tenido en no deciros la
causa de la pena que imagináis que siento, lo haya causado tener yo
poco deseo de obedeceros, pues ya se sabe que si algún bien mi
abatido estado en esta vida tiene, es haber granjeado con él venir á
términos de conoceros, y como criado sei viros : solo ha sido la
causa imaginar que aunque la descubra, no servirá para mas de
daros lástima, viendo cuan lejos está el remedio della ; pero ya que
me es forzoso satisfaceros en esto , sabréis , señoras , que en esln
ciudad está un caballero natural de mi mesma patria, á quien tengo
por señor, por amparo y por amigo , el mas liberal , discreto y gentil
hombre que en gran parte hallarse pueda , el cual eslá aquí ausente
de la amada patria por ciertas cuestiones que allá le sucedieron, que
le forzaron á venir á esta ciudad, creyendo que si allá en la suya
dejaba enemigos, acá en la ajena no le faltaran amigos; mas hale
salido tan al revés su pcnsaniiciito, qneá un solo enemigo que él
mismo sin saber cóuio aquí se ha procurado , le tiene puesto en tal
extremo , que si el cielo no le socorre, con acabar la vida acabará
sus nmistades y enemistades; y como yo conozco el valor de Timbrio
(que este es el nombre del caballero cuya desgracia os voy contando
, y sé lo que perderé si le pierdo), doy las muestras de sentimiento
(pie habéis visto, y aun son pocas según á lo que me obliga el
peligro en que Timbrio está puesto. Bien sé que descaréis saber ,
señoras, quién es el enemigo que á tan valeroso caballero, como es
el que os he pintado, tiene puesto en tal exlremo; pero también sé
que cu diciéndoosle , no os maraviraréis sino de cómo no le tiene ya
consumido y mueilo : su enemigo es amor, universal destruidor de
nue.>-lru5 sosiegos y bienandanzas : este (ieio enemigo t uñó poseí
sion de sus entrañas. En entiaudo cu osla ciudad vio Timbiio una
hermosa dama de singular valor y hermo 
30 OBRAS DE sijia ; mas tan principal y lioncsta , que
jan)as el miserable se ha avenliuado á descubrirle su pensamiento. A
este punto llegaba yo, cuando Mísida me dijo : Por cierto, Astor, que
entonces era esle el nombre mió, que no s6 yo si crea que ese
caballero sea tan valeroso y discreto con)n dices, pues tan
rácilmenle se ha dejado rendir á un mal deseo tan recien nacido,
entregándose tan sin ocasión alguna en los brazos de la
desesperación ; y aimque {\ mí se me alcanza poco destos amorosos
efelos, todavía me parece que es simplicidad y flaqueza dejar, el que
se ve fatigado dellos, de descubrir su ¡leusamienlo á quien se le
causa, puesto que sea del valor que imaginarse puede; porque ¿qué
afrenta se le puede seguirá ella de saber que es bien querida, ó á él
qué mayor mal de su aceda y desabrida respuesta, que la muerte
que él mismo se procura callando? Y no sería bien que por tener im
juez fama de riguroso, dejase alguno de alegar de su derecho ; pero
pongamos que sucede la nmerte de im amante tan callado y
temeroso como ese tu amigo, dime : ¿llamarías tú cruel á la dama
de quien estaba enamorado? No por cierto ; que mal [luede
remediar nadie la necesidad que no llega á su noticia, ni cae en su
obligación procurar saberla para remediarla. Así que, Astor,
perdóname, que las obras dése tu amigo no hacen nnay verdaderas
las alabanzas que le das. Cuando yo oí á iNisida semejantes razones,
luego quisiera con las mias descubrirle todo el secreto de mi pecho ;
mas como yo entendía la bondad y llaneza con que ella las hablaba,
hube de detenerme, y esperar mas sola y mejor coyuntura , y así le
respondí : Cuando los casos de amor, hermosa Nísida , con libres
ojos se miran , tantos desatinos se ven en ellos, que no menos de
risa que de compasión son dignos ; pero si de la sutil red amorosa
se halla enlazada el alma, allí están los sentidos tan trabados y tan
fuera de su propio ser, que la memoria solo sirve de tesorera y
guardadora del objeto que los ojos miraron ; y el entendimiento de
escudriñar y conocer el valor de la que bien ama; y la voluntad de
consentir de que la memoria y entendimiento en otra cosa no se
ocupen ; y así los ojos ven como espejo de alinde, que todas las
cosas se les hacen mayores : era crece la esperanza cuando son
favorecidos, ora el temor cuando desechados : y así sucede á
muchos lo que álimbrio ha sucedido, que pareciéndoles á los
principios altísimo el objeto á quien los ojos levantaron, pierden la
esperanza de alcanzarle; pero no de manera que no les diga amor
allá dentro en el alma : ¿quién sabe? ¿podría ser? y con esto anda la
esperanza, como decirse suele, entre dos aguas , la cual si del todo
les desamparase, con ella huiría el amor. Y de aquí nace andar entre
el temer y osar el corazón del amante afligido, que sin aventurarse á
decirla, se recoge y aprieta en .^u llaga, y espera, aunque no sabe
de quién, el remedio de que se ve tan apartado. En este mismo
extremo he yo hallado á Timbrio, aunque todavía á persuasiones
mías ha escrito una carta á la dama por quien muere , la cual me dio
para que la viese y mirase si en alguna manera se mostraba en ella
descomedido, porque la enmendaría : encargóme asimismo que
buscase orden de ponerla en manos de su señora, que creo será
imposible, no porque yo no me aventuraré á ello, pues lo menos que
aventuraré será la vida por servirle; mas porque me parece que no
he de hallar ocasión para darla. Yeámosla, dijo Nísida, porque deseo
ver cómo escriben CERVANTES. I los enamorados discretos. Luego
saqué yo una carta del seno , que algunos días antes estaba escrita ,
esperando ocasión de que Nísida la viese , y ofreciéndome la ventura
esta, se la mostré; la cual por haberla yo leído muchas veces se me
quedó en la memoria , cuyas razones eran estas. TIMBRlO Á >ÍSinA.
«Determinado había, hermosa señdra , que el fin desastiadd mío os
diese nolícia de quién yo era , pareciéndome ser mejor que
alabárodes mi silencio en la muerte, que no que vitnperárades mi
atrevimiento en la vida; mas porque imagino que á mí alma
conviene partirse deste mundo en gracia vuestra, porque en el otro
no le niegue amor el premio de lo que ha padecido, os hago
sabidora del estado en que vuestra rara beldad me tiene puesto, que
es tal que á poder significarle, no procurara su remedio , pues por
pequeñas cosas nadie se ha de aventurar á ofender el valor
extren)ado vuestro, del cual y de vuestra honesta liberalidad espero
restaurar la vida para serviros, ó alcanzar la nmerte para nunca mas
ofenderos. » Con mucha atención estuvo Nísida escuchando esta
carta, y en acabándula de oír, dijo : no tiene de qué agraviarse la
dama á quien esta carta se envía , si ya de puro grave no da en ser
melindrosa , enfermedad de quien no se escapa la mayor parte de
las damas de esla ciudad ; pero con todo eso no dejes , Astor , de
dársela, pues como ya te he dicho no se puede esperar mas mal de
su respuesta , que no sea peor el que agora dices que tu amigo
padece; y para mas animarte te quiero asegurar, que no hay mujer
tan recatada y tan puesta en atalaya para mirar por su honra, que le
pese mucho de ver y saber que es querida; porque entonces conoce
ella que no es vana la presunción que de sí tiene, lo cual sería al
revés, si viese que de nadie era solicitada. Bien sé, señora, que es
verdad lo que dices, respondí yo; mas tengo temor que el atreverme
á darla , por lo menos me ha de costar negarme de allí adelante la
entrada en aquella casa, de que no menor daño me vendría á mí
que á Timbrio. No quieras, Astor, replicó Nísida, confirmarla
sentencia que aun el juez no tiene dada : muestra buen ánimo, que
no es riguroso trance de batalla este á que te aventuras. Pluguiera al
cielo, hermosa Nísida, respondí yo, que en ese término me viera ,
que de mejor gana ofreciera el pecho al peligro y rigor de mil
contrapuestas armas, que no la mano á dar esta amorosa carta á
quien temo que siendo con ella ofendida , ha de arrojar sjbre mis
hond)ros la pi'ua que la ajena culpa merece; pero con todos estos
inconvenientes pienso seguir, señora, el consejo que me has dado;
puesto que aguardaré tieiupo en (pie el temor no tenga tan
ocupados mis sentidos como agora : y en este entre tantu te suplico
que haciendo cuenta que tú eresá quien esla carta se envía, me des
alguna respuesta que lleve á Timbrio, para que con este engaño, él
se entretenga un poco, y á miel tiempo y las ocasiones me
descubran lo que tengo de hacer. De mal artificio quieres usar,
respondió Nísida, porque puesto caso que yo agora diese en nombre
ajene alguna blanda ó esquiva respuesta, ¿no ves que el tiempo ,
descubridor de nuestros fines , aclarará el engaño, y Timbrio
quedará de tí mas quejoso que satisfecho ? Cuanto mas, que por no
haber dado hasta agora res 
The text on this page is estimated to be only 28.28%
accurate

La galatea puesta á semejantes cartas, no quon ia


comenzar á dar- ¡ las mentirosa y tingidamente ; mas aunque sepa
ir con- | tra lo que á mí mosnia debo, si me prometes de decir quién
es la dama, yo te diré qué digas á tu amigo, y cosa tal que él quede
contento por ahora ; y puesto que después las cosas sucedan al
revés de lo que él pensare , no por eso se averiguará la mentira. Kso
no me lo mandes, óNísida, respondí yo, por(]ne en tanta cont'usion
me pone el decirte yo á tí su nombre , como me pondría el darle á
ella la carta : basta saber que es principal, y que, sin liacerte agravio
alguno , no te debe nada en la liermosura, que con esto me parece
que la encarezco sobre cuantas son nacidas. No me maravillo que
digas eso de mi, dijo Nísída, pues los hombres de vuestra condición
y trato , lisonjear es su propio oficio ; mas dejando todo esto á una
parte, porque deseo que no pierdas la comodidad de un tan buen
amigo , te aconsejo que le digas (jue fuiste á dar la carta á su dama,
y que has pasado con ella todas las razones que conmigo siu faltar
punto, y cómo leyó tu carta , y el ánimo que te daba para que á su
dama la llevases, pensando que no era ella á quien venia, y que
aunque no te atreviste á declarar del todo, que has conocido della,
que cuando sepa ser ella para (¡uíen la carta venía, no le causará el
engaño y desengaño mucha pesadumbre. Desta suerte recibirá él
algún alivio en su trabajo, y después al descubrir tu intención á su
dama, puedes responderá Timbrio lo que ella te respondiere ; pues
basta el punto que ella lo .sepa queda en fuerza esta mentira, y la
verdad de lo que sucediere, sin que haga al caso el engaño de
agora. Admirado quedé de la discreta traza de Nísida, y aun no sin
sospecha de la verdad de mi artificio : y así besándole las manos por
el buen aviso , y quedando con ella que de cualquiera cosa que en
este negocio sucediere, habia de dar particular cuenta , vine á
contar á Timbrio todo lo que con Nísida me habia sucedido, que fué
parte para que la tuviese en su alma la esperanza , y volviese de
nuevo á sustentarle , y desterrar de su corazón los nublados del frió
temor que hasta entonces le tenían ofuscado; y todo este gusto se
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like