SlideShare a Scribd company logo
Introduction To Objectoriented Programming An
3rd Edition Timothy Budd download
https://ebookbell.com/product/introduction-to-objectoriented-
programming-an-3rd-edition-timothy-budd-33057832
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Introduction To Objectoriented Programming In Python Building Flexible
And Reusable Code 2nd Edition 2nd Edition Amir Keivan Shafiei
https://ebookbell.com/product/introduction-to-objectoriented-
programming-in-python-building-flexible-and-reusable-code-2nd-
edition-2nd-edition-amir-keivan-shafiei-57761774
An Introduction To Objectoriented Programming With Visual Basic Net
1st Edition Dan Clark
https://ebookbell.com/product/an-introduction-to-objectoriented-
programming-with-visual-basic-net-1st-edition-dan-clark-55132358
An Introduction To Objectoriented Programming With Java 5th Edition C
Thomas Wu
https://ebookbell.com/product/an-introduction-to-objectoriented-
programming-with-java-5th-edition-c-thomas-wu-2377364
An Introduction To Objectoriented Programming In C With Applications
In Computer Graphics 2nd Edition Graham M Seed Beng
https://ebookbell.com/product/an-introduction-to-objectoriented-
programming-in-c-with-applications-in-computer-graphics-2nd-edition-
graham-m-seed-beng-4198618
Microsoft Visual C 2010 An Introduction To Objectoriented Programming
4th Edition 4th Joyce Farrell
https://ebookbell.com/product/microsoft-visual-c-2010-an-introduction-
to-objectoriented-programming-4th-edition-4th-joyce-farrell-2338860
Beginning C 30 An Introduction To Object Oriented Programming 1st
Edition Jack Purdum
https://ebookbell.com/product/beginning-c-30-an-introduction-to-
object-oriented-programming-1st-edition-jack-purdum-2514132
Microsoft Visual C 2017 An Introduction To Objectoriented Programming
7th Edition Joyce Farrell
https://ebookbell.com/product/microsoft-visual-c-2017-an-introduction-
to-objectoriented-programming-7th-edition-joyce-farrell-10539110
Applying Uml And Patterns An Introduction To Object Oriented
Programming 2ed Larmen
https://ebookbell.com/product/applying-uml-and-patterns-an-
introduction-to-object-oriented-programming-2ed-larmen-1278786
Introduction To Programming With Greenfoot Objectoriented Programming
In Java With Games And Simulations Klling
https://ebookbell.com/product/introduction-to-programming-with-
greenfoot-objectoriented-programming-in-java-with-games-and-
simulations-klling-21995800
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
TRENT UNIVERSITY
ALUMNI BOOK FUND
This book is a gift of
THE ALUMNI BOOK FUND
as part of the Book Fund
of the Trent University
Alumni Association
Presented on
October 20
to The Thomas J. Bata Library
Trent University,
Peterborough, Canada.
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
Third Edition
An Introduction to
Object-Oriented
Programming
Digitized by the Internet Archive
in 2019 with funding from
Kahle/Austin Foundation
https://archive.0rg/details/introductiontoobOOOObudd
Third Edition
An Introduction to
Object-Oriented
Programming
'(( ^
Timothy A. Budd-
Oregon State University
Thomas J. Bata Library
TRENT UNIVERSi i Y
PETERBOROUGH, ONTARIO
Boston San Francisco New York
London Toronto Sydney Tokyo Singapore Madrid
Mexico City Munich Paris Cape Town Hong Kong Montreal
Executive Editor: Susan Hartman Sullivan
Associate Editor: Elinor Actipis
Executive Marketing Manager: Michael Hirsch
Production Supervisor: Diane Freed
Composition: Windfall Software, using ZzTgX
Copyeditor: Debbie Prato
Technical Art: LM Graphics
Proofreader: Brooke Albright
Text Design: Windfall Software
Cover Designer: Gina Hagen Kolenda
Cover Illustration: Susan Cyr
Design Manager: Gina Hagen
Prepress and Manufacturing: Caroline Fell
Access the latest information about Addison-Wesley titles from our World Wide Web site:
www.aw.com/cs
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in this book, and Addison-
Wesley was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
The programs and applications presented in this book have been included for their
instructional value. They have been tested with care, but are not guaranteed for any
particular purpose. The publisher does not offer any warranties or representations, nor
does it accept any liabilities with respect to the programs or applications.
Fibrary of Congress Cataloging-in-Publication Data
Budd, Timothy.
An introduction to object-oriented programming / Timothy A. Budd.—3rd ed.
p. cm.
Includes index.
ISBN 0-201-76031-2(pbk.)
1. Object-oriented programming (Computer science) I. Title.
QA76.64B83 2002
005.1T7-dc21 2001045060
CIP
Copyright © 2002 by by Pearson Education, Inc.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval
system, or transmitted, in any form or by any means, electronic, mechanical, photocopying,
recording, or otherwise, without the prior written permission of the publisher. Printed in
the United States of America.
123456789 10—HP—04030201
Preface
When I began writing my first book on Smalltalk in 1983, I distinctly remember
thinking that I must write quickly so as to not miss the crest of the object-oriented
programming wave. Who would have thought that two decades later object-
oriented programming would still be going strong? And what a long, strange
trip it has been.
In the two decades that object-oriented programming has been studied, it has
become the dominant programming paradigm. In the process, it has changed
almost every facet of computer science. And yet I find that my goal for the third
edition of this book has remained unchanged from the first. It is still my hope
to impart to my students and, by extension, my readers an understanding of
object-oriented programming based on general principles and not specific to any
particular language.
Languages come and go in this field with dizzying rapidity. In the first edi¬
tion I discussed Objective-C and Apple’s version of Object Pascal, both widely
used at that time. Although both languages still exist, neither can at present be
considered a dominant language. (However, I talk about Objective-C in the third
edition because from a language point of view it has many interesting and unique
features.) Between the first edition and the third many languages seem to have
disappeared (such as Actor and Turing), while others have come into existence
(such as Java, Eiffel, and Self). Many existing languages have acquired object ex¬
tensions (such as Common Lisp and Object Perl), and many have burst onto the
scene for a short while and then just as suddenly disappeared (for example, Sather
and Dylan). Then there is Beta, a language that hints at wonderful ideas behind
an incomprehensible syntax. Prediction is difficult, particularly about the future.
Will languages that are just now appearing, such as Ruby, have staying power, or
will they go the way of Dylan? What about C#? It is difficult to imagine that any
language with Microsoft behind it will fail to be successful, but stranger things
have happened. (Personally, I think that C# will last because it presents a route
for Visual Basic programmers to finally progress to a better language, but that
V
VI □ Preface
few Java or C++ programmers will migrate to the new language. Time will tell if
my powers of foresight are any better than anybody else’s.)
For the present edition I have expanded the number of languages that I use
for examples, but I have eliminated many long narratives on a single language.
Descriptions of techniques are often given in the form of tables or shorter expla¬
nations. As with the first two editions, I make no pretenses of being a reference
manual for any language, and students producing anything more than trivial pro¬
grams m any of the languages I discuss would do well to avail themselves of a
language-specific source.
Nevertheless, in this third edition I have attempted to retain the overall struc¬
ture I used in the first two editions. This can be described as a series of themes.
I. Introduction and Design. Chapter 1 introduces in an informal setting the basic
concepts of object-oriented programming. Chapter 2 continues this by discussing
the tools used by computer scientists to deal with complexity and how object-
oriented techniques fit into this framework. Chapter 3 introduces the principle
of designing by responsibility. These three chapters are fundamental, and their
study should not be given short shrift. In particular, I strongly encourage at
least one, if not several, group exercises in which CRC cards, introduced in
Chapter 3, are used in problem solving. The manipulation of physical index cards
in a group setting is one of the best techniques I have encountered for developing
and reinforcing the notions of behavior, responsibility, and encapsulation.
In the past decade the field of object-oriented design has expanded consider¬
ably. And for many readers Chapter 3 may either be too little or too much—too
much if they already have extensive experience with object-oriented modeling
languages and design, and too little if they have never heard of these topics. Never¬
theless, I have tried to strike a balance. I have continued to discuss responsibility-
driven design, although it is now only one of many alternative object-oriented
design techniques, because I think it is the simplest approach for beginning stu¬
dents to understand.
II. Classes, Methods, and Messages. Chapters 4 and 5 introduce the basic
syntax used by our example languages (Smalltalk, C++, Java, Objective-C, Object
and Delphi Pascal, and several others) to create classes and methods and to
send messages. Chapter 4 concentrates on the compile-time features (classes and
methods), and Chapter 5 describes the dynamic aspects (creating objects and
sending messages). Chapters 6 and 7 reinforce these ideas with the first of a series
of case studies—example programs developed in an object-oriented fashion and
illustrating various features of the technique.
III. Inheritance and Software Reuse. Although inheritance is introduced in
Chapter 1, it does not play a prominent role again until Chapter 8. Inheritance
Preface vii
and polymorphic substitution is discussed as a primary technique for software
reuse. The case study in Chapter 9, written in the newly introduced language
C#, both illustrates the application of inheritance and the use of a standard API
(application programming interface).
IV. Inheritance in More Detail. Chapters 10 through 13 delve into the concepts
of inheritance and substitution in greater detail. The introduction of inheritance
into a programming language has an impact on almost every other aspect of
the language, and this impact is often not initially obvious to the student (or
programmer). Chapter 10 discusses the sometimes subtle distinction between sub¬
classes and subtypes. Chapter 11 investigates how different languages approach
the use of static and dynamic features. Chapter 12 examines some of the surpris¬
ing implications that result from the introduction of inheritance and polymorphic
substitution into a language. Chapter 13 discusses the often misunderstood topic
of multiple inheritance. ^
V. Polymorphism. Much of the power of object-oriented programming comes
through the application of various forms of polymorphism. Chapter 14 intro¬
duces the basic mechanisms used for attaining polymorphism in object-oriented
languages and is followed by four chapters that explore the principal forms of
polymorphism in great detail.
VI. Applications of Polymorphism. Chapter 19 examines one of the most com¬
mon applications of polymorphism, the development of classes for common data
structure abstractions. Chapter 20 is a case study that examines a recent addition
to the language C++, the STL. Chapter 21 presents the idea oi frameworks, a pop¬
ular and very successful approach to software reuse that builds on the mechanisms
provided by polymorphism. Chapter 22 describes one well-known framework,
the Java Abstract Windowing Toolkit.
VII. Object Interactions. Starting in Chapter 23 we move up a level of ab¬
straction and consider classes in more general relationships and not just the
parent/child relationship. Chapter 23 discusses the ways two or more classes (or
objects) can interact with each other. Many of these interactions have been cap¬
tured and defined in a formalism called a design pattern. The concept of design
patterns and a description of the most common design patterns are presented in
Chapter 24.
VIII. Advanced Topics. The final three chapters discuss topics that can be
considered advanced for an introductory text such as this one. These include
the idea of reflection and introspection (Chapter 25), network programming
(Chapter 26), and the implementation techniques used in the execution of object-
oriented languages (Chapter 27).
s Preface
viii
In the ten-week course I teach at Oregon State University I devote approxi¬
mately one week to each of the major areas just described. Students in this course
are upper-division undergraduate and first-year graduate students. In conjunction
with the lectures, students work on moderate-sized projects, using an object-
oriented language of their choice, and the term ends with student presentations
of project designs and outcomes.
Any attempt to force a complex and multifaceted topic into a linear narrative
will run into issues of ordering, and this book is no exception. In general my
approach has been to introduce an idea as early as possible and then in later
chapters explore the idea in more detail, bringing out aspects or issues that
might not be obvious on first encounter. Despite my opinion that my ordering
makes sense, I am aware that others may find it convenient to select a different
approach. In particular, some instructors find it useful to bring forward some of
the software engineering issues that I postpone until Chapter 23, thereby bringing
them closer to the design chapter (Chapter 3). Similarly, while multiple inheritance
is a form of inheritance and therefore rightly belongs in Section IV, the features
that make multiple inheritance difficult to work with derive from interactions
with polymorphism and hence might make more sense after students have had
time to read Section V. For these reasons and many more, instructors should feel
free to adapt the material and the order of presentation to their own particular
circumstance.
Assumed Background s
I have presented the material in this book assuming only that the reader is
knowledgeable in some conventional programming language, such as Pascal or
C. In my courses, the material has been used successfully at the upper-division
(junior or senior) undergraduate level and at the first-year graduate level. In some
cases (particularly in the last quarter of the book), further knowledge may be
helpful but is not assumed. For example, a student who has taken a course in
software engineering may find some of the material in Chapter 23 more relevant,
and one who has had a course in compiler construction will find Chapter 27 more
intelligible. Both chapters can be simplified in presentation if necessary.
Many sections have been marked with an asterisk (’''). These represent op¬
tional material. Such sections may be interesting but are not central to the ideas
being presented. Often they cover a topic that is relevant only to a particular
object-oriented language and not to object-oriented programming in general. This
material can be included or omitted at the discretion of the instructor, depend¬
ing on the interests and backgrounds of the students and the instructor or on the
dictates of time.
Preface IX
Obtaining the Source b
Source code for the case studies presented in the book can be accessed via the
mechanism of anonymous ftp from the machine ftp.cs.orst.edu in the di¬
rectory /pub/budd/oopintro. This directory will also be used to maintain a
number of other items, such as an errata list, study questions for each chap¬
ter, and copies of the overhead slides I use in my course. This information can
also be accessed via the World Wide Web from my personal home pages at
http: //www. cs . orSt. edu/~budd. Requests for further information can be for¬
warded to the electronic mail address buddies . orst. edu or to Professor Timothy
A. Budd, Department of Computer Science, Oregon State University, Corvallis,
Oregon 97331.
Acknowledgments □
I am certainly grateful to the 65 students in my course, CS589, at Oregon State
University, who in the fall of 1989 suffered through the development of the first
draft of the first edition of this text. They received one chapter at a time, often
only a day or two before I lectured on the material. Their patience in this regard is
appreciated. Their specific comments, corrections, critiques, and criticisms were
most helpful. In particular, I wish to acknowledge the detailed comments provided
by Thomas Amoth, Kim Drongesen, Frank Griswold, Rajeev Pandey, and Phil
Ruder.
The solitaire game developed in Chapter 9 was inspired by the project com¬
pleted by Kim Drongesen, and the billiards game in Chapter 7 was based on the
project by Guenter Marnier and Dietrich Wettschereck. In both cases, however,
the code itself has been entirely rewritten and is my own. In fact, in both cases
my code is considerably stripped down for the purposes of exposition and is in
no way comparable to the greatly superior projects completed by those students.
For an author, it is always useful to have others provide an independent
perspective on one’s work, and I admit to gaining useful insights into the first
edition from a study guide prepared by Arina Brintz, Louise Leenen, Tommie
Meyer, Helene Rosenblatt, and Anel Viljoen of the Department of Computer
Science and Information Systems at the University of South Africa in Pretoria.
Countless people have provided assistance by pointing out errors or omissions
in the first two editions and by offering improvements. I am grateful to them all
and sorry that I cannot list them by name.
I benefitted greatly from comments provided by several readers of an early
manuscript draft of this third edition. These reviewers included Ali Behforooz
(Towson University), Hang Lau (Concordia University, Canada), Blayne Mayfield
(Oklahoma State University), Robert Morse (University of Evansville), Roberto
X Q Preface
Ordonez (Andrews University), Shon Vick (University of Maryland, Baltimore
County), and Conrad Weisert (Information Disciplines, Inc.). I have made exten¬
sive revisions in response to their comments, and therefore any remaining errors
are mine alone and no reflection on their efforts.
For the third edition my capable, competent, and patient editor at Addison-
Wesley has been Susan Hartman-Sullivan, assisted by Elinor Actipis. Final copy
was coordinated by Diane Freed. Layout and production were performed by Paul
Anagnostopoulos and Jacqui Scarlott of Windfall Software. I have worked with
Paul and Jacqui on several books now, and I’m continually amazed by the results
they are able to achieve from my meager words.
Contents
Preface
1 0 Thinking Object-Oriented
1.1 Why Is OOP Popular? 2
1.2 Language and Thought 2
1.2.1 Eskimos and snow 3
1.2.2 An example from computer languages 3
1.2.3 Church’s conjecture and the Whorf hypothesis 5
1.3 A New Paradigm 7
1.4 A Way of Viewing the World 8
1.4.1 Agents and communities 9
1.4.2 Messages and methods 10
1.4.3 Responsibilities 11
1.4.4 Classes and instances 11
1.4.5 Class hierarchies—inheritance 12
1.4.6 Method binding and overriding 14
1.4.7 Summary of object-oriented concepts 14
1.5 Computation as Simulation 15
1.5.1 The power of metaphor 16
1.5.2 Avoiding infinite regression 17
1.6 A Brief History 18
Summary 19
Further Reading 20
Self-Study Questions 22
Exercises 23
XI
xii □ Contents
2 0 Abstraction 25
2.1 Layers of Abstraction 26
2.2 Other Forms of Abstraction 30
2.2.1 Division into parts 32
2.2.2 Encapsulation and interchangeability 32
2.2.3 Interface and implementation 33
2.2.4 The service view 34
2.2.5 Composition 34
2.2.6 Layers of specialization 36
2.2.7 Patterns 38
2.3 A Short History of Abstraction Mechanisms 39
2.3.1 Assembly language 39
2.3.2 Procedures 40
2.3.3 Modules 41
2.3.4 Abstract data types 43
2.3.5 A service-centered view 44
2.3.6 Messages, inheritance, and polymorphism 44
Summary 45
Further Information 46
Self-Study Questions 47
Exercises 47
3 □ Object-Oriented Design 49
3.1 Responsibility Implies Noninterference 50
3.2 Programming in the Small and in the Large 51
3.3 Why Begin with Behavior? 51
3.4 A Case Study in RDD 52
3.4.1 The Interactive Intelligent Kitchen Helper 53
3.4.2 Working through scenarios 53
3.4.3 Identification of components 54
3.5 CRC Cards—Recording Responsibility 55
3.5.1 Give components a physical representation 55
3.5.2 The what/who cycle 56
3.5.3 Documentation 56
3.6 Components and Behavior 57
Contents
3.6.1 Postponing decisions 58
3.6.2 Preparing for change 59
3.6.3 Continuing the scenario 59
3.6.4 Interaction diagrams 61
3.7 Software Components 62
3.7.1 Behavior and state 62
3.7.2 Instances and classes 63
3.7.3 Couplmg and cohesion 63
3.7.4 Interface and implementation-—Parnas’s principles
3.8 Formalize the Interface 65
3.8.1 Coming up with names 65
3.9 Designing the Representation 67
3.10 Implementing Components 67
3.11 Integration of Components 68
3.12 Maintenance and Evolution
Summary 69
Further Reading 70
Self-Study Questions 70
Exercises 71
69
4 □ Classes and Methods
4.1 Encapsulation 73
4.2 Class Definitions 74
4.2.1 C++, Java, and C# 75
4.2.2 Apple Object Pascal and Delphi Pascal 77
4.2.3 Smalltalk 77
4.2.4 Other languages 79
4.3 Methods 80
4.3.1 Order of methods in a class declaration 82
4.3.2 Constant or immutable data fields 83
4.3.3 Separating definition and implementation 83
4.4 Variations on Class Themes 87
4.4.1 Methods without classes in Oberon 87
4.4.2 Interfaces 88
4.4.3 Properties 89
64
xiv □ Contents
4.4.4 Forward definitions 90
4.4.5 Inner or nested classes 91
4.4.6 Class data fields 94
4.4.7 Classes as objects 96
Summary 97
Further Reading 97
Self-Study Questions 98
Exercises 98
5 □ Messages, Instances, and Initialization 101
5.1 Message-Passing Syntax 101
5.2 Statically and Dynamically Typed Languages 103
5.3 Accessing the Receiver from within a Method 104
5.4 Object Creation 106
5.4.1 Creation of arrays of objects 107
5.5 Pointers and Memory Allocation 108
5.5.1 Memory recovery 109
5.6 Constructors 111
5.6.1 The orthodox canonical class form 115
5.6.2 Constant values 116
5.7 Destructors and Finalizers 117
5.8 Metaclasses in Smalltalk 120
Summary 122
Further Reading 122
Self-Study Questions 123
Exercises 123
6 0 A Case Study: The Eight-Queens Puzzle 1 25
6.1 The Eight-Queens Puzzle 125
6.1.1 Creating objects that find their own solution 126
6.2 Using Generators 127
6.2.1 Initialization 128
6.2.2 Finding a solution 129
6.2.3 Advancing to the next position 129
Contents XV
6.3 The Eight-Queens Puzzle in Several Languages 130
6.3.1 The eight-queens puzzle in Object Pascal 130
6.3.2 The eight-queens puzzle in C++ 133
6.3.3 The eight-queens puzzle in Java 136
6.3.4 The eight-queens puzzle in Objective-C 139
6.3.5 The eight-queens puzzle in Smalltalk 142
6.3.6 The eight-queens puzzle in Ruby 143
Summary 145
Further Reading 145
Self-Study Questions 145
Exercises 146
7 0 A Case Study: A Billiards Game 147
7.1 The Elements of Billiards 147
7.2 Graphical Objects 148
7.2.1 The wall graphical object 149
7.2.2 The hole graphical object ISO
7.2.3 The ball graphical object 151
7.3 The Main Program 155
7.4 Using Inheritance 156
Summary 159
Further Information 159
Self-Study Questions 159
Exercises 160
8 0 Inheritance and Substitution 161
8.1 An Intuitive Description of Inheritance 161
8.1.1 The is-a test 162
8.1.2 Reasons to use inheritance 162
8.2 Inheritance in Various Languages 164
8.3 Subclass, Subtype, and Substitution 166
8.3.1 Substitution and strong typing 167
' ’ 8.4 Overriding and Virtual Methods 168
8.5 Interfaces and Abstract Classes 170
XVI □ Contents
8.6 Forms of Inheritance 171
8.6.1 Subclassing for specialization (subtyping) 171
8.6.2 Subclassing for specification 171
8.6.3 Subclassing for construction 172
8.6.4 Subclassing for generalization 173
8.6.5 Subclassing for extension 174
8.6.6 Subclassing for limitation 174
8.6.7 Subclassing for variance 174
8.6.8 Subclassing for combination 175
8.6.9 Summary of the forms of inheritance 175
8.7 Variations on Inheritance 176
8.7.1 Anonymous classes in Java 176
8.7.2 Inheritance and constructors 177
8.7.3 Virtual destructors 178
8.8 The Benefits of Inheritance 179
8.8.1 Software reusability 179
8.8.2 Code sharing 179
8.8.3 Consistency of interface 179
8.8.4 Software components 179
8.8.5 Rapid prototyping 180
8.8.6 Polymorphism and frameworks 180
8.8.7 Information hiding 180
8.9 The Costs of Inheritance 181
8.9.1 Execution speed 181
8.9.2 Program size 181
8.9.3 Message-passing overhead 181
8.9.4 Program complexity 182
Summary 182
Further Reading 183
Self-Study Questions 183
Exercises 184
187
9 □ A Case Study—A Card Game
9.1 The Class PlayingCard 187
9.2 Data and View Classes 189
9.3 The Game 190
Contents xvii
9.4 Card Piles—Inheritance in Action 191
9.4.1 The default card pile 193
9.4.2 The suit piles 194
9.4.3 The deck pile 194
9.4.4 The discard pile 196
9.4.5 The tableau piles 197
9.5 Playing the Polymorphic Game 199
9.6 The Graphical User Interface 199
Summary 204
Further Reading 204
Self-Study Questions 204
Exercises 205
10 0 Subclasses and Subtypes 207
10.1 Substitutability 207
10.2 Subtypes 208
10.3 The Substitutability Paradox 211
10.3.1 Is this a problem? 212
10.4 Subclassing for Construction 212
10.4.1 Private inheritance in C++ 214
10.5 Dynamically Typed Languages 215
10.6 Pre- and Postconditions 216
10.7 Refinement Semantics 217
Summary 218
Further Reading 218
Self-Study Questions 219
Exercises 219
11 E Static and Dynamic Behavior 221
11.1 Static versus Dynamic Typing 221
11.2 Static and Dynamic Classes 223
11.2.1 Run-time type determination 225
11.2.2 Down casting (reverse polymorphism) 227
XViii □ Contents
11.2.3 Run-time testing without language support 227
11.2.4 Testing message understanding 229
11.3 Static versus Dynamic Method Binding 230
Summary 232
Further Reading 233
Self-Study Questions 233
Exercises 234
12 0 Implications of Substitution
12.1 Memory Layout 235
12.1.1 Minimum static space allocation 237
12.1.2 Maximum static space allocation 240
12.1.3 Dynamic memory allocation 240
12.2 Assignment 242
12.2.1 Assignment in C++ 242
12.3 Copies and Clones 245
12.3.1 Copies in Smalltalk and Objective-C 24S
12.3.2 Copy constructors in C++ 245
12.3.3 Cloning in Java 246
12.4 Equality 247
12.4.1 Equality and identity 247
12.4.2 The paradoxes of equality testing 248
Summary 250
Eurther Reading 251
Self-Study Questions 251
Exercises 251
13 0 Multiple Inheritance
13.1 Inheritance as Categorization 254
13.1.1 Incomparable complex numbers 255
13.2 Problems Arising from Multiple Inheritance 257
13.2.1 Name ambiguity 257
13.2.2 Impact on substitutability 259
13.2.3 Redefinition in Eiffel 260
13.2.4 Resolution by class ordering in CEOS 261
235
253
Contents XIX
13.3 Multiple Inheritance of Interfaces 263
13.3.1 Mixins in CLOS 266
13.4 Inheritance from Common Ancestors 267
13.4.1 Constructors and multiple inheritance 270
13.5 Inner Classes 271
Summary 272
Further Reading 273
Self-Study Questions 273
Exercises 273
14 □ Polymorphism and Software Reuse 275
14.1 Polymorphism in Programming Languages 275
14.1.1 Many tools, one goal 277
14.2 Mechanisms for Software Reuse 277
14.2.1 Using composition 278
14.2.2 Using inheritance 280
14.2.3 Composition and inheritance contrasted 282
14.3 Efficiency and Polymorphism 283
14.4 Will Widespread Software Reuse Become Reality? 284
Summary 285
Further Information 285
Self-Study Questions 286
Exercises 286
1 5 E Overloading 287
15.1 Type Signatures and Scopes 288
15.2 Overloading Based on Scopes 289
15.3 Overloading Based on Type Signatures 290
15.3.1 Coercion and conversion 293
15.4 Redefinition 299
15.5 Polyadicity 301
" 15.5.1 Optional parameters 303
15.6 Multi-Methods 303
XX Q Contents
15.6.1 Overloading Based on Values 306
Summary 306
Further Information 306
Self-Study Questions 307
Exercises 307
16 □ Overriding 309
16.1 Notating Overriding 311
16.2 Replacement versus Refinement 313
16.2.1 Replacement in Smalltalk 313
16.2.2 Refinement in Beta 316
16.2.3 Refinement and the subclass/subtype distinction 319
16.2.4 Wrappers in CLOS 319
16.3 Deferred Methods 320
16.4 Overriding versus Shadowing 322
16.5 Covariance and Contravariance 324
16.6 Variations on Overriding 329
16.6.1 Final methods in Java 329
16.6.2 Versioning in C# 330
Summary 331
Further Information 332
Self-Study Questions 332
Exercises 332
17 0 The Polymorphic Variable 335
17.1 Simple Polymorphic Variables 335
17.2 The Receiver Variable 337
17.2.1 The role of the polymorphic variable in frameworks 339
17.2.2 Endpoint comparisons in Smalltalk 340
17.2.3 Self and super 341
17.3 Downcasting 343
17.4 Pure Polymorphism 344
Summary 347
Further Information 347
Self-Study Questions 348
Exercises 348
Contents XX i
18 0 Generics
18.1 Template Functions 349
18.2 Template Classes 351
18.2.1 Bounded genericity 353
18.3 Inheritance in Template Arguments 353
18.3.1 Inheritance and arrays 355
18.4 Case Study—Combining Separate Classes 356
Summary 360
Further Reading 360
Self-Study Questions 360
Exercises 360
19 0 Container Classes
19.1 Containers in Dynamically Typed Languages 363
19.1.1 Containers in Smalltalk-80 364
19.2 Containers in Statically Typed Languages 365
19.2.1 The tension between typing and reuse 366
19.2.2 Substitution and downcasting 368
19.2.3 Using substitution and overriding 372
19.2.4 Parameterized classes 374
19.3 Restricting Element Types 376
19.4 Element Traversal 378
19.4.1 Iterator loops 379
19.4.2 The visitor approach 381
Summary 385
Eurther Reading 386
' ' Self-Study Questions 387
Exercises 387
349
363
XX ii □ Contents
20 0 A Case Study: The STL 389
20.1 Iterators 391
20.2 Function Objects 393
20.3 Example Program—An Inventory System 394
20.4 Example Program—Graphs 396
20.4.1 Shortest path algorithm 399
20.4.2 Developing the data structures 399
20.5 A Concordance 402
20.6 The Future of OOP 405
Summary 406
Further Reading 406
Self-Study Questions 406
Exercises 406
21 0 Frameworks 407
21.1 Reuse and Specialization 407
21.1.1 High-and low-level abstractions 410
21.1.2 An upside-down library 412
21.2 Example Erameworks 413
21.2.1 The Java Applet API 413
21.2.2 A Simulation Framework 414
21.2.3 An event-driven simulation framework 415
Summary 422
Further Reading 422
Self-Study Questions 422
Exercises 422
22 0 An Example Framework:
The AWT and Swing 423
22.1 The AWT Class Hierarchy 423
22.2 The Layout Manager 426
22.3 Listeners 428
22.3.1 Adapter classes 429
22.4 User Interface Components 430
Contents
22.5 Case Study: A Color Display 433
22.6 The Swing Component Library 437
22.6.1 Import libraries 437
22.6.2 Different components 437
22.6.3 Different paint protocol 438
22.6.4 Adding components to a window 438
Summary 438
Further Reading 439
Self-Study Questions 439
Exercises 439
23 0 Object Interconnections
23.1 Coupling and Cohesion 442
23.1.1 Varieties of coupling 442
23.1.2 Varieties of cohesion 445
23.1.3 The Law of Demeter 447
23.1.4 Class-level versus object-level visibility 448
23.1.5 Active values 449
23.2 Subclass Clients and User Clients 450
23.3 Control of Access and Visibility 451
23.3.1 Visibility in Smalltalk 451
23.3.2 Visibility in Object Pascal 452
23.3.3 Visibility in C++ 452
23.3.4 Visibility in Java 457
23.3.5 Visibility in Objective-C 458
23.4 Intentional Dependency 459
Summary 460
Further Reading 460
Self-Study Questions 461
Exercises 461
24 0 Design Patterns
24.1 Controlling Information Flow 464
24.2 Describing Patterns 465
24.3 Iterator 466
xxiii
441
463
XXIV H Contents
24.4 Software Factory 467
24.5 Strategy 468
24.6 Singleton 469
24.7 Composite 469
24.8 Decorator 471
24.9 The Double-Dispatching Pattern 472
24.10 Flyweight 474
24.11 Proxy 474
24.12 Facade 475
24.13 Observer 475
Summary 476
Further Reading 477
Self-Study Questions 478
Exercises 478
25 □ Reflection and Introspection
25.1 Mechanisms for Understanding 479
25.1.1 Class objects 479
25.1.2 The class name as string 481
25.1.3 Testing the class of an object 481
25.1.4 Creating an instance from a class 483
25.1.5 Testing if an object understands a message 484
25.1.6 Class behavior 484
25.2 Methods as Objects 485
25.3 Mechanisms for Modification 486
25.3.1 Method editing in Smalltalk 486
25.3.2 Dynamic class loading in Java 487
25.4 Metaclasses 489
Summary 491
Further Reading 491
Self-Study Questions 492
479
Contents XXV
26 0 Distributed Objects
26.1 Addresses, Ports, and Sockets 494
26.2 A Simple Client/Server Program 496
26.3 Multiple Clients 498
26.4 Transmitting Objects over a Network 504
26.5 Providing More Complexity 507
Summary 507
Further Reading 508
Self-Study Questions 508
Exercises 508
27 0 Implementation
27.1 Compilers and Interpreters 511
27.2 The Receiver as Argument 512
27.3 Inherited Methods 513
27.3.1 The problem of multiple inheritance 514
173.1 The slicing problem 515
27.4 Overridden Methods 515
27.4.1 Eliminating virtual calls.and in-lining 517
27.5 Name Encoding 518
27.6 Dispatch Tables 518
27.6.1 A method cache 510
27.7 Bytecode Interpreters 521
27.8 Just-in-Time Compilation 523
Summary 524
Eurther Reading 524
Self-Study Questions 525
Exercises 525
A 0 Source for the Eight-Queens Puzzle
A.l Eight-Queens in Apple Object Pascal 527
A.2 Eight-Queens in C++ 530
493
511
527
XXVi Q Contents
A.3 Eight-Queens in Java 532
A.4 Eight-Queens in Objective-C 536
A.5 Eight-Queens in Ruby 539
A. 6 Eight-Queens in Smalltalk 541
B 0 Source for the Billiards Game 543
B. l The Version without Inheritance 543
B.2 The Version with Inheritance 552
C 0 Source for the Solitaire Game 557
Glossary 569
References 585
Index 599
Third Edition
An Introduction to
Object-Oriented
Programming
✓
1 fit
» •
K' CK* CWV’’ 37
► ..i
sw
m
w
4nd
•t
I«
. • f '
■ • * -j (ffh ■ *
'■*1 *
Although the fundamental features of what we now call ohject-oriented program¬
ming were invented in the 1960s, object-oriented languages really caught the
attention of the computing public-at-large in the 1980s. Two seminal events were
the publication of a widely read issue of Byte (August 1981) that described the
programming language Smalltalk, and the first international conference on object-
oriented programming languages and applications, held in Portland, Oregon in
1986.
Now, almost 20 years later, the situation noted in the first edition of this book
(1991) still exists.
Object-oriented programming (OOP) has become exceedingly popular in
the past few years. Software producers rush to release object-oriented
versions of their products. Countless books and special issues of academic
and trade journals have appeared on the subject. Students strive to list
“experience in object-oriented programming” on their resumes. To judge
from this frantic activity, object-oriented programming is being greeted
with even more enthusiasm than we saw heralding earlier revolutionary
ideas, such as “structured programming” or “expert systems.”
My intent in these first two chapters is to investigate and explain the basic
principles of object-oriented programming and, in so doing to illustrate the
following two propositions.
• OOP is a revolutionary idea, totally unlike anything that has come before in
programming.
1
2 Chapter 1 Q Thinking Object-Oriented
• OOP is an evolutionary step, following naturally on the heels of earlier
programming abstractions.
1.1 □ Why Is OOP Popular?
There are a number of important reasons why in the past two decades object-
oriented programming has become the dominant programming paradigm. Object-
oriented programming scales very well, from the most trivial of problems to
the most complex tasks. It provides a form of abstraction that resonates with
techniques people use to solve problems in their everyday lives. And for most of
the dominant object-oriented languages there are an increasingly large number of
libraries that assist in the development of applications for many domains.
Object-oriented programming is just the latest in a long series of solutions that
has been proposed to help solve the “software crisis.” At heart, the software crisis
simply means that our imaginations, and the tasks we would like to solve with
the help of computers, almost always outstrip our abilities.
But while object-oriented techniques do facilitate the creation of complex
software systems, it is important to remember that OOP is not a panacea. Pro¬
gramming a computer is still one of the most difficult tasks people undertake.
Becoming proficient in programming requires talent, creativity, intelligence, logic,
the ability to build and use abstractions, and experience—even when the best of
tools are available.
I suspect another reason for the particular popularity of languages such as
C++ and Delphi (as opposed to languages such as Smalltalk and Beta) is that
managers and programmers alike hope that a C or Pascal programmer can be
changed into a C++ or Delphi programmer with no more effort than the addition
of a few characters to their job title. Unfortunately, this hope is a long way
from being realized. Object-oriented programming is a new way of thinking
about what it means to compute, about how we can structure information
and communicate our intentions both to each other and to the machine. To
become proficient in object-oriented techniques requires a complete reevaluation
of traditional software development.
1.2 □ Language and Thought
In his book Language, Thought & Reality, Benjamin Lee Whorf discusses the
ideas of linguist Edward Sapir.
Human beings do not live in the objective world alone, nor alone in the
world of social activity as ordinarily understood, but are very much at
the mercy of the particular language which has become the medium of
expression for their society. It is quite an illusion to imagine that one adjusts
1.2 Language and Thought 3
to reality essentially without the use of language and that language is merely
an incidental means of solving specific problems of communication or
reflection. The fact of the matter is that the “real world” is to a large extent
unconsciously built up on the language habits of the group .... We see and
hear and otherwise experience very largely as we do because the language
habits of our community predispose certain choices of interpretation.
This quote emphasizes the fact that the languages we speak directly influence
the way in which we view the world. This is true not only for natural languages,
such as the kind studied by early-twentieth-century American linguists Edward
Sapir and Benjamin Lee Whorf, but also for artificial languages, such as those we
use in programming computers.
1.2.1 Eskimos and snow
An almost universally cited e?tample of the phenomenon of language influencing
thought, although also perhaps an erroneous one, is that Eskimo (or Inuit)
languages have different words to describe different types of snow—wet, fluffy,
heavy, icy, and so on. This is not surprising. Any community with common
interests will naturally develop a specialized vocabulary for concepts they wish
to discuss. (Meteorologists, despite working in English, face similar problems of
communication and have also developed their own extensive vocabulary.)
What is important is to not overgeneralize the conclusion we can draw from
this simple observation. It is not that the Eskimo eye is in any significant respect
different from my own or that Eskimos can see things I cannot perceive. With
time and training I could do just as well at differentiating types of snow. But the
language I speak (English) does not force me into doing so, and so it is not natural
to me. Thus, a different language (such as Inuktitut) can lead one (but does not
require one) to view the world in a different fashion.
Making effective use of object-oriented principles requires one to view the
world in a new way. But simply using an object-oriented language (such as Java
or C+-I-) does not, by itself, force one to become an object-oriented programmer.
While the use of an object-oriented language will simplify the development of
object-oriented solutions, it is true, as it has been quipped, that “EORTRAN
programs can be written in any language.”
1.2.2 An example from computer languages
The relationship we noted between language and thought for natural languages
is even more pronounced in artificial computer languages. That is, the language
in which a programmer thinks a problem will be solved will fundamentally color
and alter the way an algorithm is developed.
4 Chapter 1 □ Thinking Object-Oriented
Here is an example that illustrates this relationship between computer lan¬
guage and problem solution. Several years ago a student working in genetic
research was faced with a task in the analysis of DNA sequences. The problem
could be reduced to relatively simple form. The DNA is represented as a vector of
N integer values, where N is very large (on the order of tens of thousands). The
problem was to discover whether any pattern of length M, where M was a fixed
and small constant (say 5 or 10), is ever repeated in the array of values.
1 m m n
t c g a g t c g a g
The programmer dutifully sat down and wrote a simple and straightforward
FORTRAN program something like the following.
DO 10 I = 1, N-M
DO 10 J = 1, N-M
FOUND = .TRUE.
DO 20 K = 1, M
20 IF XEl+K-1] .NE. X[J+K-1] THEN FOUND = .FALSE.
IF FOUND THEN ...
10 CONTINUE
He was somewhat disappointed when trial runs indicated his program would
need many hours to complete. He discussed his problem with a second student
who happened to be proficient in the programming language APL. She offered to
try to write a program for this problem. The first student was dubious. After all,
FORTRAN was known to be one of the most “efficient” programming languages.
It was compiled; APL was only interpreted. So it was with a certain amount of
incredulity that he discovered that the APL programmer was able to write an
algorithm that worked in a matter of minutes, not hours.
What the APL programmer had done was to rearrange the problem. Rather
than working with a vector of N elements, she reorganized the data into a matrix
with roughly N rows and M columns.
Xi X2 • • •
X2 X3 • • •
^n—m X„_i
^n—(m— 1) . . . ^n—
She then ordered this matrix by rows (that is, treated each row as a unit,
moving entire rows during the process of sorting). If any pattern was repeated,
then two adjacent rows in the ordered matrix would have identical values.
1.2 Language and Thought 5
T G G A C C
T G G A G C
It was a trivial matter to check for this condition. The reason the APT pro¬
gram was faster had nothing to do with the speed of APT versus FORTRAN;
it was simply that the FORTRAN program employed an algorithm that was
0(M X N^), whereas the sorting solution used by the APT programmer required
approximately 0(M x N log N) operations.
The point of this story is not that APT is in any way a “better” programming
language than FORTRAN but that the APT programmer was naturally led to
discover an entirely different form of solution. The reason, in this case, is that
loops are very difficult to write in APT, whereas sorting is trivial—it is a built-in
operator defined as part of the language. Thus, because the sorting operation is so
easy to perform, good APT programmers tend to look for novel applications for
it. This is how the programming language in which the solution is to be written
directs the programmer’s mind to view the problem in a certain way.
* 1.2.3 Church’s conjecture and the Whorf hypothesis
The assertion that the language in which an idea is expressed can influence
or direct a line of thought is relatively easy to believe. However, a stronger
conjecture, known in linguistics as the Sapir-Whorf hypothesis, goes much further
and remains controversial.
The Sapir-Whorf hypothesis asserts that it may be possible for an individual
working in one language to imagine thoughts or to utter ideas that cannot in
any way be translated, or even understood by individuals operating in a different
linguistic framework. According to advocates of the hypothesis, this can occur
when the language of the second individual has no equivalent words and lacks
even concepts or categories for the ideas involved in the thought. It is interesting to
compare this possibility with an almost directly opposite concept from computer
science—namely. Church’s conjecture.
Starting in the 1930s and continuing through the 1940s and 1950s there was a
great deal of interest within the mathematical and nascent computing community
in a variety of formalisms that could be used for the calculation of functions.
Examples are the notations proposed by Church [Church 1936], Post [Post 1936],
Markov [Markov 1951], Turing [Turing 1936], Kleene [Kleene 1936], and others.
Over time a number of arguments were put forth to demonstrate that many
of these systems could be used in the simulation of other systems. Often, such
argurnents for a pair of systems could be made in both directions, effectively
showing that the systems were identical in computation power. The sheer number
6 Chapter 1 H Thinking Object-Oriented
of such arguments led the logician Alonzo Church to pronounce a conjecture that
is now associated with his name.
Church’s Conjecture: Any computation for which there is an effective
procedure can be realized by a Turing machine.
By nature this conjecture must remain unproven and unprovable, since we
have no rigorous definition of the term “effective procedure.” Nevertheless, no
counterexample has yet been found, and the weight of evidence seems to favor
affirmation of this claim.
Acceptance of Church’s conjecture has an important and profound implication
for the study of programming languages. Turing machines are wonderfully simple
mechanisms, and it does not require many features in a language to simulate such
a device. In the 1960s, for example, it was demonstrated that a Turing machine
could be emulated in any language that possessed at least a conditional statement
and a looping construct [Bohm 1966]. (This greatly misunderstood result was
the major ammunition used to “prove” that the infamous goto statement was
unnecessary.)
If we accept Church’s conjecture, any language in which it is possible to
simulate a Turing machine is sufficiently powerful to perform any realizable
algorithm. (To solve a problem, find the Turing machine that produces the desired
result, which by Church’s conjecture must exist; then simulate the execution
of the Turing machine in your favorite language.) Thus, arguments about the
relative “power” of programming languages—if by power we mean “ability to
solve problems”—are generally vacuous. The late Alan Perils had a term for such
an argument. He called it a “Turing Tarpit” because it is often so difficult to
extricate oneself from it and so fundamentally pointless.
Note that Church’s conjecture is, in a certain sense, almost the exact opposite
of the Sapir-Whorf hypothesis. Church’s conjecture states that in a fundamental
way all programming languages are identical. Any idea that can be expressed
in one language can, in theory, be expressed in any language. The Sapir-Whorf
hypothesis claims that it is possible to have ideas that can be expressed in one
language that cannot be expressed in another.
Many linguists reject the Sapir-Whorf hypothesis and instead adopt a sort
of “Turing-equivalence” for natural languages. By this we mean that, with a
sufficient amount of work, any idea can be expressed in any language. For
example, while the language spoken by a native of a warm climate may not make
it instinctive to examine a field of snow and categorize it by type or use, with time
and training it certainly can be learned. Similarly, object-oriented techniques do
not provide any new computational power that permits problems to be solved
that cannot, in theory, be solved by other means. But object-oriented techniques
do make it easier and more natural to address problems in a fashion that tends
to favor the management of large software projects.
1.3 A New Paradigm 1
Thus, for both computer and natural languages the language will direct
thoughts but cannot proscribe thoughts.
1.3 B A New Paradigm
Object-oriented programming is frequently referred to as a new programming
paradigm. Other programming paradigms include the imperative-programming
paradigm (languages such as Pascal or C), the logic programming paradigm
(Prolog), and the functional-programming paradigm (ML or Haskell).
It is interesting to examine the definition of the word “paradigm.” The fol¬
lowing is from the American Heritage Dictionary of the English Language.
par a digm n. 1. A list of all the inflectional forms of a word taken as an
illustrative example of the conjugation or declension to which it belongs.
2. Any example or model. [Late Latin paradigma, from Greek paradeigma,
model, from paradeiknunai, to compare, exhibit.]
At first blush, the conjugation or declension of Latin words would seem to have
little to do with computer programming languages. To understand the connection,
we must note that the word was brought into the modern vocabulary through
an influential book. The Structure of Scientific Revolutions, by the historian of
science Thomas Kuhn [Kuhn 1970]. Kuhn used the term in the second form, to
describe a set of theories, standards, and methods that together represent a way
of organizing knowledge—that is, a way of viewing the world. Kuhn’s thesis was
that revolutions in science occur when an older paradigm is reexamined, rejected,
and replaced by another.
It is in this sense, as a model or example and as an organizational approach,
that Robert Floyd used the term in his 1979 ACM Turing Award lecture [Floyd
1979], “The Paradigms of Programming.” A programming paradigm is a way
of conceptualizing what it means to perform computation and how tasks to be
carried out on a computer should be structured and organized.
Although new to computation, the organizing technique that lies at the heart
of object-oriented programming can be traced back at least as far as Carolus Lin¬
naeus (1707-1778) (Figure 1.1). It was Linnaeus, you will recall, who categorized
biological organisms using the idea of phylum, genus, species, and so on.
Paradoxically, the style of problem solving embodied in the object-oriented
technique is frequently the method used to address problems in everyday life.
Thus, computer novices are often able to grasp the basic ideas of object-oriented
programming easily, whereas people who are more computer literate are often
blocked by their own preconceptions. Alan Kay, for example, found that it was
often easier to teach Smalltalk to children than to computer professionals [Kay
1977].
8 Chapter 1 H Thinking Object-Oriented
kingdom Animalia
phylum Mollusca Chordata
class Gastropoda Reptilla Mammalia
order Mesogastropoda Predentata
genus
species
Cypraea
Y
tigris
Triceratops
horridus
Primates
family Cypraeidae Ceratopsidae Hominidae
Homo
i
sapiens
Figure 1.1-The Linnaen Inheritance Hierarchy
In trying to understand exactly what is meant by the term object-oriented
programming, it is useful to examine the idea from several perspectives. The next
few sections outline two aspects of object-oriented programming; each illustrates
a particular reason that this technique should be considered an important new
tool.
1.4 □ A Way of Viewing the World
To illustrate some of the major ideas in object-oriented programming, let us
consider first how we might go about handling a real-world situation and then ask
how we could make the computer more closely model the techniques employed.
Suppose an individual named Chris wishes to send flowers to a friend named
Robin, who lives in another city. Because of the distance, Chris cannot simply pick
the flowers and take them to Robin in person. Nevertheless, it is a task that is
easily solved. Chris simply walks to a nearby flower shop, run by a florist named
Fred. Chris will tell Fred the kinds of flowers to send to Robin and the address
to which they should be delivered. Chris can then be assured that the flowers will
be delivered expediently and automatically.
1.4 A Way of Viewing the World 9
1 A. 1 Agents and communities
At the risk of belaboring a point, let us emphasize that the mechanism that was
used to solve this problem was to find an appropriate agent (namely, Fred) and
to pass to this agent a message containing a request. It is the responsibility of
Fred to satisfy the request. There is some method—some algorithm or set of
operations—used by Fred to do this. Chris does not need to know the particular
method that Fred will use to satisfy the request; indeed, often the person making
a request does not want to know the details. This information is usually hidden
from inspection.
An investigation, however, might uncover the fact that Fred delivers a slightly
different message to another florist in the city where Robin lives. That florist, in
turn, perhaps has a subordinate who makes the flower arrangement. The florist
then passes the flowers, along with yet another message, to a delivery person, and
so on. Earlier, the florist in Robin’s city had obtained the flowers from a flower
wholesaler who, in turn, had interactions with the flower growers, each of whom
had to manage a team of gardeners.
So, our first observation of object-oriented problem solving is that the solution
to this problem required the help of many other individuals (Figure 1.2). Without
their help, the problem could not be easily solved. We phrase this in a general
fashion.
An object-oriented program is structured as a community of interacting
agents called objects. Each object has a role to play. Each object provides
a service or performs an action that is used by other members of the
community.
Robin
Chris
Delivery Person Gardeners
Grower
Wholesaler
H Figure 1.2-The community of agents in the flower delivery process
1 0 Chapter 1 □ Thinking Object-Oriented
1.4.2 Messages and methods
The chain reaction that ultimately resulted in the solution to Chris’s problem
began with a request given to the florist, Fred. This request lead to other requests,
which lead to still more requests, until the flowers ultimately reached Chris’s
friend, Robin. We see, therefore, that members of this community interact with
each other by making requests. So, our next principle of object-oriented problem
solving is the vehicle used to indicate an action to be performed.
Action is initiated in object-oriented programming by the transmission of
a message to an agent (an object) responsible for the action. The message
encodes the request for an action and is accompanied by any additional
information (arguments) needed to carry out the request. The receiver is
the object to whom the message is sent. If the receiver accepts the message,
it accepts the responsibility to carry out the indicated action. In response
to a message, the receiver will perform some method to satisfy the request.
We have noted the important principle of information hiding in regard to
message passing—that is, the client sending the request need not know the actual
means by which the request will be honored. There is another principle, all too
human, that we see is implicit in message passing. If there is a task to perform,
the first thought of the client is to find somebody else he or she can ask to do the
work. This second reaction often becomes atrophied in many programmers with
extensive experience in conventional techniques. Frequently, a difficult hurdle
to overcome is the idea in the programmer’s mind that he or she must write
everything and not use the services of others. An important part of object-oriented
programming is the development of reusable components, and an important first
step in the use of reusable components is a willingness to trust software written
by others.
Messages Versus Procedure Calls
Information hiding is also an important aspect of programming in conventional
languages. In what sense is a message different from, say, a procedure call? In
both cases, there is a set of well-defined steps that will be initiated following the
request. But there are two important distinctions.
The first is that in a message there is a designated receiver for that message;
the receiver is some object to which the message is sent. In a procedure call, there
is no designated receiver.
The second is that the interpretation of the message (that is, the method used to
respond to the message) is determined by the receiver and can vary with different
receivers. Chris could give a message to a friend named Elizabeth, for example,
and she will understand it and a satisfactory outcome will be produced (that is.
1.4 A Way of Viewing the World 1 1
flowers will be delivered to their mutual friend Robin). However, the method
Elizabeth uses to satisfy the request (in all likelihood, simply passing the request
on to Fred) will be different from that used by Fred in response to the same request.
If Chris were to ask Kenneth, a dentist, to send flowers to Robin, Kenneth
may not have a method for solving that problem. If he understands the request
at all, he will probably issue an appropriate error diagnostic.
Fet us move our discussion back to the level of computers and programs.
There, the distinction between message passing and procedure calling is that
in message passing there is a designated receiver, and the interpretation—the
selection of a method to execute in response to the message—may vary with
different receivers. Usually, the specific receiver for any given message will not
be known until run time, so the determination of which method to invoke cannot
be made until then. Thus, we say there is late binding between the message
(function or procedure name) and the code fragment (method) used to respond
to the message. This situation is in contrast to the very early (compile-time or
link-time) binding of name to code fragment in conventional procedure calls.
1.4.3 Responsibilities
A fundamental concept in object-oriented programming is to describe behavior
in terms of responsibilities. Chris’s request for action indicates only the desired
outcome (flowers sent to Robin). Fred is free to pursue any technique that achieves
the desired objective and in doing so will not be hampered by interference from
Chris.
By discussing a problem in terms of responsibilities we increase the level of
abstraction. This permits greater independence between objects, a critical factor
in solving complex problems. The entire collection of responsibilities associated
with an object is often described by the term protocol.
A traditional program often operates by acting on data structures—for exam¬
ple, changing fields in an array or record. In contrast, an object-oriented program
requests data structures (that is, objects) to perform a service. This difference be¬
tween viewing software in traditional, structured terms and viewing it from an
object-oriented perspective can be summarized by a twist on a well-known quote.
Ask not what you can do to your data structures.
Ask what your data structures can do for you.
1.4.4 Classes and instances
Although Chris has only dealt with Fred a few times, Chris has a rough idea of the
transaction that will occur inside Fred’s flower shop. Chris is able to make certain
assumptions based on previous experience with other florists, and hence Chris can
1 2 Chapter 1 □ Thinking Object-Oriented
expect that Fred, being an instance of this category, will fit the general pattern.
We can use the term Florist to represent the category (or class) of all florists. Let us
incorporate these notions into our next principle of object-oriented programming.
All objects are instances of a class. The method invoked by an object in
response to a message is determined by the class of the receiver. All objects
of a given class use the same method in response to similar messages.
1.4.5 Class hierarchies—inheritance
Chris has more information about Fred—not necessarily because Fred is a florist
but because he is a shopkeeper. Chris knows, for example, that a transfer of money
will be part of the transaction and that in return for payment Fred will offer
a receipt. These actions are true of grocers, stationers, and other shopkeepers.
Since the category Florist is a more specialized form of the category Shopkeeper, any
knowledge Chris has of Shopkeepers is also true of Florists and, hence, of Fred.
One way to think about how Chris has organized knowledge of Fred is in
terms of a hierarchy of categories (see Figure 1.3). Fred is a Florist, but Florist is a
specialized form of Shopkeeper. Furthermore, a Shopkeeper is also a Human; so Chris
knows, for example, that Fred is probably bipedal. A Human is a Mammal (therefore,
they nurse their young and have hair), a Mammal is an Animal (therefore, it breathes
Figure 1.3-The categories surrounding Fred
1.4 A Way of Viewing the World 1 3
Material Objects
Animal
Mammal
Plant
Flower
Carnation
Fido Fred Elizabeth Kenneth Phyl Robin’s flowers
H Figure 1.4-A class hierarchy for various material objects
oxygen), and an Animal is a Material Object (therefore, it has mass and weight). Thus,
quite a lot of knowledge that Chris has that is applicable to Fred is not directly
associated with him, or even with the category Florist.
The principle that knowledge of a more general category is also applicable
to a more specific category is called inheritance. We say that the class Florist will
inherit attributes of the class (or category) Shopkeeper.
There is an alternative graphical technique often used to illustrate this rela¬
tionship, particularly when there are many individuals with differing lineages.
This technique shows classes listed in a hierarchical treelike structure, with more
abstract classes (such as Material Object or Animal) listed near the top of the tree and
more specific classes, and finally individuals, listed near the bottom. Figure 1.4
shows this class hierarchy for Fred. This same hierarchy also includes Elizabeth;
Chris’s dog, Fido; Phyl the platypus, who lives at the zoo; and the flowers Chris
is sending to Robin. Notice that the structure and interpretation of this type of
diagram is similar to the biological hierarchy presented in Figure 1.1.
Any/information that Chris has about Fred because Fred is an instance of class
Fluman is also applicable to Elizabeth. Any information that Chris has about Fred
because Fred is a Mammal is applicable to Fido as well. Any information about
1 4 Chapter 1 □ Thinking Object-Oriented
all members of Material Object is equally applicable to Fred and to his flowers. We
capture this in the idea of inheritance.
Classes can be organized into a hierarchical inheritance structure. A child
class (or subclass) will inherit attributes from a parent class higher in the
tree. An abstract parent class is a class (such as Mammal) for which there are
no direct instances; it is used only to create subclasses.
1.4.6 Method binding and overriding
Phyl the platypus presents a problem for our simple organizing structure. Chris
knows that mammals give birth to live children, and Phyl is certainly a Mammal,
yet Phyl (or rather his mate Phyllis) lays eggs. To accommodate this, we need to
find a technique to encode exceptions to a general rule.
We do this by decreeing that information contained in a subclass can override
information inherited from a parent class. Most often, implementations of this
approach take the form of a method in a subclass having the same name as a
method in the parent class, combined with a rule for how the search for a method
to match a specific message is conducted.
The search for a method to invoke in response to a given message begins
with the class of the receiver. If no appropriate method is found, the search
is conducted in the parent class of this class. The search continues up the
parent class chain until either a method is found or the parent class chain
is exhausted. In the former case the method is executed; in the latter case,
an error message is issued. If methods with the same name can be found
higher in the class hierarchy, the method executed is said to override the
inherited behavior.
Even if a compiler cannot determine which method will be invoked at run
time, in many object-oriented languages, such as Java, it can determine whether
there will be an appropriate method and issue an error message as a compile-time
error diagnostic rather than as a run-time message.
The fact that both Elizabeth and Fred will react to Chris’s messages but use
different methods to respond is one form of polymorphism. As explained, that
Chris does not, and need not, know exactly what method Fred will use to honor
the request is an example of information hiding.
1.4.7 Summary of object-oriented concepts
Alan Kay, considered by some to be the father of object-oriented programming,
identified the following characteristics as fundamental to OOP [Kay 1993]:
1.5 Computation as Simulation 15
1. Everything is an object.
2. Computation is performed by objects communicating with each other, re¬
questing that other objects perform actions. Objects communicate by sending
and receiving messages. A message is a request for action bundled with what¬
ever arguments may be necessary to complete the task.
3. Each object has its own memory, which consists of other objects.
4. Every object is an instance of a class. A class simply represents a grouping
of similar objects, such as integers or lists.
5. The class is the repository for behavior associated with an object. That is,
all objects that are instances of the same class can perform the same actions.
6. Classes are organized into a singly rooted tree structure, called the inheri¬
tance hierarchy. Memory and behavior associated with instances of a class
are automatically available to any class associated with a descendant in this
tree structure.
*1.5 □ Computation as Simulation
The view of programming represented by the example of sending flowers to a
friend is very different from the conventional conception of a computer. The
traditional model describing the behavior of a computer executing a program
is a process-state or pigeon-hole model. In this view, the computer is a data
manager, following some pattern of instructions, wandering through memory,
pulling values out of various slots (memory addresses), transforming them in
some manner, and pushing the results back into other slots (see Figure 1.5). By
examining the values in the slots, one can determine the state of the machine or
the results produced by a computation. Although this model may be a more or
less accurate picture of what takes place inside a computer, it does little to help us
understand how to solve problems using the computer, and it is certainly not the
way most people (pigeon handlers and postal workers excepted) go about solving
problems.
In contrast, in the object-oriented framework we never mention memory
addresses, variables, assignments, or any of the conventional programming terms.
Instead, we speak of objects, messages, and responsibility for some action. I quote
Dan Ingalls’s memorable phrase.
Instead of a bit-grinding processor . . . plundering data structures, we have
a uruverse of well-behaved objects that courteously ask each other to carry
out their various desires [Ingalls 1981].
1 6 Chapter 1 □ Thinking Object-Oriented
Figure 1.5-Visualization of imperative programming.
Another author has described object-oriented programming as “animistic”:
a process of creating a host of helpers that form a community and assist the
programmer in the solution of a problem [Actor 1987].
This view of programming as creating a “universe” is in many ways similar
to a style of computer simulation called “discrete event-driven simulation.” In
brief, in a discrete event-driven simulation the user creates computer models of
the various elements of the simulation, describes how they will interact with one
another, and sets them moving. This is almost identical to the average object-
oriented program, in which the user describes what the various entities in the
universe for the program are and how they will interact with one another, and
then finally sets them in motion. Thus, in object-oriented programming, we have
the view that computation is simulation [Kay 1977].
1.5.1 The power of metaphor
An easily overlooked benefit to the use of object-oriented techniques is the power
of metaphor. When programmers think about problems in terms of behaviors
and responsibilities of objects, they bring with them a wealth of intuition, ideas,
and understanding from their everyday experiences. When envisioned as pigeon
holes, mailboxes, or slots containing values, there is little in the programmer’s
background to provide insight into how problems should be structured.
Although anthropomorphic descriptions such as the quote by Ingalls may
strike some people as odd, in fact they are a reflection of the great expositive power
of metaphor. Journalists make use of metaphor every day, as in this description
of object-oriented programming from Newsweek (Figure 1.6).
Unlike the usual programming method—writing software one line at a
time—NeXT’s “object-oriented” system offers larger building blocks that
1.5 Computation as Simulation 17
0 Figure 1.6-Mr. Potato Head, an object-oriented toy (Hasbro, Inc.)
developers can quickly assemble the way a kid builds faces on Mr. Potato
Head.
Possibly this feature, more than any other, is responsible for the frequent obser¬
vation that it is sometimes easier to teach object-oriented programming concepts
to computer novices than to computer professionals. Novice users quickly adapt
the metaphors with which they are already comfortable from their everyday life,
whereas seasoned computer professionals can be blinded by an adherence to more
traditional ways of viewing computation.
1.5.2 Avoiding infinite regression
Of course, objects cannot always respond to a message by politely asking another
object to perform some action. The result would be an infinite circle of requests,
like two gentlemen politely waiting for the other to go first before entering a
doorway, or like a bureaucracy of paper pushers, each passing on all papers to
some other member of the organization. At some point, at least a few objects need
to perfqrm some work besides passing on requests to other agents. This work is
accomplished differently in various object-oriented languages.
1 8 Chapter 1 h Thinking Object-Oriented
In blended object-oriented/imperative languages, such as C++, Object Pascal,
and Objective-C, it is accomplished by methods written in the base (non-object-
oriented) language. In more purely object-oriented languages, such as Smalltalk or
Java, it is accomplished by “primitive” or “native” operations that are provided
by the underlying system.
* 1.6 □ A Brief History
It is commonly thought that object-oriented programming is a relatively recent
phenomenon in computer science. To the contrary, in fact, almost all the major
concepts we now associate with object-oriented programs, such as objects, classes,
and inheritance hierarchies, were developed in the 1960s as part of a language
called Simula, designed by researchers at the Norwegian Computing Center.
Simula, as the name suggests, was a language inspired by problems involving
the simulation of real life systems. However, the importance of these constructs,
even to the developers of Simula, was only slowly recognized [Nygaard 1981].
In the 1970s Alan Kay organized a research group at Xerox PARC (the Palo
Alto Research Center). With great prescience, Kay predicated the coming revo¬
lution in personal computing that was to develop nearly a decade later (see, for
example, his 1977 article in Scientific American [Kay 1977]). Kay was concerned
with discovering a programming language that would be understandable to non¬
computer professionals, to ordinary people with no prior training in computer
use.^ He found in the notion of classes and computing as simulation a metaphor
that could easily be understood by novice users, as he then demonstrated by a
series of experiments conducted at PARC using children as programmers. The
programming language developed by his group was named Smalltalk. This lan¬
guage evolved through several revisions during the decade. A widely read 1981
issue of Byte magazine did much to popularize the concepts developed by Kay
and his team at Xerox.
Roughly contemporaneous with Kay’s work was another project being con¬
ducted on the other side of the country. Bjarne Stroustrup, a researcher at Bell
Laboratories who had learned Simula while completing his doctorate at Cam¬
bridge University in England, was developing an extension to the C language that
would facilitate the creation of objects and classes [Stroustrup 1982]. This was
to eventually evolve into the language C++ [Stroustrup 1994].
1. I have always found it ironic that Kay missed an important point. He thought that to use
a computer one would be required to program a computer. Although he correctly predicted in
1977 the coming trend in hardware, few could have predicted at that time the rapid development
of general purpose computer applications that was to accompany, perhaps even drive, the
introduction of personal computers. Nowadays the vast majority of people who use personal
computers have no idea how to program.
Discovering Diverse Content Through
Random Scribd Documents
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
The Project Gutenberg eBook of The Adventurers
This ebook is for the use of anyone anywhere in the United States and
most other parts of the world at no cost and with almost no restrictions
whatsoever. You may copy it, give it away or re-use it under the terms
of the Project Gutenberg License included with this ebook or online at
www.gutenberg.org. If you are not located in the United States, you will
have to check the laws of the country where you are located before
using this eBook.
Title: The Adventurers
Author: Gustave Aimard
Translator: Sir Lascelles Wraxall
Release date: September 14, 2013 [eBook #43716]
Most recently updated: October 23, 2024
Language: English
Credits: Produced by Marc D'Hooghe
*** START OF THE PROJECT GUTENBERG EBOOK THE ADVENTURERS
***
THE ADVENTURERS
A Story of a Love-Chase
BY
GUSTAVE AIMARD
AUTHOR OF
"LAST OF THE INCAS," "QUEEN OF THE SAVANNAH,"
ETC.
LONDON
WARD AND LOCK, 158, FLEET STREET.
1863.
PREFACE.
With the publication of the present and the ensuing volume, "The Pearl
of the Andes," I am enabled to perfect the most important series of
Aimard's Tales of Indian Life and Adventure. To preserve uniformity, the
volumes of this series should be arranged in the following order on the
book-shelf;—
1. THE ADVENTURERS.
2. THE PEARL OF THE ANDES.
3. THE TRAIL-HUNTER.
4. PIRATES OF THE PRAIRIES.
5. THE TRAPPER'S BRIDE.
6. THE TIGER SLAYER.
7. THE GOLD SEEKERS.
8. THE INDIAN CHIEF.
9. THE RED TRACK.
Gustave Aimard has a precedent in Fenimore Cooper for introducing the
same hero in a long range of volumes, and, like his great predecessor,
he has so arranged, that each work should be complete in itself, and not
necessitate the purchase of another. But Aimard has one marked
advantage over Cooper; for while "Leather-Stocking" is but a creation of
the fancy, or, at the most, the type of the Backwoodsman, the Count
Louis who figures as the hero of Aimard's series, is a real man. Count de
Raousset Boulbon, had he succeeded in his daring attempt of founding
an independent kingdom in Mexico, would in all probability have become
the Napoleon of the West. A gallant adventurer and thorough
gentleman, he staked his life upon the issue, and ended his career the
victim of unparalleled treachery, as Aimard has faithfully recorded.
Hence Aimard's romances have the great merit of being founded on an
historic basis, and but little fiction was required to heighten the startling
interest of the narrative.
Valentine Guillois, there is very little doubt, is intended for the Author
himself, with all his qualities and defects. When he first reached the New
World, he was the true, reckless Parisian; but constant intercourse with
nature rendered him a generous and thoughtful friend of humanity. So
soon as he returned to civilization, he began recording the history of his
past life; not so much as a livelihood, as for the pleasure he felt in living
once again the life of excitement and adventure which he had known
among the Indians. Hence his books are written without an effort; they
flow spontaneously from his pen; and the absence of artistic effect is the
best guarantee of their truthfulness.
It is not surprising, consequently, that M. Aimard's books have met with
such extensive popularity. They have been translated into nearly every
modern language, and the Author is now generally recognised as the
French Cooper. The reception given to his stories in this country has
been most flattering, and each day heightens their popularity. Hence it is
not too much to assume that they will become standard works,
especially with young readers, for whom they are especially adapted;
because M. Aimard has never yet written a line which could prove
offensive to the most delicate mind.
L
.W.
CONTENTS.
I.THE CHAPARRAL
II.THE FOSTER BROTHERS
III.THE RESOLUTION
IV.THE EXECUTION
V.THE PASSAGE
VI.THE LINDA
VII.HUSBAND AND WIFE
VIII.THE DARK-HEARTS
IX.IN THE STREET
X.SWORD-THRUSTS
XI.GENERAL BUSTAMENTE
XII.THE SPY
XIII.LOVE
XIV.THE QUINTA VERDE
XV.THE DEPARTURE
XVI.THE MEETING
XVII.THE PUELCHES
XVIII.THE BLACK JACKAL
XIX.TWO OLD FRIENDS
XX.THE SORCERER
XXI.THE OBSEQUIES OF AN APO-ULMEN
XXII.EXPLANATIONS
XXIII.THE CHINGANA
XXIV.THE TWO ULMENS
XXV.THE SUN-TIGER
XXVI.THE MATRICIDE
XXVII.THE JUSTICE OF THE DARK-HEARTS
XXVIII.THE TREATY OF PEACE
XXIX.THE ABDUCTION
XXX.THE PROTEST
XXXI.SPANIARD AND INDIAN
XXXII.IN THE MOUNTAIN
XXXIII.ON THE WATCH
XXXIV.FACE TO FACE
XXXV.THE REVOLT
XXXVI.THE LION AT BAY
XXXVII.THE TRUCE
XXXVIII.TWO ROGUISH PROFILES
XXXIX.THE WOUNDED MAN
XL.ARAUCANIAN DIPLOMACY
XLI.THE COUNCIL
XLII.THE NIGHT JOURNEY
XLIII.TWO HATREDS
XLIV.THE RETURN TO VALDIVIA
XLV.THE FATHER REVEALS HIMSELF
XLVI.CURUMILLA
CHAPTER I.
THE CHAPARRAL.
During my last sojourn in America, chance, or rather my good star, led
me to form an acquaintance with one of those hunters, or wood
rangers, the type of whom has been immortalized by Cooper, in his
poetical personage, Leather-Stockings.
The strange circumstance by which we were brought together was as
follows. Towards the end of July, 1855, I had left Galveston, terrified at
the fevers prevalent there, which are so fatal to Europeans, with the
intention of visiting the north-west portion of Texas, a country I was
then unacquainted with.
A Spanish proverb somewhere says, "It is better to go alone than in bad
company;" and, like all other proverbs, this possesses a certain
foundation of truth, particularly in America, where the traveller is
exposed at each instant to the chance of meeting rogues of every hue,
who, thanks to their seducing exterior, charm him, win his confidence,
and take advantage of the first occasion to remorselessly plunder and
assassinate him.
I had profited by the proverb, and, like a shrewd old traveller of the
prairies, as I knew no one who inspired me with sufficient sympathy to
lead me to make him my travelling companion, I had bravely set out
alone, clothed in the picturesque dress of the inhabitants of the country,
armed to the teeth, and mounted upon an excellent half wild horse,
which had cost me twenty-five piastres—an enormous sum in those
countries, where horses are considered as worth little or nothing.
I carelessly wandered here and there, living that nomadic life which is so
full of attractions; at times stopping at a toldería, at others encamping in
the desert, hunting wild animals, and plunging deeper and deeper into
unknown regions. I had, in this fashion, passed through, without any
untoward accident, Fredericksburgh, the Llana Braunfels, and had just
left Castroville, on my way to Quichi. Like all Spanish-American villages,
Castroville is nothing but a miserable agglomeration of ruined cabins,
cut at right angles by streets choked with weeds, growing undisturbed,
and concealing multitudes of ants, reptiles, and even rabbits of a very
small breed, which spring up beneath the feet of the few passengers.
The pueblo is bounded on the west by the Medina, a slender thread of
water, almost dry in the great heat seasons; and on the east by thickly-
wooded hills, the dark green of which forms a pleasing contrast with the
pale blue of the sky.
At Galveston I had undertaken to deliver a letter to an inhabitant of
Castroville. The worthy man lived in this village like La Fontaine's rat in
the depths of its Dutch cheese. Charmed by the arrival of a stranger,
who, no doubt, brought him news for which he had been long anxious,
he received me in the most cordial manner, and thought of every
expedient to detain me. Unfortunately, the little I had seen of Castroville
had sufficed to completely disgust me with it, and my only wish was to
get out of it as quickly as possible. My host, in despair at seeing all his
advances repulsed, at length consented to allow me to continue my
journey.
"Adieu, then," he said, warmly pressing my hand, with a sigh of regret;
"since you are determined to go, may God protect you! You are wrong in
setting out so late; the road you have to travel is dangerous; the Indios
bravos are up; they assassinate without mercy all the whites who fall
into their hands—beware!"
I smiled at this warning, which I took for a last effort of the worthy man
to detain me.
"Bah!" I replied gaily; "the Indians and I are too old acquaintances for
me to fear anything on their account."
My host shook his head sorrowfully, and retreated into his hut, making
me a last farewell greeting. I again set forward. I soon began to reflect
that it was full late, and pressed my horse, in order to pass, before
nightfall, a chaparral, or large thicket of underwood, of at least two
miles in length, against which my host had particularly warned me. This
ill-famed spot had a very sinister aspect. The mezquite, the acacia, and
the cactus constituted its sole vegetation, while here and there,
whitened bones and planted crosses plainly designated places where
murders had been committed. Beyond that extended a vast plain, called
the Leona, peopled by animals of every description. This plain, covered
by grass at least two feet in height, was dotted at intervals with thickets
of trees, upon which warbled thousands of golden-throated starlings,
cardinals, and bluebirds. I was anxious to reach the Leona, which I saw
in the distance; but ere I did so, I had to cross the chaparral. After
examining my weapons, and looking carefully in all directions, as I could
perceive nothing positively suspicious, I resolutely spurred my horse
forward, determined, if attacked, to sell my life as dearly as possible.
The sun, in the meantime, was sinking rapidly towards the horizon, the
ruddy hues of closing day tinged with their changing reflections the
summits of the wooded hills, and a fresh breeze agitated the branches
of the trees with mysterious murmurs. In this country, where there is no
twilight, night was not long in enveloping me in thick darkness, and that
before I had passed through two-thirds of the chaparral.
I was beginning to hope I should reach the Leona safe and sound,
when, all at once, my horse made a violent bound on one side, pricking
up its ears, and snorting loudly. The sudden shock almost threw me out
of the saddle, and it was not without trouble that I recovered the
mastery over my horse, which displayed signs of the greatest terror. As
always happens in such cases, I instinctively looked round me for the
cause of this panic; and soon the truth was revealed to me. A cold
perspiration bedewed my brow, and a shudder of terror ran through my
whole frame, at the horrible spectacle which met my eyes. Five dead
human bodies lay stretched beneath the trees, within ten paces of me.
Among them was one of a woman, and one of a girl about fourteen
years of age. They all belonged to the white race. They appeared to
have fought long and obstinately before they fell; they were literally
covered with wounds; and long arrows, with jagged barbs, and painted
red, stood out from the bodies, which they had pierced through and
through. The victims had all been scalped. It was evidently the work of
Indians, marked with their sanguinary rage, and their inveterate hatred
for the white race. The form and colour of the arrows told me that the
perpetrators of this atrocity were the Apaches, the most cruel plunderers
of the desert. Around the bodies I observed fragments of both wagons
and furniture. The unfortunate beings, assassinated with refined cruelty,
had, no doubt, been poor emigrants on their way to Castroville.
At the aspect of this heartbreaking spectacle, I cannot express the pity
and grief which weighed upon my spirits; high in the air, urubus and
vultures hovered with lazy wings over the bodies, uttering lugubrious
cries of joy, whilst in the depths of the chaparral the wolves and jaguars
began to growl portentously.
I cast a melancholy glance around: all immediately near to me was
quiet. The Apaches had, according to all appearances, surprised the
emigrants during a halt. Gutted bales were still ranged in a symmetrical
circle, and a fire, near which was a heap of dry wood, was not yet
extinguished.
"No!" said I to myself, "whatever may happen, I will not leave Christians
without burial, to become, in this desert, the prey of wild beasts."
My resolution, once formed, was soon carried into execution. Springing
to the ground, I hobbled my horse, gave it some provender, and cast
some branches of wood upon the fire, which soon sparkled and sent into
the air a column of bright flame. Among the necessaries of the
emigrants were spades, pickaxes, and other agricultural instruments,
which, being of no use to the Indians, they had disdainfully left behind
them. I seized a spade, and, after having carefully explored the environs
of my encampment, to assure myself that no immediate danger need be
apprehended, I set to work to dig a grave.
The night had now set in; one of those American nights, clear, silent, full
of intoxicating odours, and mysterious melodies chanted by the desert in
praise of God. Extraordinary to say, all my fears had vanished, as if by
enchantment! Though alone in this sinister place, close to these
frightfully-mutilated carcasses, watched in the darkness, no doubt, by
the unseen eyes of wild beasts, and, perhaps, of the murderous Indians,
some incomprehensible influence sustained me, and gave me strength
to accomplish the rude but sacred task I had undertaken. Instead of
thinking of the dangers which surrounded me, I found myself yielding to
a pensive melancholy. I thought of these poor people, who had come
from distant lands, full of hope for the future, to seek in the New World
a little of the comfort and well-being which were denied to them at
home, and who, scarcely landed, had fallen, in an obscure corner of the
desert, by the hands of ferocious savages. They had left in their own
country friends, perhaps relations, to whom their fate would for ever
remain a mystery, and who would for years reckon the hours with
anxiety, looking for their much-wished return, or for intelligence of their
success in their bold undertaking.
Except two or three alarms caused by the rustling of the leaves in the
bushes, nothing occurred to interrupt my melancholy duty. In less than
three-quarters of an hour I had dug a grave large enough to contain the
five bodies. After extracting the arrows by which they were transfixed, I
raised them one after the other in my arms, and laid them gently side
by side at the bottom of the grave. I then hastened to throw in the
mould again, till it was level with the sod; and that being done, I
dragged upon the surface all the large stones I could find, to keep wild
beasts from profaning the dead. This religious duty accomplished, I
breathed a deep sigh of satisfaction, and bowing my head towards the
ground, I mentally addressed a short prayer to the Almighty, for the
unfortunate beings I had buried.
Upon raising my head, I uttered a cry of surprise and terror, while at the
same time mechanically feeling for my revolver; for, without the least
noise having given me warning of his approach, a man was standing
within four paces of me, watching me earnestly, and leaning on his long
rifle. Two magnificent Newfoundland dogs were lying carelessly but
quietly at his feet. On observing my gesture, the unknown smiled with a
kindly expression, and holding out his hand to me over the grave, said—
"Fear nothing! I am a friend. You have buried these poor people; I have
avenged them—their assassins are dead!"
I silently pressed the hand that was so frankly extended to me.
Acquaintance was formed—we were friends—we are so still! A few
minutes later we were seated near the fire, supping together with a
good appetite, while the dogs kept watch against intruders.
The companion I had fallen in with in so curious a manner was a man of
about forty-five years of age, although he did not appear to be more
than thirty-two. He was tall and well made; his broad shoulders and
muscular limbs denoting extraordinary strength and agility. He wore the
picturesque hunter's costume in all its purity, that is to say, the capote,
or surtout (which is nothing but a kind of blanket worn as a robe,
fastened to the shoulders, and falling in long folds behind), a shirt of
striped cotton, large mitasses (drawers of doeskin, stitched with hair,
fastened at distances, and ornamented with little bells), leather gaiters,
moccasins of elk skin, braided with beads and porcupine quills, and a
checked woollen belt, from which hung his knife, tobacco pouch, powder
horn, pistols, and medicine bag. His headdress consisted of a cap made
of the skin of a beaver, the tail of which fell between his shoulders. This
man was a type of a hardy race of adventurers who traverse America in
all directions. A primitive race, longing for open air, space, and liberty,
opposed to our ideas of civilization, and consequently destined to
disappear before the immigration of the laborious races, whose powerful
agents of conquest are steam and the application of mechanical
inventions of all kinds.
This hunter was a Frenchman, and his frank, manly countenance, his
picturesque language, his open and engaging manners, notwithstanding
his long abode in America, had preserved a reflex of the mother country
which awakened sympathy and created interest.
All the countries of the New World were familiar to him; he had lived
more than twenty years in the depths of the woods, and had been
engaged in dangerous and distant excursions among the Indian tribes.
Hence, although myself well initiated in the customs of the redskins, and
though a great part of my existence had been passed in the desert, I
have felt myself often shudder involuntarily at the recital of his
adventures. When seated beside him on the banks of the Rio Gila,
during an excursion we had undertaken into the prairies, he would at
times allow himself to be carried away by his remembrances, and relate
to me, as he smoked his Indian pipe, the strange history of the early
days of his abode in the New World. It is one of these recitals I am
about to lay before my readers—the first in order of date, since it is the
history of the events which led him to become a wood ranger. I do not
venture to hope that my readers will take the interest in it which it
excited in me; but I beg them to have the kindness to recollect that this
narrative was told me in the desert, amidst that grand, vast, and
powerful nature, unknown to the inhabitants of old Europe, and that I
had it from the lips of the man who had been the hero.
CHAPTER II.
THE FOSTER BROTHERS.
On the 31st of December, 1834, at eleven o'clock in the evening, a man
of about twenty-five years of age, of handsome person and
countenance, and aristocratic appearance, was sitting, or rather
reclining, in a luxurious easy chair, near the mantelpiece, within which
sparkled a fire that the advanced season rendered indispensable. This
personage was the Count Maxime Edouard Louis de Prébois-Crancé. His
countenance, of a cadaverous paleness, formed a striking contrast with
his black curly hair, which fell in disorder upon his shoulders, covered by
a large-patterned damask dressing gown. His brows were contracted,
and his eyes were fixed with feverish impatience upon the dial of a
charming Louis Quinze clock, whilst his left hand, hanging carelessly by
his side, played with the silky ears of a magnificent Newfoundland dog
which lay by his side. The room in which the Count was sitting was
furnished with all the refinement of comfort invented by modern luxury.
A four-branched chandelier, with rose-coloured wax candles, placed
upon a table, was scarcely sufficient to enliven the room, and only
spread around a dim, uncertain light. Without, the rain was dashing
against the windows violently; and the wind sighed in mysterious
murmurs, which disposed the mind to melancholy. When the clock
struck the hour the Count started up, as if aroused from a dream. He
passed his thin white hand across his moist brow, and said, in a
dissatisfied tone—
"He will not come!"
But at that moment the dog, which had been so motionless, sprang up
and bounded towards the door, wagging its tail with joy. The door
opened, the portière was lifted by a firm hand, and a man appeared.
"Here you are at last!" the Count exclaimed, advancing towards the
newcomer, who had great trouble to get rid of the caresses of the dog.
"I had begun to be afraid that you, like the rest, had forgotten me."
"I do not understand you, brother, but trust you will explain yourself,"
the other replied. "Come, that will do, Cæsar; lie down! you are a very
good dog, but lie down!"
And drawing an easy chair towards the fire, he sat down at the other
side of the fire, in front of the Count, who had resumed his place. The
dog lay down between them.
The personage so anxiously expected by the Count formed a strange
contrast with him; for, just as M. de Prébois-Crancé united in himself all
the qualities which physically distinguish nobility of race, the other
displayed all the lively, energetic strength of a true child of the people.
He was a man of twenty-six years of age; tall, thin, and perfectly well
proportioned; while his face, bronzed by the sun, and his marked
features, lit up by blue eyes sparkling with intelligence, wore an
expression of bravery, mildness, and loyalty of character that created
sympathy at first sight. He was dressed in the elegant uniform of a
quartermaster sergeant of the Spahis, and the cross of the legion of
honour glittered on his breast. With his head leaning on his right hand, a
pensive brow and a thoughtful eye, he examined his friend attentively,
whilst twisting his long, silky light-coloured moustache with the other
hand.
The Count, shrinking before his earnest look, which appeared trying to
read his most secret thoughts, broke the silence abruptly.
"You have been a long time in responding to my message," he said.
"This is the second time you have addressed that reproach to me,
Louis," the soldier replied, taking a paper from his breast; "you forget
the terms of the note which your groom brought yesterday to my
quarters."
And he was preparing to read.
"It is useless to read it," said the Count, with a melancholy smile. "I
acknowledge I am in the wrong."
"Well, then, let us see," said the Spahi gaily, "what this serious affair is
which makes you stand in need of me. Explain: is there a woman to be
carried off?—Have you a duel on hand?—Tell me."
"Nothing that you can possibly imagine," the Count interrupted him
bitterly; "therefore do not waste time in useless surmises."
"What the devil is it, then?"
"I am going to blow out my brains."
The young man uttered these words with so firm and resolute an
accent, that the soldier started in spite of himself, and bent an anxious
glance upon the speaker.
"You believe me mad, do you not?" the Count continued, who guessed
his friend's thoughts. "No, I am not mad, Valentine; I am only at the
bottom of an abyss from which I can only escape by death or infamy,
and I prefer death."
The soldier made no reply. With an energetic gesture he pushed back
his chair, and began to walk about the room with hurried steps. The
Count had allowed his head to sink upon his breast in a state of perfect
prostration of mind. After a long silence, during which the fury of the
storm without increased, Valentine resumed his seat.
"A very strong reason must have obliged you to take such a
determination," he said coolly; "I will not endeavour to combat it; but I
command you, by our friendship, to tell me fully what has led you to
form it. I am your foster brother, Louis; we have grown up together; our
ideas have been too long in common, our friendship is too strong and
too fervent for you to refuse to satisfy me."
"To what purpose?" cried the Count, impatiently; "my sorrows are of a
nature which none but he who experiences them can comprehend."
"A bad pretext, brother," replied the soldier, in a rough tone; "the
sorrows we dare not avow are of a kind that make us blush."
"Valentine," said the Count, with a flashing eye, "it is ill judged to speak
so."
"On the contrary, it is quite right," replied the young man, warmly. "I
love you, I owe you the truth; why should I deceive you? No, you know
my frankness; therefore do not hope that I shall listen to you with my
eyes shut. If you want to be flattered in your last moments, why send
for me? Is it to applaud your death? If so, brother, farewell! I will retire,
for I have nothing to do here. You great gentlemen, who have only
known the trouble of coming into the world, know nothing of life but its
joys; at the first roseleaf which chance happens to ruffle in your bed of
happiness, you think yourselves lost, and appeal to that greatest of all
cowardices, suicide."
"Valentine!" the Count cried angrily.
"Yes," continued the young man, with increased energy, "I repeat, that
supreme cowardice! Man is no more at liberty to quit life when he
fancies he is tired of it, than the soldier is to quit his post when he
comes face to face with his country's enemy. Your sorrows, indeed! I
know well what they are."
"You know?" demanded the Count with astonishment.
"All—listen to me; and when I have told you my thoughts, why, kill
yourself if you like. Pardieu! do you think when I came here I did not
know why you summoned me? A gladiator, far too weak to fight the
good fight, you have cast yourself defencelessly among the wild beasts
of this terrible arena called Paris—and you have fallen, as was sure to be
the case. But remember, the death you contemplate will complete your
dishonour in the eyes of all, instead of reinstating you or surrounding
you with the halo of false glory you are ambitious of."
"Valentine! Valentine!" cried the Count, striking the table forcibly with his
clenched hand, "what gives you a right to speak to me thus?"
"My friendship," the soldier replied, energetically, "and the position you
have yourself placed me in by sending for me. Two causes reduce you to
despair. These two causes are, in the first place, your love for a
coquettish woman, a Creole, who has played with your heart as the
panther of her own savannahs plays with the inoffensive animals she is
preparing to devour.—Is that true?"
The young man made no reply. With his elbows on the table, his face
buried in his hands, he remained motionless, apparently insensible to
the reproaches of his foster brother. Valentine continued—
"Secondly, when, in order to win favour in her eyes, you have
compromised your fortune, and squandered all that your father had left
you, this woman flits away as she came, rejoicing over the mischief she
has done, over the victims she has left on the path she has trod, leaving
to you and to so many others the despair and the shame of having been
the sport of a coquette. What urges you to seek refuge in death is not
the loss of fortune, but the impossibility of following this woman, the
sole cause of all your misfortunes. I defy you to contradict me."
"Well, I admit all that is true. It is that alone which kills me. What care I
for the loss of fortune? She alone is the object of my ambition! I love
her—I love her—I tell you, so that I could struggle against the whole
world to obtain her!" the young man exclaimed with great excitement.
"Oh, if I could but hope! Hope—a word void of meaning, invented by the
ambitious, always implying something unattainable! Do you not plainly
see the truth of what I say? There is nothing left me but to die!"
Valentine contemplated him for some minutes with a sad countenance.
Suddenly his brow cleared, his eye sparkled; he laid his hand upon the
Count's shoulder.
"Is this, then, more than a caprice? Do you really love this woman?" he
said.
"Have I not told you that I am ready to die for her?"
"Ay; and you told me at the same time that you would struggle with the
whole world to obtain her."
"I did—and would."
"Well, then," continued Valentine, fixing his eyes earnestly upon him, "I
can help you to find this woman again—I can."
"You can?"
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Programming and problem solving with c++, 3rd edition
PDF
(Data structures) programming and problem solving
PDF
A Strong Object Recognition Using Lbp, Ltp And Rlbp
PDF
C# and java comparing programming languages
PDF
Computer Science Is The Study Of Principals And How The...
DOCX
A Survey of Object Oriented Programming LanguagesMaya Hris.docx
PDF
Java Java Java Objectoriented Problem Solving 3rd Edition Ralph Morelli Ralph...
PDF
History Of C Essay
Programming and problem solving with c++, 3rd edition
(Data structures) programming and problem solving
A Strong Object Recognition Using Lbp, Ltp And Rlbp
C# and java comparing programming languages
Computer Science Is The Study Of Principals And How The...
A Survey of Object Oriented Programming LanguagesMaya Hris.docx
Java Java Java Objectoriented Problem Solving 3rd Edition Ralph Morelli Ralph...
History Of C Essay

Similar to Introduction To Objectoriented Programming An 3rd Edition Timothy Budd (20)

PDF
Java Fundamentals Of Computer Science Using Java
PDF
The Concept Of Abstract Data Types
PDF
Object oriented-programming-in-c-sharp
PDF
Net 40 Generics Beginners Guide Sudipta Mukherjee
PDF
Key Features Of The Pseudo Code
PDF
event driven programing course for all.pdf
PDF
Evolution Of Object Oriented Technology
PDF
The Four Principles Of Object Oriented Programming
PPTX
How to become a software developer
PDF
Fluent C: Principles, Practices, and Patterns 1st Edition Christopher Preschern
PDF
Unit 4 Assignment 1 Comparative Study Of Programming...
PDF
Programming Scala 3rd Edition Dean Wampler Dean Wampler
PDF
C tutorial
PDF
with C++ seventh Edition.pdf by walter Savitch
PDF
A Complete Guide to Programming in C 1st Edition Ulla Kirch-Prinz
PDF
vbaintro.pdf
PDF
Modern C For Software Developers Serious C Development 13 Karen Singh Garewal
PPT
Java for C++ programers
PDF
Modern TypeScript 1 / converted Edition Ben Beattie-Hood
PDF
Object And Oriented Programing ( Oop ) Languages
Java Fundamentals Of Computer Science Using Java
The Concept Of Abstract Data Types
Object oriented-programming-in-c-sharp
Net 40 Generics Beginners Guide Sudipta Mukherjee
Key Features Of The Pseudo Code
event driven programing course for all.pdf
Evolution Of Object Oriented Technology
The Four Principles Of Object Oriented Programming
How to become a software developer
Fluent C: Principles, Practices, and Patterns 1st Edition Christopher Preschern
Unit 4 Assignment 1 Comparative Study Of Programming...
Programming Scala 3rd Edition Dean Wampler Dean Wampler
C tutorial
with C++ seventh Edition.pdf by walter Savitch
A Complete Guide to Programming in C 1st Edition Ulla Kirch-Prinz
vbaintro.pdf
Modern C For Software Developers Serious C Development 13 Karen Singh Garewal
Java for C++ programers
Modern TypeScript 1 / converted Edition Ben Beattie-Hood
Object And Oriented Programing ( Oop ) Languages
Ad

Recently uploaded (20)

PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
Lesson notes of climatology university.
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Classroom Observation Tools for Teachers
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Complications of Minimal Access Surgery at WLH
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
GDM (1) (1).pptx small presentation for students
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Presentation on HIE in infants and its manifestations
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Chinmaya Tiranga quiz Grand Finale.pdf
Final Presentation General Medicine 03-08-2024.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
RMMM.pdf make it easy to upload and study
Lesson notes of climatology university.
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Classroom Observation Tools for Teachers
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Complications of Minimal Access Surgery at WLH
Abdominal Access Techniques with Prof. Dr. R K Mishra
GDM (1) (1).pptx small presentation for students
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Presentation on HIE in infants and its manifestations
O5-L3 Freight Transport Ops (International) V1.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Pharmacology of Heart Failure /Pharmacotherapy of CHF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Ad

Introduction To Objectoriented Programming An 3rd Edition Timothy Budd

  • 1. Introduction To Objectoriented Programming An 3rd Edition Timothy Budd download https://ebookbell.com/product/introduction-to-objectoriented- programming-an-3rd-edition-timothy-budd-33057832 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Introduction To Objectoriented Programming In Python Building Flexible And Reusable Code 2nd Edition 2nd Edition Amir Keivan Shafiei https://ebookbell.com/product/introduction-to-objectoriented- programming-in-python-building-flexible-and-reusable-code-2nd- edition-2nd-edition-amir-keivan-shafiei-57761774 An Introduction To Objectoriented Programming With Visual Basic Net 1st Edition Dan Clark https://ebookbell.com/product/an-introduction-to-objectoriented- programming-with-visual-basic-net-1st-edition-dan-clark-55132358 An Introduction To Objectoriented Programming With Java 5th Edition C Thomas Wu https://ebookbell.com/product/an-introduction-to-objectoriented- programming-with-java-5th-edition-c-thomas-wu-2377364 An Introduction To Objectoriented Programming In C With Applications In Computer Graphics 2nd Edition Graham M Seed Beng https://ebookbell.com/product/an-introduction-to-objectoriented- programming-in-c-with-applications-in-computer-graphics-2nd-edition- graham-m-seed-beng-4198618
  • 3. Microsoft Visual C 2010 An Introduction To Objectoriented Programming 4th Edition 4th Joyce Farrell https://ebookbell.com/product/microsoft-visual-c-2010-an-introduction- to-objectoriented-programming-4th-edition-4th-joyce-farrell-2338860 Beginning C 30 An Introduction To Object Oriented Programming 1st Edition Jack Purdum https://ebookbell.com/product/beginning-c-30-an-introduction-to- object-oriented-programming-1st-edition-jack-purdum-2514132 Microsoft Visual C 2017 An Introduction To Objectoriented Programming 7th Edition Joyce Farrell https://ebookbell.com/product/microsoft-visual-c-2017-an-introduction- to-objectoriented-programming-7th-edition-joyce-farrell-10539110 Applying Uml And Patterns An Introduction To Object Oriented Programming 2ed Larmen https://ebookbell.com/product/applying-uml-and-patterns-an- introduction-to-object-oriented-programming-2ed-larmen-1278786 Introduction To Programming With Greenfoot Objectoriented Programming In Java With Games And Simulations Klling https://ebookbell.com/product/introduction-to-programming-with- greenfoot-objectoriented-programming-in-java-with-games-and- simulations-klling-21995800
  • 6. TRENT UNIVERSITY ALUMNI BOOK FUND This book is a gift of THE ALUMNI BOOK FUND as part of the Book Fund of the Trent University Alumni Association Presented on October 20 to The Thomas J. Bata Library Trent University, Peterborough, Canada.
  • 9. Third Edition An Introduction to Object-Oriented Programming
  • 10. Digitized by the Internet Archive in 2019 with funding from Kahle/Austin Foundation https://archive.0rg/details/introductiontoobOOOObudd
  • 11. Third Edition An Introduction to Object-Oriented Programming '(( ^ Timothy A. Budd- Oregon State University Thomas J. Bata Library TRENT UNIVERSi i Y PETERBOROUGH, ONTARIO Boston San Francisco New York London Toronto Sydney Tokyo Singapore Madrid Mexico City Munich Paris Cape Town Hong Kong Montreal
  • 12. Executive Editor: Susan Hartman Sullivan Associate Editor: Elinor Actipis Executive Marketing Manager: Michael Hirsch Production Supervisor: Diane Freed Composition: Windfall Software, using ZzTgX Copyeditor: Debbie Prato Technical Art: LM Graphics Proofreader: Brooke Albright Text Design: Windfall Software Cover Designer: Gina Hagen Kolenda Cover Illustration: Susan Cyr Design Manager: Gina Hagen Prepress and Manufacturing: Caroline Fell Access the latest information about Addison-Wesley titles from our World Wide Web site: www.aw.com/cs Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison- Wesley was aware of a trademark claim, the designations have been printed in initial caps or all caps. The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications. Fibrary of Congress Cataloging-in-Publication Data Budd, Timothy. An introduction to object-oriented programming / Timothy A. Budd.—3rd ed. p. cm. Includes index. ISBN 0-201-76031-2(pbk.) 1. Object-oriented programming (Computer science) I. Title. QA76.64B83 2002 005.1T7-dc21 2001045060 CIP Copyright © 2002 by by Pearson Education, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. 123456789 10—HP—04030201
  • 13. Preface When I began writing my first book on Smalltalk in 1983, I distinctly remember thinking that I must write quickly so as to not miss the crest of the object-oriented programming wave. Who would have thought that two decades later object- oriented programming would still be going strong? And what a long, strange trip it has been. In the two decades that object-oriented programming has been studied, it has become the dominant programming paradigm. In the process, it has changed almost every facet of computer science. And yet I find that my goal for the third edition of this book has remained unchanged from the first. It is still my hope to impart to my students and, by extension, my readers an understanding of object-oriented programming based on general principles and not specific to any particular language. Languages come and go in this field with dizzying rapidity. In the first edi¬ tion I discussed Objective-C and Apple’s version of Object Pascal, both widely used at that time. Although both languages still exist, neither can at present be considered a dominant language. (However, I talk about Objective-C in the third edition because from a language point of view it has many interesting and unique features.) Between the first edition and the third many languages seem to have disappeared (such as Actor and Turing), while others have come into existence (such as Java, Eiffel, and Self). Many existing languages have acquired object ex¬ tensions (such as Common Lisp and Object Perl), and many have burst onto the scene for a short while and then just as suddenly disappeared (for example, Sather and Dylan). Then there is Beta, a language that hints at wonderful ideas behind an incomprehensible syntax. Prediction is difficult, particularly about the future. Will languages that are just now appearing, such as Ruby, have staying power, or will they go the way of Dylan? What about C#? It is difficult to imagine that any language with Microsoft behind it will fail to be successful, but stranger things have happened. (Personally, I think that C# will last because it presents a route for Visual Basic programmers to finally progress to a better language, but that V
  • 14. VI □ Preface few Java or C++ programmers will migrate to the new language. Time will tell if my powers of foresight are any better than anybody else’s.) For the present edition I have expanded the number of languages that I use for examples, but I have eliminated many long narratives on a single language. Descriptions of techniques are often given in the form of tables or shorter expla¬ nations. As with the first two editions, I make no pretenses of being a reference manual for any language, and students producing anything more than trivial pro¬ grams m any of the languages I discuss would do well to avail themselves of a language-specific source. Nevertheless, in this third edition I have attempted to retain the overall struc¬ ture I used in the first two editions. This can be described as a series of themes. I. Introduction and Design. Chapter 1 introduces in an informal setting the basic concepts of object-oriented programming. Chapter 2 continues this by discussing the tools used by computer scientists to deal with complexity and how object- oriented techniques fit into this framework. Chapter 3 introduces the principle of designing by responsibility. These three chapters are fundamental, and their study should not be given short shrift. In particular, I strongly encourage at least one, if not several, group exercises in which CRC cards, introduced in Chapter 3, are used in problem solving. The manipulation of physical index cards in a group setting is one of the best techniques I have encountered for developing and reinforcing the notions of behavior, responsibility, and encapsulation. In the past decade the field of object-oriented design has expanded consider¬ ably. And for many readers Chapter 3 may either be too little or too much—too much if they already have extensive experience with object-oriented modeling languages and design, and too little if they have never heard of these topics. Never¬ theless, I have tried to strike a balance. I have continued to discuss responsibility- driven design, although it is now only one of many alternative object-oriented design techniques, because I think it is the simplest approach for beginning stu¬ dents to understand. II. Classes, Methods, and Messages. Chapters 4 and 5 introduce the basic syntax used by our example languages (Smalltalk, C++, Java, Objective-C, Object and Delphi Pascal, and several others) to create classes and methods and to send messages. Chapter 4 concentrates on the compile-time features (classes and methods), and Chapter 5 describes the dynamic aspects (creating objects and sending messages). Chapters 6 and 7 reinforce these ideas with the first of a series of case studies—example programs developed in an object-oriented fashion and illustrating various features of the technique. III. Inheritance and Software Reuse. Although inheritance is introduced in Chapter 1, it does not play a prominent role again until Chapter 8. Inheritance
  • 15. Preface vii and polymorphic substitution is discussed as a primary technique for software reuse. The case study in Chapter 9, written in the newly introduced language C#, both illustrates the application of inheritance and the use of a standard API (application programming interface). IV. Inheritance in More Detail. Chapters 10 through 13 delve into the concepts of inheritance and substitution in greater detail. The introduction of inheritance into a programming language has an impact on almost every other aspect of the language, and this impact is often not initially obvious to the student (or programmer). Chapter 10 discusses the sometimes subtle distinction between sub¬ classes and subtypes. Chapter 11 investigates how different languages approach the use of static and dynamic features. Chapter 12 examines some of the surpris¬ ing implications that result from the introduction of inheritance and polymorphic substitution into a language. Chapter 13 discusses the often misunderstood topic of multiple inheritance. ^ V. Polymorphism. Much of the power of object-oriented programming comes through the application of various forms of polymorphism. Chapter 14 intro¬ duces the basic mechanisms used for attaining polymorphism in object-oriented languages and is followed by four chapters that explore the principal forms of polymorphism in great detail. VI. Applications of Polymorphism. Chapter 19 examines one of the most com¬ mon applications of polymorphism, the development of classes for common data structure abstractions. Chapter 20 is a case study that examines a recent addition to the language C++, the STL. Chapter 21 presents the idea oi frameworks, a pop¬ ular and very successful approach to software reuse that builds on the mechanisms provided by polymorphism. Chapter 22 describes one well-known framework, the Java Abstract Windowing Toolkit. VII. Object Interactions. Starting in Chapter 23 we move up a level of ab¬ straction and consider classes in more general relationships and not just the parent/child relationship. Chapter 23 discusses the ways two or more classes (or objects) can interact with each other. Many of these interactions have been cap¬ tured and defined in a formalism called a design pattern. The concept of design patterns and a description of the most common design patterns are presented in Chapter 24. VIII. Advanced Topics. The final three chapters discuss topics that can be considered advanced for an introductory text such as this one. These include the idea of reflection and introspection (Chapter 25), network programming (Chapter 26), and the implementation techniques used in the execution of object- oriented languages (Chapter 27).
  • 16. s Preface viii In the ten-week course I teach at Oregon State University I devote approxi¬ mately one week to each of the major areas just described. Students in this course are upper-division undergraduate and first-year graduate students. In conjunction with the lectures, students work on moderate-sized projects, using an object- oriented language of their choice, and the term ends with student presentations of project designs and outcomes. Any attempt to force a complex and multifaceted topic into a linear narrative will run into issues of ordering, and this book is no exception. In general my approach has been to introduce an idea as early as possible and then in later chapters explore the idea in more detail, bringing out aspects or issues that might not be obvious on first encounter. Despite my opinion that my ordering makes sense, I am aware that others may find it convenient to select a different approach. In particular, some instructors find it useful to bring forward some of the software engineering issues that I postpone until Chapter 23, thereby bringing them closer to the design chapter (Chapter 3). Similarly, while multiple inheritance is a form of inheritance and therefore rightly belongs in Section IV, the features that make multiple inheritance difficult to work with derive from interactions with polymorphism and hence might make more sense after students have had time to read Section V. For these reasons and many more, instructors should feel free to adapt the material and the order of presentation to their own particular circumstance. Assumed Background s I have presented the material in this book assuming only that the reader is knowledgeable in some conventional programming language, such as Pascal or C. In my courses, the material has been used successfully at the upper-division (junior or senior) undergraduate level and at the first-year graduate level. In some cases (particularly in the last quarter of the book), further knowledge may be helpful but is not assumed. For example, a student who has taken a course in software engineering may find some of the material in Chapter 23 more relevant, and one who has had a course in compiler construction will find Chapter 27 more intelligible. Both chapters can be simplified in presentation if necessary. Many sections have been marked with an asterisk (’''). These represent op¬ tional material. Such sections may be interesting but are not central to the ideas being presented. Often they cover a topic that is relevant only to a particular object-oriented language and not to object-oriented programming in general. This material can be included or omitted at the discretion of the instructor, depend¬ ing on the interests and backgrounds of the students and the instructor or on the dictates of time.
  • 17. Preface IX Obtaining the Source b Source code for the case studies presented in the book can be accessed via the mechanism of anonymous ftp from the machine ftp.cs.orst.edu in the di¬ rectory /pub/budd/oopintro. This directory will also be used to maintain a number of other items, such as an errata list, study questions for each chap¬ ter, and copies of the overhead slides I use in my course. This information can also be accessed via the World Wide Web from my personal home pages at http: //www. cs . orSt. edu/~budd. Requests for further information can be for¬ warded to the electronic mail address buddies . orst. edu or to Professor Timothy A. Budd, Department of Computer Science, Oregon State University, Corvallis, Oregon 97331. Acknowledgments □ I am certainly grateful to the 65 students in my course, CS589, at Oregon State University, who in the fall of 1989 suffered through the development of the first draft of the first edition of this text. They received one chapter at a time, often only a day or two before I lectured on the material. Their patience in this regard is appreciated. Their specific comments, corrections, critiques, and criticisms were most helpful. In particular, I wish to acknowledge the detailed comments provided by Thomas Amoth, Kim Drongesen, Frank Griswold, Rajeev Pandey, and Phil Ruder. The solitaire game developed in Chapter 9 was inspired by the project com¬ pleted by Kim Drongesen, and the billiards game in Chapter 7 was based on the project by Guenter Marnier and Dietrich Wettschereck. In both cases, however, the code itself has been entirely rewritten and is my own. In fact, in both cases my code is considerably stripped down for the purposes of exposition and is in no way comparable to the greatly superior projects completed by those students. For an author, it is always useful to have others provide an independent perspective on one’s work, and I admit to gaining useful insights into the first edition from a study guide prepared by Arina Brintz, Louise Leenen, Tommie Meyer, Helene Rosenblatt, and Anel Viljoen of the Department of Computer Science and Information Systems at the University of South Africa in Pretoria. Countless people have provided assistance by pointing out errors or omissions in the first two editions and by offering improvements. I am grateful to them all and sorry that I cannot list them by name. I benefitted greatly from comments provided by several readers of an early manuscript draft of this third edition. These reviewers included Ali Behforooz (Towson University), Hang Lau (Concordia University, Canada), Blayne Mayfield (Oklahoma State University), Robert Morse (University of Evansville), Roberto
  • 18. X Q Preface Ordonez (Andrews University), Shon Vick (University of Maryland, Baltimore County), and Conrad Weisert (Information Disciplines, Inc.). I have made exten¬ sive revisions in response to their comments, and therefore any remaining errors are mine alone and no reflection on their efforts. For the third edition my capable, competent, and patient editor at Addison- Wesley has been Susan Hartman-Sullivan, assisted by Elinor Actipis. Final copy was coordinated by Diane Freed. Layout and production were performed by Paul Anagnostopoulos and Jacqui Scarlott of Windfall Software. I have worked with Paul and Jacqui on several books now, and I’m continually amazed by the results they are able to achieve from my meager words.
  • 19. Contents Preface 1 0 Thinking Object-Oriented 1.1 Why Is OOP Popular? 2 1.2 Language and Thought 2 1.2.1 Eskimos and snow 3 1.2.2 An example from computer languages 3 1.2.3 Church’s conjecture and the Whorf hypothesis 5 1.3 A New Paradigm 7 1.4 A Way of Viewing the World 8 1.4.1 Agents and communities 9 1.4.2 Messages and methods 10 1.4.3 Responsibilities 11 1.4.4 Classes and instances 11 1.4.5 Class hierarchies—inheritance 12 1.4.6 Method binding and overriding 14 1.4.7 Summary of object-oriented concepts 14 1.5 Computation as Simulation 15 1.5.1 The power of metaphor 16 1.5.2 Avoiding infinite regression 17 1.6 A Brief History 18 Summary 19 Further Reading 20 Self-Study Questions 22 Exercises 23 XI
  • 20. xii □ Contents 2 0 Abstraction 25 2.1 Layers of Abstraction 26 2.2 Other Forms of Abstraction 30 2.2.1 Division into parts 32 2.2.2 Encapsulation and interchangeability 32 2.2.3 Interface and implementation 33 2.2.4 The service view 34 2.2.5 Composition 34 2.2.6 Layers of specialization 36 2.2.7 Patterns 38 2.3 A Short History of Abstraction Mechanisms 39 2.3.1 Assembly language 39 2.3.2 Procedures 40 2.3.3 Modules 41 2.3.4 Abstract data types 43 2.3.5 A service-centered view 44 2.3.6 Messages, inheritance, and polymorphism 44 Summary 45 Further Information 46 Self-Study Questions 47 Exercises 47 3 □ Object-Oriented Design 49 3.1 Responsibility Implies Noninterference 50 3.2 Programming in the Small and in the Large 51 3.3 Why Begin with Behavior? 51 3.4 A Case Study in RDD 52 3.4.1 The Interactive Intelligent Kitchen Helper 53 3.4.2 Working through scenarios 53 3.4.3 Identification of components 54 3.5 CRC Cards—Recording Responsibility 55 3.5.1 Give components a physical representation 55 3.5.2 The what/who cycle 56 3.5.3 Documentation 56 3.6 Components and Behavior 57
  • 21. Contents 3.6.1 Postponing decisions 58 3.6.2 Preparing for change 59 3.6.3 Continuing the scenario 59 3.6.4 Interaction diagrams 61 3.7 Software Components 62 3.7.1 Behavior and state 62 3.7.2 Instances and classes 63 3.7.3 Couplmg and cohesion 63 3.7.4 Interface and implementation-—Parnas’s principles 3.8 Formalize the Interface 65 3.8.1 Coming up with names 65 3.9 Designing the Representation 67 3.10 Implementing Components 67 3.11 Integration of Components 68 3.12 Maintenance and Evolution Summary 69 Further Reading 70 Self-Study Questions 70 Exercises 71 69 4 □ Classes and Methods 4.1 Encapsulation 73 4.2 Class Definitions 74 4.2.1 C++, Java, and C# 75 4.2.2 Apple Object Pascal and Delphi Pascal 77 4.2.3 Smalltalk 77 4.2.4 Other languages 79 4.3 Methods 80 4.3.1 Order of methods in a class declaration 82 4.3.2 Constant or immutable data fields 83 4.3.3 Separating definition and implementation 83 4.4 Variations on Class Themes 87 4.4.1 Methods without classes in Oberon 87 4.4.2 Interfaces 88 4.4.3 Properties 89 64
  • 22. xiv □ Contents 4.4.4 Forward definitions 90 4.4.5 Inner or nested classes 91 4.4.6 Class data fields 94 4.4.7 Classes as objects 96 Summary 97 Further Reading 97 Self-Study Questions 98 Exercises 98 5 □ Messages, Instances, and Initialization 101 5.1 Message-Passing Syntax 101 5.2 Statically and Dynamically Typed Languages 103 5.3 Accessing the Receiver from within a Method 104 5.4 Object Creation 106 5.4.1 Creation of arrays of objects 107 5.5 Pointers and Memory Allocation 108 5.5.1 Memory recovery 109 5.6 Constructors 111 5.6.1 The orthodox canonical class form 115 5.6.2 Constant values 116 5.7 Destructors and Finalizers 117 5.8 Metaclasses in Smalltalk 120 Summary 122 Further Reading 122 Self-Study Questions 123 Exercises 123 6 0 A Case Study: The Eight-Queens Puzzle 1 25 6.1 The Eight-Queens Puzzle 125 6.1.1 Creating objects that find their own solution 126 6.2 Using Generators 127 6.2.1 Initialization 128 6.2.2 Finding a solution 129 6.2.3 Advancing to the next position 129
  • 23. Contents XV 6.3 The Eight-Queens Puzzle in Several Languages 130 6.3.1 The eight-queens puzzle in Object Pascal 130 6.3.2 The eight-queens puzzle in C++ 133 6.3.3 The eight-queens puzzle in Java 136 6.3.4 The eight-queens puzzle in Objective-C 139 6.3.5 The eight-queens puzzle in Smalltalk 142 6.3.6 The eight-queens puzzle in Ruby 143 Summary 145 Further Reading 145 Self-Study Questions 145 Exercises 146 7 0 A Case Study: A Billiards Game 147 7.1 The Elements of Billiards 147 7.2 Graphical Objects 148 7.2.1 The wall graphical object 149 7.2.2 The hole graphical object ISO 7.2.3 The ball graphical object 151 7.3 The Main Program 155 7.4 Using Inheritance 156 Summary 159 Further Information 159 Self-Study Questions 159 Exercises 160 8 0 Inheritance and Substitution 161 8.1 An Intuitive Description of Inheritance 161 8.1.1 The is-a test 162 8.1.2 Reasons to use inheritance 162 8.2 Inheritance in Various Languages 164 8.3 Subclass, Subtype, and Substitution 166 8.3.1 Substitution and strong typing 167 ' ’ 8.4 Overriding and Virtual Methods 168 8.5 Interfaces and Abstract Classes 170
  • 24. XVI □ Contents 8.6 Forms of Inheritance 171 8.6.1 Subclassing for specialization (subtyping) 171 8.6.2 Subclassing for specification 171 8.6.3 Subclassing for construction 172 8.6.4 Subclassing for generalization 173 8.6.5 Subclassing for extension 174 8.6.6 Subclassing for limitation 174 8.6.7 Subclassing for variance 174 8.6.8 Subclassing for combination 175 8.6.9 Summary of the forms of inheritance 175 8.7 Variations on Inheritance 176 8.7.1 Anonymous classes in Java 176 8.7.2 Inheritance and constructors 177 8.7.3 Virtual destructors 178 8.8 The Benefits of Inheritance 179 8.8.1 Software reusability 179 8.8.2 Code sharing 179 8.8.3 Consistency of interface 179 8.8.4 Software components 179 8.8.5 Rapid prototyping 180 8.8.6 Polymorphism and frameworks 180 8.8.7 Information hiding 180 8.9 The Costs of Inheritance 181 8.9.1 Execution speed 181 8.9.2 Program size 181 8.9.3 Message-passing overhead 181 8.9.4 Program complexity 182 Summary 182 Further Reading 183 Self-Study Questions 183 Exercises 184 187 9 □ A Case Study—A Card Game 9.1 The Class PlayingCard 187 9.2 Data and View Classes 189 9.3 The Game 190
  • 25. Contents xvii 9.4 Card Piles—Inheritance in Action 191 9.4.1 The default card pile 193 9.4.2 The suit piles 194 9.4.3 The deck pile 194 9.4.4 The discard pile 196 9.4.5 The tableau piles 197 9.5 Playing the Polymorphic Game 199 9.6 The Graphical User Interface 199 Summary 204 Further Reading 204 Self-Study Questions 204 Exercises 205 10 0 Subclasses and Subtypes 207 10.1 Substitutability 207 10.2 Subtypes 208 10.3 The Substitutability Paradox 211 10.3.1 Is this a problem? 212 10.4 Subclassing for Construction 212 10.4.1 Private inheritance in C++ 214 10.5 Dynamically Typed Languages 215 10.6 Pre- and Postconditions 216 10.7 Refinement Semantics 217 Summary 218 Further Reading 218 Self-Study Questions 219 Exercises 219 11 E Static and Dynamic Behavior 221 11.1 Static versus Dynamic Typing 221 11.2 Static and Dynamic Classes 223 11.2.1 Run-time type determination 225 11.2.2 Down casting (reverse polymorphism) 227
  • 26. XViii □ Contents 11.2.3 Run-time testing without language support 227 11.2.4 Testing message understanding 229 11.3 Static versus Dynamic Method Binding 230 Summary 232 Further Reading 233 Self-Study Questions 233 Exercises 234 12 0 Implications of Substitution 12.1 Memory Layout 235 12.1.1 Minimum static space allocation 237 12.1.2 Maximum static space allocation 240 12.1.3 Dynamic memory allocation 240 12.2 Assignment 242 12.2.1 Assignment in C++ 242 12.3 Copies and Clones 245 12.3.1 Copies in Smalltalk and Objective-C 24S 12.3.2 Copy constructors in C++ 245 12.3.3 Cloning in Java 246 12.4 Equality 247 12.4.1 Equality and identity 247 12.4.2 The paradoxes of equality testing 248 Summary 250 Eurther Reading 251 Self-Study Questions 251 Exercises 251 13 0 Multiple Inheritance 13.1 Inheritance as Categorization 254 13.1.1 Incomparable complex numbers 255 13.2 Problems Arising from Multiple Inheritance 257 13.2.1 Name ambiguity 257 13.2.2 Impact on substitutability 259 13.2.3 Redefinition in Eiffel 260 13.2.4 Resolution by class ordering in CEOS 261 235 253
  • 27. Contents XIX 13.3 Multiple Inheritance of Interfaces 263 13.3.1 Mixins in CLOS 266 13.4 Inheritance from Common Ancestors 267 13.4.1 Constructors and multiple inheritance 270 13.5 Inner Classes 271 Summary 272 Further Reading 273 Self-Study Questions 273 Exercises 273 14 □ Polymorphism and Software Reuse 275 14.1 Polymorphism in Programming Languages 275 14.1.1 Many tools, one goal 277 14.2 Mechanisms for Software Reuse 277 14.2.1 Using composition 278 14.2.2 Using inheritance 280 14.2.3 Composition and inheritance contrasted 282 14.3 Efficiency and Polymorphism 283 14.4 Will Widespread Software Reuse Become Reality? 284 Summary 285 Further Information 285 Self-Study Questions 286 Exercises 286 1 5 E Overloading 287 15.1 Type Signatures and Scopes 288 15.2 Overloading Based on Scopes 289 15.3 Overloading Based on Type Signatures 290 15.3.1 Coercion and conversion 293 15.4 Redefinition 299 15.5 Polyadicity 301 " 15.5.1 Optional parameters 303 15.6 Multi-Methods 303
  • 28. XX Q Contents 15.6.1 Overloading Based on Values 306 Summary 306 Further Information 306 Self-Study Questions 307 Exercises 307 16 □ Overriding 309 16.1 Notating Overriding 311 16.2 Replacement versus Refinement 313 16.2.1 Replacement in Smalltalk 313 16.2.2 Refinement in Beta 316 16.2.3 Refinement and the subclass/subtype distinction 319 16.2.4 Wrappers in CLOS 319 16.3 Deferred Methods 320 16.4 Overriding versus Shadowing 322 16.5 Covariance and Contravariance 324 16.6 Variations on Overriding 329 16.6.1 Final methods in Java 329 16.6.2 Versioning in C# 330 Summary 331 Further Information 332 Self-Study Questions 332 Exercises 332 17 0 The Polymorphic Variable 335 17.1 Simple Polymorphic Variables 335 17.2 The Receiver Variable 337 17.2.1 The role of the polymorphic variable in frameworks 339 17.2.2 Endpoint comparisons in Smalltalk 340 17.2.3 Self and super 341 17.3 Downcasting 343 17.4 Pure Polymorphism 344 Summary 347
  • 29. Further Information 347 Self-Study Questions 348 Exercises 348 Contents XX i 18 0 Generics 18.1 Template Functions 349 18.2 Template Classes 351 18.2.1 Bounded genericity 353 18.3 Inheritance in Template Arguments 353 18.3.1 Inheritance and arrays 355 18.4 Case Study—Combining Separate Classes 356 Summary 360 Further Reading 360 Self-Study Questions 360 Exercises 360 19 0 Container Classes 19.1 Containers in Dynamically Typed Languages 363 19.1.1 Containers in Smalltalk-80 364 19.2 Containers in Statically Typed Languages 365 19.2.1 The tension between typing and reuse 366 19.2.2 Substitution and downcasting 368 19.2.3 Using substitution and overriding 372 19.2.4 Parameterized classes 374 19.3 Restricting Element Types 376 19.4 Element Traversal 378 19.4.1 Iterator loops 379 19.4.2 The visitor approach 381 Summary 385 Eurther Reading 386 ' ' Self-Study Questions 387 Exercises 387 349 363
  • 30. XX ii □ Contents 20 0 A Case Study: The STL 389 20.1 Iterators 391 20.2 Function Objects 393 20.3 Example Program—An Inventory System 394 20.4 Example Program—Graphs 396 20.4.1 Shortest path algorithm 399 20.4.2 Developing the data structures 399 20.5 A Concordance 402 20.6 The Future of OOP 405 Summary 406 Further Reading 406 Self-Study Questions 406 Exercises 406 21 0 Frameworks 407 21.1 Reuse and Specialization 407 21.1.1 High-and low-level abstractions 410 21.1.2 An upside-down library 412 21.2 Example Erameworks 413 21.2.1 The Java Applet API 413 21.2.2 A Simulation Framework 414 21.2.3 An event-driven simulation framework 415 Summary 422 Further Reading 422 Self-Study Questions 422 Exercises 422 22 0 An Example Framework: The AWT and Swing 423 22.1 The AWT Class Hierarchy 423 22.2 The Layout Manager 426 22.3 Listeners 428 22.3.1 Adapter classes 429 22.4 User Interface Components 430
  • 31. Contents 22.5 Case Study: A Color Display 433 22.6 The Swing Component Library 437 22.6.1 Import libraries 437 22.6.2 Different components 437 22.6.3 Different paint protocol 438 22.6.4 Adding components to a window 438 Summary 438 Further Reading 439 Self-Study Questions 439 Exercises 439 23 0 Object Interconnections 23.1 Coupling and Cohesion 442 23.1.1 Varieties of coupling 442 23.1.2 Varieties of cohesion 445 23.1.3 The Law of Demeter 447 23.1.4 Class-level versus object-level visibility 448 23.1.5 Active values 449 23.2 Subclass Clients and User Clients 450 23.3 Control of Access and Visibility 451 23.3.1 Visibility in Smalltalk 451 23.3.2 Visibility in Object Pascal 452 23.3.3 Visibility in C++ 452 23.3.4 Visibility in Java 457 23.3.5 Visibility in Objective-C 458 23.4 Intentional Dependency 459 Summary 460 Further Reading 460 Self-Study Questions 461 Exercises 461 24 0 Design Patterns 24.1 Controlling Information Flow 464 24.2 Describing Patterns 465 24.3 Iterator 466 xxiii 441 463
  • 32. XXIV H Contents 24.4 Software Factory 467 24.5 Strategy 468 24.6 Singleton 469 24.7 Composite 469 24.8 Decorator 471 24.9 The Double-Dispatching Pattern 472 24.10 Flyweight 474 24.11 Proxy 474 24.12 Facade 475 24.13 Observer 475 Summary 476 Further Reading 477 Self-Study Questions 478 Exercises 478 25 □ Reflection and Introspection 25.1 Mechanisms for Understanding 479 25.1.1 Class objects 479 25.1.2 The class name as string 481 25.1.3 Testing the class of an object 481 25.1.4 Creating an instance from a class 483 25.1.5 Testing if an object understands a message 484 25.1.6 Class behavior 484 25.2 Methods as Objects 485 25.3 Mechanisms for Modification 486 25.3.1 Method editing in Smalltalk 486 25.3.2 Dynamic class loading in Java 487 25.4 Metaclasses 489 Summary 491 Further Reading 491 Self-Study Questions 492 479
  • 33. Contents XXV 26 0 Distributed Objects 26.1 Addresses, Ports, and Sockets 494 26.2 A Simple Client/Server Program 496 26.3 Multiple Clients 498 26.4 Transmitting Objects over a Network 504 26.5 Providing More Complexity 507 Summary 507 Further Reading 508 Self-Study Questions 508 Exercises 508 27 0 Implementation 27.1 Compilers and Interpreters 511 27.2 The Receiver as Argument 512 27.3 Inherited Methods 513 27.3.1 The problem of multiple inheritance 514 173.1 The slicing problem 515 27.4 Overridden Methods 515 27.4.1 Eliminating virtual calls.and in-lining 517 27.5 Name Encoding 518 27.6 Dispatch Tables 518 27.6.1 A method cache 510 27.7 Bytecode Interpreters 521 27.8 Just-in-Time Compilation 523 Summary 524 Eurther Reading 524 Self-Study Questions 525 Exercises 525 A 0 Source for the Eight-Queens Puzzle A.l Eight-Queens in Apple Object Pascal 527 A.2 Eight-Queens in C++ 530 493 511 527
  • 34. XXVi Q Contents A.3 Eight-Queens in Java 532 A.4 Eight-Queens in Objective-C 536 A.5 Eight-Queens in Ruby 539 A. 6 Eight-Queens in Smalltalk 541 B 0 Source for the Billiards Game 543 B. l The Version without Inheritance 543 B.2 The Version with Inheritance 552 C 0 Source for the Solitaire Game 557 Glossary 569 References 585 Index 599
  • 35. Third Edition An Introduction to Object-Oriented Programming ✓
  • 36. 1 fit » • K' CK* CWV’’ 37 ► ..i sw m w 4nd •t I« . • f ' ■ • * -j (ffh ■ * '■*1 *
  • 37. Although the fundamental features of what we now call ohject-oriented program¬ ming were invented in the 1960s, object-oriented languages really caught the attention of the computing public-at-large in the 1980s. Two seminal events were the publication of a widely read issue of Byte (August 1981) that described the programming language Smalltalk, and the first international conference on object- oriented programming languages and applications, held in Portland, Oregon in 1986. Now, almost 20 years later, the situation noted in the first edition of this book (1991) still exists. Object-oriented programming (OOP) has become exceedingly popular in the past few years. Software producers rush to release object-oriented versions of their products. Countless books and special issues of academic and trade journals have appeared on the subject. Students strive to list “experience in object-oriented programming” on their resumes. To judge from this frantic activity, object-oriented programming is being greeted with even more enthusiasm than we saw heralding earlier revolutionary ideas, such as “structured programming” or “expert systems.” My intent in these first two chapters is to investigate and explain the basic principles of object-oriented programming and, in so doing to illustrate the following two propositions. • OOP is a revolutionary idea, totally unlike anything that has come before in programming. 1
  • 38. 2 Chapter 1 Q Thinking Object-Oriented • OOP is an evolutionary step, following naturally on the heels of earlier programming abstractions. 1.1 □ Why Is OOP Popular? There are a number of important reasons why in the past two decades object- oriented programming has become the dominant programming paradigm. Object- oriented programming scales very well, from the most trivial of problems to the most complex tasks. It provides a form of abstraction that resonates with techniques people use to solve problems in their everyday lives. And for most of the dominant object-oriented languages there are an increasingly large number of libraries that assist in the development of applications for many domains. Object-oriented programming is just the latest in a long series of solutions that has been proposed to help solve the “software crisis.” At heart, the software crisis simply means that our imaginations, and the tasks we would like to solve with the help of computers, almost always outstrip our abilities. But while object-oriented techniques do facilitate the creation of complex software systems, it is important to remember that OOP is not a panacea. Pro¬ gramming a computer is still one of the most difficult tasks people undertake. Becoming proficient in programming requires talent, creativity, intelligence, logic, the ability to build and use abstractions, and experience—even when the best of tools are available. I suspect another reason for the particular popularity of languages such as C++ and Delphi (as opposed to languages such as Smalltalk and Beta) is that managers and programmers alike hope that a C or Pascal programmer can be changed into a C++ or Delphi programmer with no more effort than the addition of a few characters to their job title. Unfortunately, this hope is a long way from being realized. Object-oriented programming is a new way of thinking about what it means to compute, about how we can structure information and communicate our intentions both to each other and to the machine. To become proficient in object-oriented techniques requires a complete reevaluation of traditional software development. 1.2 □ Language and Thought In his book Language, Thought & Reality, Benjamin Lee Whorf discusses the ideas of linguist Edward Sapir. Human beings do not live in the objective world alone, nor alone in the world of social activity as ordinarily understood, but are very much at the mercy of the particular language which has become the medium of expression for their society. It is quite an illusion to imagine that one adjusts
  • 39. 1.2 Language and Thought 3 to reality essentially without the use of language and that language is merely an incidental means of solving specific problems of communication or reflection. The fact of the matter is that the “real world” is to a large extent unconsciously built up on the language habits of the group .... We see and hear and otherwise experience very largely as we do because the language habits of our community predispose certain choices of interpretation. This quote emphasizes the fact that the languages we speak directly influence the way in which we view the world. This is true not only for natural languages, such as the kind studied by early-twentieth-century American linguists Edward Sapir and Benjamin Lee Whorf, but also for artificial languages, such as those we use in programming computers. 1.2.1 Eskimos and snow An almost universally cited e?tample of the phenomenon of language influencing thought, although also perhaps an erroneous one, is that Eskimo (or Inuit) languages have different words to describe different types of snow—wet, fluffy, heavy, icy, and so on. This is not surprising. Any community with common interests will naturally develop a specialized vocabulary for concepts they wish to discuss. (Meteorologists, despite working in English, face similar problems of communication and have also developed their own extensive vocabulary.) What is important is to not overgeneralize the conclusion we can draw from this simple observation. It is not that the Eskimo eye is in any significant respect different from my own or that Eskimos can see things I cannot perceive. With time and training I could do just as well at differentiating types of snow. But the language I speak (English) does not force me into doing so, and so it is not natural to me. Thus, a different language (such as Inuktitut) can lead one (but does not require one) to view the world in a different fashion. Making effective use of object-oriented principles requires one to view the world in a new way. But simply using an object-oriented language (such as Java or C+-I-) does not, by itself, force one to become an object-oriented programmer. While the use of an object-oriented language will simplify the development of object-oriented solutions, it is true, as it has been quipped, that “EORTRAN programs can be written in any language.” 1.2.2 An example from computer languages The relationship we noted between language and thought for natural languages is even more pronounced in artificial computer languages. That is, the language in which a programmer thinks a problem will be solved will fundamentally color and alter the way an algorithm is developed.
  • 40. 4 Chapter 1 □ Thinking Object-Oriented Here is an example that illustrates this relationship between computer lan¬ guage and problem solution. Several years ago a student working in genetic research was faced with a task in the analysis of DNA sequences. The problem could be reduced to relatively simple form. The DNA is represented as a vector of N integer values, where N is very large (on the order of tens of thousands). The problem was to discover whether any pattern of length M, where M was a fixed and small constant (say 5 or 10), is ever repeated in the array of values. 1 m m n t c g a g t c g a g The programmer dutifully sat down and wrote a simple and straightforward FORTRAN program something like the following. DO 10 I = 1, N-M DO 10 J = 1, N-M FOUND = .TRUE. DO 20 K = 1, M 20 IF XEl+K-1] .NE. X[J+K-1] THEN FOUND = .FALSE. IF FOUND THEN ... 10 CONTINUE He was somewhat disappointed when trial runs indicated his program would need many hours to complete. He discussed his problem with a second student who happened to be proficient in the programming language APL. She offered to try to write a program for this problem. The first student was dubious. After all, FORTRAN was known to be one of the most “efficient” programming languages. It was compiled; APL was only interpreted. So it was with a certain amount of incredulity that he discovered that the APL programmer was able to write an algorithm that worked in a matter of minutes, not hours. What the APL programmer had done was to rearrange the problem. Rather than working with a vector of N elements, she reorganized the data into a matrix with roughly N rows and M columns. Xi X2 • • • X2 X3 • • • ^n—m X„_i ^n—(m— 1) . . . ^n— She then ordered this matrix by rows (that is, treated each row as a unit, moving entire rows during the process of sorting). If any pattern was repeated, then two adjacent rows in the ordered matrix would have identical values.
  • 41. 1.2 Language and Thought 5 T G G A C C T G G A G C It was a trivial matter to check for this condition. The reason the APT pro¬ gram was faster had nothing to do with the speed of APT versus FORTRAN; it was simply that the FORTRAN program employed an algorithm that was 0(M X N^), whereas the sorting solution used by the APT programmer required approximately 0(M x N log N) operations. The point of this story is not that APT is in any way a “better” programming language than FORTRAN but that the APT programmer was naturally led to discover an entirely different form of solution. The reason, in this case, is that loops are very difficult to write in APT, whereas sorting is trivial—it is a built-in operator defined as part of the language. Thus, because the sorting operation is so easy to perform, good APT programmers tend to look for novel applications for it. This is how the programming language in which the solution is to be written directs the programmer’s mind to view the problem in a certain way. * 1.2.3 Church’s conjecture and the Whorf hypothesis The assertion that the language in which an idea is expressed can influence or direct a line of thought is relatively easy to believe. However, a stronger conjecture, known in linguistics as the Sapir-Whorf hypothesis, goes much further and remains controversial. The Sapir-Whorf hypothesis asserts that it may be possible for an individual working in one language to imagine thoughts or to utter ideas that cannot in any way be translated, or even understood by individuals operating in a different linguistic framework. According to advocates of the hypothesis, this can occur when the language of the second individual has no equivalent words and lacks even concepts or categories for the ideas involved in the thought. It is interesting to compare this possibility with an almost directly opposite concept from computer science—namely. Church’s conjecture. Starting in the 1930s and continuing through the 1940s and 1950s there was a great deal of interest within the mathematical and nascent computing community in a variety of formalisms that could be used for the calculation of functions. Examples are the notations proposed by Church [Church 1936], Post [Post 1936], Markov [Markov 1951], Turing [Turing 1936], Kleene [Kleene 1936], and others. Over time a number of arguments were put forth to demonstrate that many of these systems could be used in the simulation of other systems. Often, such argurnents for a pair of systems could be made in both directions, effectively showing that the systems were identical in computation power. The sheer number
  • 42. 6 Chapter 1 H Thinking Object-Oriented of such arguments led the logician Alonzo Church to pronounce a conjecture that is now associated with his name. Church’s Conjecture: Any computation for which there is an effective procedure can be realized by a Turing machine. By nature this conjecture must remain unproven and unprovable, since we have no rigorous definition of the term “effective procedure.” Nevertheless, no counterexample has yet been found, and the weight of evidence seems to favor affirmation of this claim. Acceptance of Church’s conjecture has an important and profound implication for the study of programming languages. Turing machines are wonderfully simple mechanisms, and it does not require many features in a language to simulate such a device. In the 1960s, for example, it was demonstrated that a Turing machine could be emulated in any language that possessed at least a conditional statement and a looping construct [Bohm 1966]. (This greatly misunderstood result was the major ammunition used to “prove” that the infamous goto statement was unnecessary.) If we accept Church’s conjecture, any language in which it is possible to simulate a Turing machine is sufficiently powerful to perform any realizable algorithm. (To solve a problem, find the Turing machine that produces the desired result, which by Church’s conjecture must exist; then simulate the execution of the Turing machine in your favorite language.) Thus, arguments about the relative “power” of programming languages—if by power we mean “ability to solve problems”—are generally vacuous. The late Alan Perils had a term for such an argument. He called it a “Turing Tarpit” because it is often so difficult to extricate oneself from it and so fundamentally pointless. Note that Church’s conjecture is, in a certain sense, almost the exact opposite of the Sapir-Whorf hypothesis. Church’s conjecture states that in a fundamental way all programming languages are identical. Any idea that can be expressed in one language can, in theory, be expressed in any language. The Sapir-Whorf hypothesis claims that it is possible to have ideas that can be expressed in one language that cannot be expressed in another. Many linguists reject the Sapir-Whorf hypothesis and instead adopt a sort of “Turing-equivalence” for natural languages. By this we mean that, with a sufficient amount of work, any idea can be expressed in any language. For example, while the language spoken by a native of a warm climate may not make it instinctive to examine a field of snow and categorize it by type or use, with time and training it certainly can be learned. Similarly, object-oriented techniques do not provide any new computational power that permits problems to be solved that cannot, in theory, be solved by other means. But object-oriented techniques do make it easier and more natural to address problems in a fashion that tends to favor the management of large software projects.
  • 43. 1.3 A New Paradigm 1 Thus, for both computer and natural languages the language will direct thoughts but cannot proscribe thoughts. 1.3 B A New Paradigm Object-oriented programming is frequently referred to as a new programming paradigm. Other programming paradigms include the imperative-programming paradigm (languages such as Pascal or C), the logic programming paradigm (Prolog), and the functional-programming paradigm (ML or Haskell). It is interesting to examine the definition of the word “paradigm.” The fol¬ lowing is from the American Heritage Dictionary of the English Language. par a digm n. 1. A list of all the inflectional forms of a word taken as an illustrative example of the conjugation or declension to which it belongs. 2. Any example or model. [Late Latin paradigma, from Greek paradeigma, model, from paradeiknunai, to compare, exhibit.] At first blush, the conjugation or declension of Latin words would seem to have little to do with computer programming languages. To understand the connection, we must note that the word was brought into the modern vocabulary through an influential book. The Structure of Scientific Revolutions, by the historian of science Thomas Kuhn [Kuhn 1970]. Kuhn used the term in the second form, to describe a set of theories, standards, and methods that together represent a way of organizing knowledge—that is, a way of viewing the world. Kuhn’s thesis was that revolutions in science occur when an older paradigm is reexamined, rejected, and replaced by another. It is in this sense, as a model or example and as an organizational approach, that Robert Floyd used the term in his 1979 ACM Turing Award lecture [Floyd 1979], “The Paradigms of Programming.” A programming paradigm is a way of conceptualizing what it means to perform computation and how tasks to be carried out on a computer should be structured and organized. Although new to computation, the organizing technique that lies at the heart of object-oriented programming can be traced back at least as far as Carolus Lin¬ naeus (1707-1778) (Figure 1.1). It was Linnaeus, you will recall, who categorized biological organisms using the idea of phylum, genus, species, and so on. Paradoxically, the style of problem solving embodied in the object-oriented technique is frequently the method used to address problems in everyday life. Thus, computer novices are often able to grasp the basic ideas of object-oriented programming easily, whereas people who are more computer literate are often blocked by their own preconceptions. Alan Kay, for example, found that it was often easier to teach Smalltalk to children than to computer professionals [Kay 1977].
  • 44. 8 Chapter 1 H Thinking Object-Oriented kingdom Animalia phylum Mollusca Chordata class Gastropoda Reptilla Mammalia order Mesogastropoda Predentata genus species Cypraea Y tigris Triceratops horridus Primates family Cypraeidae Ceratopsidae Hominidae Homo i sapiens Figure 1.1-The Linnaen Inheritance Hierarchy In trying to understand exactly what is meant by the term object-oriented programming, it is useful to examine the idea from several perspectives. The next few sections outline two aspects of object-oriented programming; each illustrates a particular reason that this technique should be considered an important new tool. 1.4 □ A Way of Viewing the World To illustrate some of the major ideas in object-oriented programming, let us consider first how we might go about handling a real-world situation and then ask how we could make the computer more closely model the techniques employed. Suppose an individual named Chris wishes to send flowers to a friend named Robin, who lives in another city. Because of the distance, Chris cannot simply pick the flowers and take them to Robin in person. Nevertheless, it is a task that is easily solved. Chris simply walks to a nearby flower shop, run by a florist named Fred. Chris will tell Fred the kinds of flowers to send to Robin and the address to which they should be delivered. Chris can then be assured that the flowers will be delivered expediently and automatically.
  • 45. 1.4 A Way of Viewing the World 9 1 A. 1 Agents and communities At the risk of belaboring a point, let us emphasize that the mechanism that was used to solve this problem was to find an appropriate agent (namely, Fred) and to pass to this agent a message containing a request. It is the responsibility of Fred to satisfy the request. There is some method—some algorithm or set of operations—used by Fred to do this. Chris does not need to know the particular method that Fred will use to satisfy the request; indeed, often the person making a request does not want to know the details. This information is usually hidden from inspection. An investigation, however, might uncover the fact that Fred delivers a slightly different message to another florist in the city where Robin lives. That florist, in turn, perhaps has a subordinate who makes the flower arrangement. The florist then passes the flowers, along with yet another message, to a delivery person, and so on. Earlier, the florist in Robin’s city had obtained the flowers from a flower wholesaler who, in turn, had interactions with the flower growers, each of whom had to manage a team of gardeners. So, our first observation of object-oriented problem solving is that the solution to this problem required the help of many other individuals (Figure 1.2). Without their help, the problem could not be easily solved. We phrase this in a general fashion. An object-oriented program is structured as a community of interacting agents called objects. Each object has a role to play. Each object provides a service or performs an action that is used by other members of the community. Robin Chris Delivery Person Gardeners Grower Wholesaler H Figure 1.2-The community of agents in the flower delivery process
  • 46. 1 0 Chapter 1 □ Thinking Object-Oriented 1.4.2 Messages and methods The chain reaction that ultimately resulted in the solution to Chris’s problem began with a request given to the florist, Fred. This request lead to other requests, which lead to still more requests, until the flowers ultimately reached Chris’s friend, Robin. We see, therefore, that members of this community interact with each other by making requests. So, our next principle of object-oriented problem solving is the vehicle used to indicate an action to be performed. Action is initiated in object-oriented programming by the transmission of a message to an agent (an object) responsible for the action. The message encodes the request for an action and is accompanied by any additional information (arguments) needed to carry out the request. The receiver is the object to whom the message is sent. If the receiver accepts the message, it accepts the responsibility to carry out the indicated action. In response to a message, the receiver will perform some method to satisfy the request. We have noted the important principle of information hiding in regard to message passing—that is, the client sending the request need not know the actual means by which the request will be honored. There is another principle, all too human, that we see is implicit in message passing. If there is a task to perform, the first thought of the client is to find somebody else he or she can ask to do the work. This second reaction often becomes atrophied in many programmers with extensive experience in conventional techniques. Frequently, a difficult hurdle to overcome is the idea in the programmer’s mind that he or she must write everything and not use the services of others. An important part of object-oriented programming is the development of reusable components, and an important first step in the use of reusable components is a willingness to trust software written by others. Messages Versus Procedure Calls Information hiding is also an important aspect of programming in conventional languages. In what sense is a message different from, say, a procedure call? In both cases, there is a set of well-defined steps that will be initiated following the request. But there are two important distinctions. The first is that in a message there is a designated receiver for that message; the receiver is some object to which the message is sent. In a procedure call, there is no designated receiver. The second is that the interpretation of the message (that is, the method used to respond to the message) is determined by the receiver and can vary with different receivers. Chris could give a message to a friend named Elizabeth, for example, and she will understand it and a satisfactory outcome will be produced (that is.
  • 47. 1.4 A Way of Viewing the World 1 1 flowers will be delivered to their mutual friend Robin). However, the method Elizabeth uses to satisfy the request (in all likelihood, simply passing the request on to Fred) will be different from that used by Fred in response to the same request. If Chris were to ask Kenneth, a dentist, to send flowers to Robin, Kenneth may not have a method for solving that problem. If he understands the request at all, he will probably issue an appropriate error diagnostic. Fet us move our discussion back to the level of computers and programs. There, the distinction between message passing and procedure calling is that in message passing there is a designated receiver, and the interpretation—the selection of a method to execute in response to the message—may vary with different receivers. Usually, the specific receiver for any given message will not be known until run time, so the determination of which method to invoke cannot be made until then. Thus, we say there is late binding between the message (function or procedure name) and the code fragment (method) used to respond to the message. This situation is in contrast to the very early (compile-time or link-time) binding of name to code fragment in conventional procedure calls. 1.4.3 Responsibilities A fundamental concept in object-oriented programming is to describe behavior in terms of responsibilities. Chris’s request for action indicates only the desired outcome (flowers sent to Robin). Fred is free to pursue any technique that achieves the desired objective and in doing so will not be hampered by interference from Chris. By discussing a problem in terms of responsibilities we increase the level of abstraction. This permits greater independence between objects, a critical factor in solving complex problems. The entire collection of responsibilities associated with an object is often described by the term protocol. A traditional program often operates by acting on data structures—for exam¬ ple, changing fields in an array or record. In contrast, an object-oriented program requests data structures (that is, objects) to perform a service. This difference be¬ tween viewing software in traditional, structured terms and viewing it from an object-oriented perspective can be summarized by a twist on a well-known quote. Ask not what you can do to your data structures. Ask what your data structures can do for you. 1.4.4 Classes and instances Although Chris has only dealt with Fred a few times, Chris has a rough idea of the transaction that will occur inside Fred’s flower shop. Chris is able to make certain assumptions based on previous experience with other florists, and hence Chris can
  • 48. 1 2 Chapter 1 □ Thinking Object-Oriented expect that Fred, being an instance of this category, will fit the general pattern. We can use the term Florist to represent the category (or class) of all florists. Let us incorporate these notions into our next principle of object-oriented programming. All objects are instances of a class. The method invoked by an object in response to a message is determined by the class of the receiver. All objects of a given class use the same method in response to similar messages. 1.4.5 Class hierarchies—inheritance Chris has more information about Fred—not necessarily because Fred is a florist but because he is a shopkeeper. Chris knows, for example, that a transfer of money will be part of the transaction and that in return for payment Fred will offer a receipt. These actions are true of grocers, stationers, and other shopkeepers. Since the category Florist is a more specialized form of the category Shopkeeper, any knowledge Chris has of Shopkeepers is also true of Florists and, hence, of Fred. One way to think about how Chris has organized knowledge of Fred is in terms of a hierarchy of categories (see Figure 1.3). Fred is a Florist, but Florist is a specialized form of Shopkeeper. Furthermore, a Shopkeeper is also a Human; so Chris knows, for example, that Fred is probably bipedal. A Human is a Mammal (therefore, they nurse their young and have hair), a Mammal is an Animal (therefore, it breathes Figure 1.3-The categories surrounding Fred
  • 49. 1.4 A Way of Viewing the World 1 3 Material Objects Animal Mammal Plant Flower Carnation Fido Fred Elizabeth Kenneth Phyl Robin’s flowers H Figure 1.4-A class hierarchy for various material objects oxygen), and an Animal is a Material Object (therefore, it has mass and weight). Thus, quite a lot of knowledge that Chris has that is applicable to Fred is not directly associated with him, or even with the category Florist. The principle that knowledge of a more general category is also applicable to a more specific category is called inheritance. We say that the class Florist will inherit attributes of the class (or category) Shopkeeper. There is an alternative graphical technique often used to illustrate this rela¬ tionship, particularly when there are many individuals with differing lineages. This technique shows classes listed in a hierarchical treelike structure, with more abstract classes (such as Material Object or Animal) listed near the top of the tree and more specific classes, and finally individuals, listed near the bottom. Figure 1.4 shows this class hierarchy for Fred. This same hierarchy also includes Elizabeth; Chris’s dog, Fido; Phyl the platypus, who lives at the zoo; and the flowers Chris is sending to Robin. Notice that the structure and interpretation of this type of diagram is similar to the biological hierarchy presented in Figure 1.1. Any/information that Chris has about Fred because Fred is an instance of class Fluman is also applicable to Elizabeth. Any information that Chris has about Fred because Fred is a Mammal is applicable to Fido as well. Any information about
  • 50. 1 4 Chapter 1 □ Thinking Object-Oriented all members of Material Object is equally applicable to Fred and to his flowers. We capture this in the idea of inheritance. Classes can be organized into a hierarchical inheritance structure. A child class (or subclass) will inherit attributes from a parent class higher in the tree. An abstract parent class is a class (such as Mammal) for which there are no direct instances; it is used only to create subclasses. 1.4.6 Method binding and overriding Phyl the platypus presents a problem for our simple organizing structure. Chris knows that mammals give birth to live children, and Phyl is certainly a Mammal, yet Phyl (or rather his mate Phyllis) lays eggs. To accommodate this, we need to find a technique to encode exceptions to a general rule. We do this by decreeing that information contained in a subclass can override information inherited from a parent class. Most often, implementations of this approach take the form of a method in a subclass having the same name as a method in the parent class, combined with a rule for how the search for a method to match a specific message is conducted. The search for a method to invoke in response to a given message begins with the class of the receiver. If no appropriate method is found, the search is conducted in the parent class of this class. The search continues up the parent class chain until either a method is found or the parent class chain is exhausted. In the former case the method is executed; in the latter case, an error message is issued. If methods with the same name can be found higher in the class hierarchy, the method executed is said to override the inherited behavior. Even if a compiler cannot determine which method will be invoked at run time, in many object-oriented languages, such as Java, it can determine whether there will be an appropriate method and issue an error message as a compile-time error diagnostic rather than as a run-time message. The fact that both Elizabeth and Fred will react to Chris’s messages but use different methods to respond is one form of polymorphism. As explained, that Chris does not, and need not, know exactly what method Fred will use to honor the request is an example of information hiding. 1.4.7 Summary of object-oriented concepts Alan Kay, considered by some to be the father of object-oriented programming, identified the following characteristics as fundamental to OOP [Kay 1993]:
  • 51. 1.5 Computation as Simulation 15 1. Everything is an object. 2. Computation is performed by objects communicating with each other, re¬ questing that other objects perform actions. Objects communicate by sending and receiving messages. A message is a request for action bundled with what¬ ever arguments may be necessary to complete the task. 3. Each object has its own memory, which consists of other objects. 4. Every object is an instance of a class. A class simply represents a grouping of similar objects, such as integers or lists. 5. The class is the repository for behavior associated with an object. That is, all objects that are instances of the same class can perform the same actions. 6. Classes are organized into a singly rooted tree structure, called the inheri¬ tance hierarchy. Memory and behavior associated with instances of a class are automatically available to any class associated with a descendant in this tree structure. *1.5 □ Computation as Simulation The view of programming represented by the example of sending flowers to a friend is very different from the conventional conception of a computer. The traditional model describing the behavior of a computer executing a program is a process-state or pigeon-hole model. In this view, the computer is a data manager, following some pattern of instructions, wandering through memory, pulling values out of various slots (memory addresses), transforming them in some manner, and pushing the results back into other slots (see Figure 1.5). By examining the values in the slots, one can determine the state of the machine or the results produced by a computation. Although this model may be a more or less accurate picture of what takes place inside a computer, it does little to help us understand how to solve problems using the computer, and it is certainly not the way most people (pigeon handlers and postal workers excepted) go about solving problems. In contrast, in the object-oriented framework we never mention memory addresses, variables, assignments, or any of the conventional programming terms. Instead, we speak of objects, messages, and responsibility for some action. I quote Dan Ingalls’s memorable phrase. Instead of a bit-grinding processor . . . plundering data structures, we have a uruverse of well-behaved objects that courteously ask each other to carry out their various desires [Ingalls 1981].
  • 52. 1 6 Chapter 1 □ Thinking Object-Oriented Figure 1.5-Visualization of imperative programming. Another author has described object-oriented programming as “animistic”: a process of creating a host of helpers that form a community and assist the programmer in the solution of a problem [Actor 1987]. This view of programming as creating a “universe” is in many ways similar to a style of computer simulation called “discrete event-driven simulation.” In brief, in a discrete event-driven simulation the user creates computer models of the various elements of the simulation, describes how they will interact with one another, and sets them moving. This is almost identical to the average object- oriented program, in which the user describes what the various entities in the universe for the program are and how they will interact with one another, and then finally sets them in motion. Thus, in object-oriented programming, we have the view that computation is simulation [Kay 1977]. 1.5.1 The power of metaphor An easily overlooked benefit to the use of object-oriented techniques is the power of metaphor. When programmers think about problems in terms of behaviors and responsibilities of objects, they bring with them a wealth of intuition, ideas, and understanding from their everyday experiences. When envisioned as pigeon holes, mailboxes, or slots containing values, there is little in the programmer’s background to provide insight into how problems should be structured. Although anthropomorphic descriptions such as the quote by Ingalls may strike some people as odd, in fact they are a reflection of the great expositive power of metaphor. Journalists make use of metaphor every day, as in this description of object-oriented programming from Newsweek (Figure 1.6). Unlike the usual programming method—writing software one line at a time—NeXT’s “object-oriented” system offers larger building blocks that
  • 53. 1.5 Computation as Simulation 17 0 Figure 1.6-Mr. Potato Head, an object-oriented toy (Hasbro, Inc.) developers can quickly assemble the way a kid builds faces on Mr. Potato Head. Possibly this feature, more than any other, is responsible for the frequent obser¬ vation that it is sometimes easier to teach object-oriented programming concepts to computer novices than to computer professionals. Novice users quickly adapt the metaphors with which they are already comfortable from their everyday life, whereas seasoned computer professionals can be blinded by an adherence to more traditional ways of viewing computation. 1.5.2 Avoiding infinite regression Of course, objects cannot always respond to a message by politely asking another object to perform some action. The result would be an infinite circle of requests, like two gentlemen politely waiting for the other to go first before entering a doorway, or like a bureaucracy of paper pushers, each passing on all papers to some other member of the organization. At some point, at least a few objects need to perfqrm some work besides passing on requests to other agents. This work is accomplished differently in various object-oriented languages.
  • 54. 1 8 Chapter 1 h Thinking Object-Oriented In blended object-oriented/imperative languages, such as C++, Object Pascal, and Objective-C, it is accomplished by methods written in the base (non-object- oriented) language. In more purely object-oriented languages, such as Smalltalk or Java, it is accomplished by “primitive” or “native” operations that are provided by the underlying system. * 1.6 □ A Brief History It is commonly thought that object-oriented programming is a relatively recent phenomenon in computer science. To the contrary, in fact, almost all the major concepts we now associate with object-oriented programs, such as objects, classes, and inheritance hierarchies, were developed in the 1960s as part of a language called Simula, designed by researchers at the Norwegian Computing Center. Simula, as the name suggests, was a language inspired by problems involving the simulation of real life systems. However, the importance of these constructs, even to the developers of Simula, was only slowly recognized [Nygaard 1981]. In the 1970s Alan Kay organized a research group at Xerox PARC (the Palo Alto Research Center). With great prescience, Kay predicated the coming revo¬ lution in personal computing that was to develop nearly a decade later (see, for example, his 1977 article in Scientific American [Kay 1977]). Kay was concerned with discovering a programming language that would be understandable to non¬ computer professionals, to ordinary people with no prior training in computer use.^ He found in the notion of classes and computing as simulation a metaphor that could easily be understood by novice users, as he then demonstrated by a series of experiments conducted at PARC using children as programmers. The programming language developed by his group was named Smalltalk. This lan¬ guage evolved through several revisions during the decade. A widely read 1981 issue of Byte magazine did much to popularize the concepts developed by Kay and his team at Xerox. Roughly contemporaneous with Kay’s work was another project being con¬ ducted on the other side of the country. Bjarne Stroustrup, a researcher at Bell Laboratories who had learned Simula while completing his doctorate at Cam¬ bridge University in England, was developing an extension to the C language that would facilitate the creation of objects and classes [Stroustrup 1982]. This was to eventually evolve into the language C++ [Stroustrup 1994]. 1. I have always found it ironic that Kay missed an important point. He thought that to use a computer one would be required to program a computer. Although he correctly predicted in 1977 the coming trend in hardware, few could have predicted at that time the rapid development of general purpose computer applications that was to accompany, perhaps even drive, the introduction of personal computers. Nowadays the vast majority of people who use personal computers have no idea how to program.
  • 55. Discovering Diverse Content Through Random Scribd Documents
  • 59. The Project Gutenberg eBook of The Adventurers
  • 60. This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this ebook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. Title: The Adventurers Author: Gustave Aimard Translator: Sir Lascelles Wraxall Release date: September 14, 2013 [eBook #43716] Most recently updated: October 23, 2024 Language: English Credits: Produced by Marc D'Hooghe *** START OF THE PROJECT GUTENBERG EBOOK THE ADVENTURERS ***
  • 61. THE ADVENTURERS A Story of a Love-Chase BY
  • 62. GUSTAVE AIMARD AUTHOR OF "LAST OF THE INCAS," "QUEEN OF THE SAVANNAH," ETC. LONDON WARD AND LOCK, 158, FLEET STREET. 1863. PREFACE. With the publication of the present and the ensuing volume, "The Pearl of the Andes," I am enabled to perfect the most important series of Aimard's Tales of Indian Life and Adventure. To preserve uniformity, the volumes of this series should be arranged in the following order on the book-shelf;— 1. THE ADVENTURERS. 2. THE PEARL OF THE ANDES. 3. THE TRAIL-HUNTER. 4. PIRATES OF THE PRAIRIES. 5. THE TRAPPER'S BRIDE. 6. THE TIGER SLAYER. 7. THE GOLD SEEKERS. 8. THE INDIAN CHIEF. 9. THE RED TRACK.
  • 63. Gustave Aimard has a precedent in Fenimore Cooper for introducing the same hero in a long range of volumes, and, like his great predecessor, he has so arranged, that each work should be complete in itself, and not necessitate the purchase of another. But Aimard has one marked advantage over Cooper; for while "Leather-Stocking" is but a creation of the fancy, or, at the most, the type of the Backwoodsman, the Count Louis who figures as the hero of Aimard's series, is a real man. Count de Raousset Boulbon, had he succeeded in his daring attempt of founding an independent kingdom in Mexico, would in all probability have become the Napoleon of the West. A gallant adventurer and thorough gentleman, he staked his life upon the issue, and ended his career the victim of unparalleled treachery, as Aimard has faithfully recorded. Hence Aimard's romances have the great merit of being founded on an historic basis, and but little fiction was required to heighten the startling interest of the narrative. Valentine Guillois, there is very little doubt, is intended for the Author himself, with all his qualities and defects. When he first reached the New World, he was the true, reckless Parisian; but constant intercourse with nature rendered him a generous and thoughtful friend of humanity. So soon as he returned to civilization, he began recording the history of his past life; not so much as a livelihood, as for the pleasure he felt in living once again the life of excitement and adventure which he had known among the Indians. Hence his books are written without an effort; they flow spontaneously from his pen; and the absence of artistic effect is the best guarantee of their truthfulness. It is not surprising, consequently, that M. Aimard's books have met with such extensive popularity. They have been translated into nearly every modern language, and the Author is now generally recognised as the French Cooper. The reception given to his stories in this country has been most flattering, and each day heightens their popularity. Hence it is not too much to assume that they will become standard works, especially with young readers, for whom they are especially adapted; because M. Aimard has never yet written a line which could prove offensive to the most delicate mind. L .W.
  • 64. CONTENTS. I.THE CHAPARRAL II.THE FOSTER BROTHERS III.THE RESOLUTION IV.THE EXECUTION V.THE PASSAGE VI.THE LINDA VII.HUSBAND AND WIFE VIII.THE DARK-HEARTS IX.IN THE STREET X.SWORD-THRUSTS XI.GENERAL BUSTAMENTE XII.THE SPY XIII.LOVE XIV.THE QUINTA VERDE XV.THE DEPARTURE XVI.THE MEETING XVII.THE PUELCHES XVIII.THE BLACK JACKAL XIX.TWO OLD FRIENDS XX.THE SORCERER XXI.THE OBSEQUIES OF AN APO-ULMEN XXII.EXPLANATIONS XXIII.THE CHINGANA XXIV.THE TWO ULMENS XXV.THE SUN-TIGER XXVI.THE MATRICIDE XXVII.THE JUSTICE OF THE DARK-HEARTS XXVIII.THE TREATY OF PEACE XXIX.THE ABDUCTION XXX.THE PROTEST XXXI.SPANIARD AND INDIAN XXXII.IN THE MOUNTAIN XXXIII.ON THE WATCH XXXIV.FACE TO FACE XXXV.THE REVOLT XXXVI.THE LION AT BAY
  • 65. XXXVII.THE TRUCE XXXVIII.TWO ROGUISH PROFILES XXXIX.THE WOUNDED MAN XL.ARAUCANIAN DIPLOMACY XLI.THE COUNCIL XLII.THE NIGHT JOURNEY XLIII.TWO HATREDS XLIV.THE RETURN TO VALDIVIA XLV.THE FATHER REVEALS HIMSELF XLVI.CURUMILLA CHAPTER I. THE CHAPARRAL. During my last sojourn in America, chance, or rather my good star, led me to form an acquaintance with one of those hunters, or wood rangers, the type of whom has been immortalized by Cooper, in his poetical personage, Leather-Stockings. The strange circumstance by which we were brought together was as follows. Towards the end of July, 1855, I had left Galveston, terrified at the fevers prevalent there, which are so fatal to Europeans, with the intention of visiting the north-west portion of Texas, a country I was then unacquainted with. A Spanish proverb somewhere says, "It is better to go alone than in bad company;" and, like all other proverbs, this possesses a certain foundation of truth, particularly in America, where the traveller is exposed at each instant to the chance of meeting rogues of every hue, who, thanks to their seducing exterior, charm him, win his confidence, and take advantage of the first occasion to remorselessly plunder and assassinate him. I had profited by the proverb, and, like a shrewd old traveller of the prairies, as I knew no one who inspired me with sufficient sympathy to lead me to make him my travelling companion, I had bravely set out
  • 66. alone, clothed in the picturesque dress of the inhabitants of the country, armed to the teeth, and mounted upon an excellent half wild horse, which had cost me twenty-five piastres—an enormous sum in those countries, where horses are considered as worth little or nothing. I carelessly wandered here and there, living that nomadic life which is so full of attractions; at times stopping at a toldería, at others encamping in the desert, hunting wild animals, and plunging deeper and deeper into unknown regions. I had, in this fashion, passed through, without any untoward accident, Fredericksburgh, the Llana Braunfels, and had just left Castroville, on my way to Quichi. Like all Spanish-American villages, Castroville is nothing but a miserable agglomeration of ruined cabins, cut at right angles by streets choked with weeds, growing undisturbed, and concealing multitudes of ants, reptiles, and even rabbits of a very small breed, which spring up beneath the feet of the few passengers. The pueblo is bounded on the west by the Medina, a slender thread of water, almost dry in the great heat seasons; and on the east by thickly- wooded hills, the dark green of which forms a pleasing contrast with the pale blue of the sky. At Galveston I had undertaken to deliver a letter to an inhabitant of Castroville. The worthy man lived in this village like La Fontaine's rat in the depths of its Dutch cheese. Charmed by the arrival of a stranger, who, no doubt, brought him news for which he had been long anxious, he received me in the most cordial manner, and thought of every expedient to detain me. Unfortunately, the little I had seen of Castroville had sufficed to completely disgust me with it, and my only wish was to get out of it as quickly as possible. My host, in despair at seeing all his advances repulsed, at length consented to allow me to continue my journey. "Adieu, then," he said, warmly pressing my hand, with a sigh of regret; "since you are determined to go, may God protect you! You are wrong in setting out so late; the road you have to travel is dangerous; the Indios bravos are up; they assassinate without mercy all the whites who fall into their hands—beware!" I smiled at this warning, which I took for a last effort of the worthy man to detain me.
  • 67. "Bah!" I replied gaily; "the Indians and I are too old acquaintances for me to fear anything on their account." My host shook his head sorrowfully, and retreated into his hut, making me a last farewell greeting. I again set forward. I soon began to reflect that it was full late, and pressed my horse, in order to pass, before nightfall, a chaparral, or large thicket of underwood, of at least two miles in length, against which my host had particularly warned me. This ill-famed spot had a very sinister aspect. The mezquite, the acacia, and the cactus constituted its sole vegetation, while here and there, whitened bones and planted crosses plainly designated places where murders had been committed. Beyond that extended a vast plain, called the Leona, peopled by animals of every description. This plain, covered by grass at least two feet in height, was dotted at intervals with thickets of trees, upon which warbled thousands of golden-throated starlings, cardinals, and bluebirds. I was anxious to reach the Leona, which I saw in the distance; but ere I did so, I had to cross the chaparral. After examining my weapons, and looking carefully in all directions, as I could perceive nothing positively suspicious, I resolutely spurred my horse forward, determined, if attacked, to sell my life as dearly as possible. The sun, in the meantime, was sinking rapidly towards the horizon, the ruddy hues of closing day tinged with their changing reflections the summits of the wooded hills, and a fresh breeze agitated the branches of the trees with mysterious murmurs. In this country, where there is no twilight, night was not long in enveloping me in thick darkness, and that before I had passed through two-thirds of the chaparral. I was beginning to hope I should reach the Leona safe and sound, when, all at once, my horse made a violent bound on one side, pricking up its ears, and snorting loudly. The sudden shock almost threw me out of the saddle, and it was not without trouble that I recovered the mastery over my horse, which displayed signs of the greatest terror. As always happens in such cases, I instinctively looked round me for the cause of this panic; and soon the truth was revealed to me. A cold perspiration bedewed my brow, and a shudder of terror ran through my whole frame, at the horrible spectacle which met my eyes. Five dead human bodies lay stretched beneath the trees, within ten paces of me. Among them was one of a woman, and one of a girl about fourteen
  • 68. years of age. They all belonged to the white race. They appeared to have fought long and obstinately before they fell; they were literally covered with wounds; and long arrows, with jagged barbs, and painted red, stood out from the bodies, which they had pierced through and through. The victims had all been scalped. It was evidently the work of Indians, marked with their sanguinary rage, and their inveterate hatred for the white race. The form and colour of the arrows told me that the perpetrators of this atrocity were the Apaches, the most cruel plunderers of the desert. Around the bodies I observed fragments of both wagons and furniture. The unfortunate beings, assassinated with refined cruelty, had, no doubt, been poor emigrants on their way to Castroville. At the aspect of this heartbreaking spectacle, I cannot express the pity and grief which weighed upon my spirits; high in the air, urubus and vultures hovered with lazy wings over the bodies, uttering lugubrious cries of joy, whilst in the depths of the chaparral the wolves and jaguars began to growl portentously. I cast a melancholy glance around: all immediately near to me was quiet. The Apaches had, according to all appearances, surprised the emigrants during a halt. Gutted bales were still ranged in a symmetrical circle, and a fire, near which was a heap of dry wood, was not yet extinguished. "No!" said I to myself, "whatever may happen, I will not leave Christians without burial, to become, in this desert, the prey of wild beasts." My resolution, once formed, was soon carried into execution. Springing to the ground, I hobbled my horse, gave it some provender, and cast some branches of wood upon the fire, which soon sparkled and sent into the air a column of bright flame. Among the necessaries of the emigrants were spades, pickaxes, and other agricultural instruments, which, being of no use to the Indians, they had disdainfully left behind them. I seized a spade, and, after having carefully explored the environs of my encampment, to assure myself that no immediate danger need be apprehended, I set to work to dig a grave. The night had now set in; one of those American nights, clear, silent, full of intoxicating odours, and mysterious melodies chanted by the desert in praise of God. Extraordinary to say, all my fears had vanished, as if by
  • 69. enchantment! Though alone in this sinister place, close to these frightfully-mutilated carcasses, watched in the darkness, no doubt, by the unseen eyes of wild beasts, and, perhaps, of the murderous Indians, some incomprehensible influence sustained me, and gave me strength to accomplish the rude but sacred task I had undertaken. Instead of thinking of the dangers which surrounded me, I found myself yielding to a pensive melancholy. I thought of these poor people, who had come from distant lands, full of hope for the future, to seek in the New World a little of the comfort and well-being which were denied to them at home, and who, scarcely landed, had fallen, in an obscure corner of the desert, by the hands of ferocious savages. They had left in their own country friends, perhaps relations, to whom their fate would for ever remain a mystery, and who would for years reckon the hours with anxiety, looking for their much-wished return, or for intelligence of their success in their bold undertaking. Except two or three alarms caused by the rustling of the leaves in the bushes, nothing occurred to interrupt my melancholy duty. In less than three-quarters of an hour I had dug a grave large enough to contain the five bodies. After extracting the arrows by which they were transfixed, I raised them one after the other in my arms, and laid them gently side by side at the bottom of the grave. I then hastened to throw in the mould again, till it was level with the sod; and that being done, I dragged upon the surface all the large stones I could find, to keep wild beasts from profaning the dead. This religious duty accomplished, I breathed a deep sigh of satisfaction, and bowing my head towards the ground, I mentally addressed a short prayer to the Almighty, for the unfortunate beings I had buried. Upon raising my head, I uttered a cry of surprise and terror, while at the same time mechanically feeling for my revolver; for, without the least noise having given me warning of his approach, a man was standing within four paces of me, watching me earnestly, and leaning on his long rifle. Two magnificent Newfoundland dogs were lying carelessly but quietly at his feet. On observing my gesture, the unknown smiled with a kindly expression, and holding out his hand to me over the grave, said— "Fear nothing! I am a friend. You have buried these poor people; I have avenged them—their assassins are dead!"
  • 70. I silently pressed the hand that was so frankly extended to me. Acquaintance was formed—we were friends—we are so still! A few minutes later we were seated near the fire, supping together with a good appetite, while the dogs kept watch against intruders. The companion I had fallen in with in so curious a manner was a man of about forty-five years of age, although he did not appear to be more than thirty-two. He was tall and well made; his broad shoulders and muscular limbs denoting extraordinary strength and agility. He wore the picturesque hunter's costume in all its purity, that is to say, the capote, or surtout (which is nothing but a kind of blanket worn as a robe, fastened to the shoulders, and falling in long folds behind), a shirt of striped cotton, large mitasses (drawers of doeskin, stitched with hair, fastened at distances, and ornamented with little bells), leather gaiters, moccasins of elk skin, braided with beads and porcupine quills, and a checked woollen belt, from which hung his knife, tobacco pouch, powder horn, pistols, and medicine bag. His headdress consisted of a cap made of the skin of a beaver, the tail of which fell between his shoulders. This man was a type of a hardy race of adventurers who traverse America in all directions. A primitive race, longing for open air, space, and liberty, opposed to our ideas of civilization, and consequently destined to disappear before the immigration of the laborious races, whose powerful agents of conquest are steam and the application of mechanical inventions of all kinds. This hunter was a Frenchman, and his frank, manly countenance, his picturesque language, his open and engaging manners, notwithstanding his long abode in America, had preserved a reflex of the mother country which awakened sympathy and created interest. All the countries of the New World were familiar to him; he had lived more than twenty years in the depths of the woods, and had been engaged in dangerous and distant excursions among the Indian tribes. Hence, although myself well initiated in the customs of the redskins, and though a great part of my existence had been passed in the desert, I have felt myself often shudder involuntarily at the recital of his adventures. When seated beside him on the banks of the Rio Gila, during an excursion we had undertaken into the prairies, he would at times allow himself to be carried away by his remembrances, and relate
  • 71. to me, as he smoked his Indian pipe, the strange history of the early days of his abode in the New World. It is one of these recitals I am about to lay before my readers—the first in order of date, since it is the history of the events which led him to become a wood ranger. I do not venture to hope that my readers will take the interest in it which it excited in me; but I beg them to have the kindness to recollect that this narrative was told me in the desert, amidst that grand, vast, and powerful nature, unknown to the inhabitants of old Europe, and that I had it from the lips of the man who had been the hero. CHAPTER II. THE FOSTER BROTHERS. On the 31st of December, 1834, at eleven o'clock in the evening, a man of about twenty-five years of age, of handsome person and countenance, and aristocratic appearance, was sitting, or rather reclining, in a luxurious easy chair, near the mantelpiece, within which sparkled a fire that the advanced season rendered indispensable. This personage was the Count Maxime Edouard Louis de Prébois-Crancé. His countenance, of a cadaverous paleness, formed a striking contrast with his black curly hair, which fell in disorder upon his shoulders, covered by a large-patterned damask dressing gown. His brows were contracted, and his eyes were fixed with feverish impatience upon the dial of a charming Louis Quinze clock, whilst his left hand, hanging carelessly by his side, played with the silky ears of a magnificent Newfoundland dog which lay by his side. The room in which the Count was sitting was furnished with all the refinement of comfort invented by modern luxury. A four-branched chandelier, with rose-coloured wax candles, placed upon a table, was scarcely sufficient to enliven the room, and only spread around a dim, uncertain light. Without, the rain was dashing against the windows violently; and the wind sighed in mysterious murmurs, which disposed the mind to melancholy. When the clock struck the hour the Count started up, as if aroused from a dream. He
  • 72. passed his thin white hand across his moist brow, and said, in a dissatisfied tone— "He will not come!" But at that moment the dog, which had been so motionless, sprang up and bounded towards the door, wagging its tail with joy. The door opened, the portière was lifted by a firm hand, and a man appeared. "Here you are at last!" the Count exclaimed, advancing towards the newcomer, who had great trouble to get rid of the caresses of the dog. "I had begun to be afraid that you, like the rest, had forgotten me." "I do not understand you, brother, but trust you will explain yourself," the other replied. "Come, that will do, Cæsar; lie down! you are a very good dog, but lie down!" And drawing an easy chair towards the fire, he sat down at the other side of the fire, in front of the Count, who had resumed his place. The dog lay down between them. The personage so anxiously expected by the Count formed a strange contrast with him; for, just as M. de Prébois-Crancé united in himself all the qualities which physically distinguish nobility of race, the other displayed all the lively, energetic strength of a true child of the people. He was a man of twenty-six years of age; tall, thin, and perfectly well proportioned; while his face, bronzed by the sun, and his marked features, lit up by blue eyes sparkling with intelligence, wore an expression of bravery, mildness, and loyalty of character that created sympathy at first sight. He was dressed in the elegant uniform of a quartermaster sergeant of the Spahis, and the cross of the legion of honour glittered on his breast. With his head leaning on his right hand, a pensive brow and a thoughtful eye, he examined his friend attentively, whilst twisting his long, silky light-coloured moustache with the other hand. The Count, shrinking before his earnest look, which appeared trying to read his most secret thoughts, broke the silence abruptly. "You have been a long time in responding to my message," he said. "This is the second time you have addressed that reproach to me, Louis," the soldier replied, taking a paper from his breast; "you forget
  • 73. the terms of the note which your groom brought yesterday to my quarters." And he was preparing to read. "It is useless to read it," said the Count, with a melancholy smile. "I acknowledge I am in the wrong." "Well, then, let us see," said the Spahi gaily, "what this serious affair is which makes you stand in need of me. Explain: is there a woman to be carried off?—Have you a duel on hand?—Tell me." "Nothing that you can possibly imagine," the Count interrupted him bitterly; "therefore do not waste time in useless surmises." "What the devil is it, then?" "I am going to blow out my brains." The young man uttered these words with so firm and resolute an accent, that the soldier started in spite of himself, and bent an anxious glance upon the speaker. "You believe me mad, do you not?" the Count continued, who guessed his friend's thoughts. "No, I am not mad, Valentine; I am only at the bottom of an abyss from which I can only escape by death or infamy, and I prefer death." The soldier made no reply. With an energetic gesture he pushed back his chair, and began to walk about the room with hurried steps. The Count had allowed his head to sink upon his breast in a state of perfect prostration of mind. After a long silence, during which the fury of the storm without increased, Valentine resumed his seat. "A very strong reason must have obliged you to take such a determination," he said coolly; "I will not endeavour to combat it; but I command you, by our friendship, to tell me fully what has led you to form it. I am your foster brother, Louis; we have grown up together; our ideas have been too long in common, our friendship is too strong and too fervent for you to refuse to satisfy me." "To what purpose?" cried the Count, impatiently; "my sorrows are of a nature which none but he who experiences them can comprehend."
  • 74. "A bad pretext, brother," replied the soldier, in a rough tone; "the sorrows we dare not avow are of a kind that make us blush." "Valentine," said the Count, with a flashing eye, "it is ill judged to speak so." "On the contrary, it is quite right," replied the young man, warmly. "I love you, I owe you the truth; why should I deceive you? No, you know my frankness; therefore do not hope that I shall listen to you with my eyes shut. If you want to be flattered in your last moments, why send for me? Is it to applaud your death? If so, brother, farewell! I will retire, for I have nothing to do here. You great gentlemen, who have only known the trouble of coming into the world, know nothing of life but its joys; at the first roseleaf which chance happens to ruffle in your bed of happiness, you think yourselves lost, and appeal to that greatest of all cowardices, suicide." "Valentine!" the Count cried angrily. "Yes," continued the young man, with increased energy, "I repeat, that supreme cowardice! Man is no more at liberty to quit life when he fancies he is tired of it, than the soldier is to quit his post when he comes face to face with his country's enemy. Your sorrows, indeed! I know well what they are." "You know?" demanded the Count with astonishment. "All—listen to me; and when I have told you my thoughts, why, kill yourself if you like. Pardieu! do you think when I came here I did not know why you summoned me? A gladiator, far too weak to fight the good fight, you have cast yourself defencelessly among the wild beasts of this terrible arena called Paris—and you have fallen, as was sure to be the case. But remember, the death you contemplate will complete your dishonour in the eyes of all, instead of reinstating you or surrounding you with the halo of false glory you are ambitious of." "Valentine! Valentine!" cried the Count, striking the table forcibly with his clenched hand, "what gives you a right to speak to me thus?" "My friendship," the soldier replied, energetically, "and the position you have yourself placed me in by sending for me. Two causes reduce you to despair. These two causes are, in the first place, your love for a
  • 75. coquettish woman, a Creole, who has played with your heart as the panther of her own savannahs plays with the inoffensive animals she is preparing to devour.—Is that true?" The young man made no reply. With his elbows on the table, his face buried in his hands, he remained motionless, apparently insensible to the reproaches of his foster brother. Valentine continued— "Secondly, when, in order to win favour in her eyes, you have compromised your fortune, and squandered all that your father had left you, this woman flits away as she came, rejoicing over the mischief she has done, over the victims she has left on the path she has trod, leaving to you and to so many others the despair and the shame of having been the sport of a coquette. What urges you to seek refuge in death is not the loss of fortune, but the impossibility of following this woman, the sole cause of all your misfortunes. I defy you to contradict me." "Well, I admit all that is true. It is that alone which kills me. What care I for the loss of fortune? She alone is the object of my ambition! I love her—I love her—I tell you, so that I could struggle against the whole world to obtain her!" the young man exclaimed with great excitement. "Oh, if I could but hope! Hope—a word void of meaning, invented by the ambitious, always implying something unattainable! Do you not plainly see the truth of what I say? There is nothing left me but to die!" Valentine contemplated him for some minutes with a sad countenance. Suddenly his brow cleared, his eye sparkled; he laid his hand upon the Count's shoulder. "Is this, then, more than a caprice? Do you really love this woman?" he said. "Have I not told you that I am ready to die for her?" "Ay; and you told me at the same time that you would struggle with the whole world to obtain her." "I did—and would." "Well, then," continued Valentine, fixing his eyes earnestly upon him, "I can help you to find this woman again—I can." "You can?"
  • 76. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com