100% found this document useful (1 vote)
11 views

Object Oriented Programming Languages And Eventdriven Programming Dorian P Yeager instant download

The document discusses 'Object-Oriented Programming Languages and Event-Driven Programming' by Dorian P. Yeager, covering key concepts such as data abstraction, inheritance, and polymorphism. It includes a detailed examination of programming paradigms, event-driven programming, and specific languages like Smalltalk and Java. Additionally, it outlines licensing terms, publisher information, and the structure of the book, including chapters and topics covered.

Uploaded by

cariogajicd2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
11 views

Object Oriented Programming Languages And Eventdriven Programming Dorian P Yeager instant download

The document discusses 'Object-Oriented Programming Languages and Event-Driven Programming' by Dorian P. Yeager, covering key concepts such as data abstraction, inheritance, and polymorphism. It includes a detailed examination of programming paradigms, event-driven programming, and specific languages like Smalltalk and Java. Additionally, it outlines licensing terms, publisher information, and the structure of the book, including chapters and topics covered.

Uploaded by

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

Object Oriented Programming Languages And

Eventdriven Programming Dorian P Yeager download

https://ebookbell.com/product/object-oriented-programming-
languages-and-eventdriven-programming-dorian-p-yeager-42253260

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.

Objectoriented Programming Languages And Eventdriven Programming


Dorian P Yeager

https://ebookbell.com/product/objectoriented-programming-languages-
and-eventdriven-programming-dorian-p-yeager-5226670

Object Oriented Programming Languages And Eventdriven Programming


Dorian P Yeager

https://ebookbell.com/product/object-oriented-programming-languages-
and-eventdriven-programming-dorian-p-yeager-42252990

Object Oriented Programming Languages And Eventdriven Programming


Dorian P Yeager

https://ebookbell.com/product/object-oriented-programming-languages-
and-eventdriven-programming-dorian-p-yeager-43143164

Object Oriented Programming Languages And Eventdriven Programming


Dorian P Yeager

https://ebookbell.com/product/object-oriented-programming-languages-
and-eventdriven-programming-dorian-p-yeager-42252604
Objectoriented Programming Languages And Eventdriven Programming
Yeager

https://ebookbell.com/product/objectoriented-programming-languages-
and-eventdriven-programming-yeager-232074700

Concepts And Semantics Of Programming Languages 2 Modular And


Objectoriented Constructs With Ocaml Python C Ada And Java 1st Edition
Therese Hardin

https://ebookbell.com/product/concepts-and-semantics-of-programming-
languages-2-modular-and-objectoriented-constructs-with-ocaml-python-c-
ada-and-java-1st-edition-therese-hardin-34071910

Objectoriented Programming Languages Interpretation Iain D Craig

https://ebookbell.com/product/objectoriented-programming-languages-
interpretation-iain-d-craig-2095070

Objectoriented Programming Languages Iain D Craig

https://ebookbell.com/product/objectoriented-programming-languages-
iain-d-craig-46201296

The Interpretation Of Objectoriented Programming Languages 2nd Edition


Iain Craig Ma

https://ebookbell.com/product/the-interpretation-of-objectoriented-
programming-languages-2nd-edition-iain-craig-ma-4199548
O -O
P L
A
E -D P
LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED
WARRANTY

By purchasing or using this book (the “Work”), you agree that this
license grants permission to use the contents contained herein, but
does not give you the right of ownership to any of the textual content
in the book or ownership to any of the information or products
contained in it. This license does not permit uploading of the Work
onto the Internet or on a network (of any kind) without the written
consent of the Publisher. Duplication or dissemination of any text,
code, simulations, images, etc. contained herein is limited to and
subject to licensing terms for the respective products, and
permission must be obtained from the Publisher or the owner of the
content, etc., in order to reproduce or network any portion of the
textual material (in any media) that is contained in the Work.
M L A I LLC (“MLI” or “the
Publisher”) and anyone involved in the creation, writing, or
production of the companion disc, accompanying algorithms, code,
or computer programs (“the software”), and any accompanying Web
site or software of the Work, cannot and do not warrant the
performance or results that might be obtained by using the contents
of the Work. The author, developers, and the Publisher have used
their best efforts to insure the accuracy and functionality of the
textual material and/or programs contained in this package; we,
however, make no warranty of any kind, express or implied,
regarding the performance of these contents or programs. The Work
is sold “as is” without warranty (except for defective materials used
in manufacturing the book or due to faulty workmanship).
The author, developers, and the publisher of any accompanying
content, and anyone involved in the composition, production, and
manufacturing of this work will not be liable for damages of any kind
arising out of the use of (or the inability to use) the algorithms,
source code, computer programs, or textual material contained in
this publication. This includes, but is not limited to, loss of revenue
or profit, or other incidental, physical, or consequential damages
arising out of the use of this Work.
The sole remedy in the event of a claim of any kind is expressly
limited to replacement of the book, and only at the discretion of the
Publisher. The use of “implied warranty” and certain “exclusions”
vary from state to state, and might not apply to the purchaser of this
product.
O -O
P L
A
E -D P

Dorian P. Yeager
Copyright ©2014 by Mercury Learning and Information LLC. All
rights reserved.

This publication, portions of it, or any accompanying software may


not be reproduced in any way, stored in a retrieval system of any
type, or transmitted by any means, media, electronic display or
mechanical display, including, but not limited to, photocopy,
recording, Internet postings, or scanning, without prior permission in
writing from the publisher.

Publisher: David Pallai


M L I
22841 Quicksilver Drive
Dulles, VA 20166
[email protected]
www.merclearning.com
1-800-758-3756

This book is printed on acid-free paper.

Dorian P. Yeager, Object-Oriented Programming Languages and


Event-Driven Programming.
ISBN: 978-1-936420-37-7

The publisher recognizes and respects all marks used by


companies, manufacturers, and developers as a means to
distinguish their products. All brand names and product names
mentioned in this book are trademarks or service marks of their
respective companies. Any omission or misuse (of any kind) of
service marks or trademarks, etc. is not an attempt to infringe on
the property of others.

Library of Congress Control Number: 2012952666

131415321 Printed in the United States of America


This book is printed on acid-free paper.
Our titles are available for adoption, license, or bulk purchase by
institutions, corporations, etc. For additional information, please
contact the Customer Service Dept. at 1-800-758-3756 (toll free).

The sole obligation of Mercury Learning and Information to the


purchaser is to replace the book and/or disc, based on defective
materials or faulty workmanship, but not based on the operation or
functionality of the product.
CONTENTS

Preface
Acknowledgments

Chapter 1 A Context-Sensitive Introduction


1.1 What Is Object-Oriented Programming?
1.1.1 Data Abstraction and Information Hiding
1.1.2 Inheritance
1.1.3 Polymorphism
1.1.4 Related Concepts—Overloading and Generic
Programming
1.2 Alternative Language Paradigms
1.2.1 Introduction—Some Basic Terminology
1.2.2 The Imperative Programming Paradigm
1.2.3 Procedural Programming Languages
1.2.4 Functional Programming Languages
1.2.5 Modular Programming Languages
1.2.6 Declarative Programming Languages
1.3 Relevant Programming Language Concepts
1.3.1 Abstraction
1.3.2 Syntax and Semantics
1.3.3 Target Machines
1.3.4 The Semantic Mapping, Parsing, and Syntactic
Discontinuities
1.3.5 Binding Times and Translation Strategies
1.3.6 Storage Classes and Storage Management
1.3.7 Dealing with Garbage
1.3.8 Scope, Visibility, Accessibility, and Lifetime
1.3.9 Types, Type Checking, and Type Transfers
1.3.10 Uninitialized Variables and Existence Checking
1.3.11 Pointer Semantics versus Value Semantics
1.3.12 Parameter Passing Mechanisms
1.3.13 Aliasing
1.3.14 I/O and the External Environment
1.3.15 Exception Handling
1.3.16 Threading
1.4 Simula 67 and its Historical Significance
1.4.1 Generalizing the Procedure Call
1.4.2 Inheritance in Simula
1.4.3 Coroutines
1.5 Setting the Stage: Object-Oriented Terminology
1.6 Summary

Chapter 2 Event-Driven Programming


2.1 Basic Definitions
2.2 The Hardware Model: Interrupts and Interrupt Handlers
2.3 Operating System Support
2.4 Callback Functions
2.5 Object-Oriented Models for EDP
2.6 An Example of an Event and its Lifetime
2.7 Programming in an Object-Oriented Windowing Environment
2.7.1 Bitmapped Graphics Displays
2.7.2 Partitioning the Display
2.7.3 Mice, Cursors, and the “Focus”
2.8 Two-Stage View Creation
2.9 A Warning about Code Generators
2.10 Generic Graphics Overview
2.11 Primitive Events and their Handlers
2.11.1 Mouse Events
2.11.2 Keyboard Events
2.11.3 Timer Events
2.12 Higher-Level Events
2.12.1 The Load Event
2.12.2 The Paint Event
2.12.3 Focus Gained and Focus Lost
2.12.4 The Destroy Event
2.12.5 Programmer-Defined Events
2.13 GUI Component Examples
2.13.1 Push Buttons and Menu Choices
2.13.2 Edit Boxes
2.13.3 List Boxes
2.13.4 Scroll Bars
2.14 GUIs and Threading
2.15 Summary

Chapter 3 Smalltalk and the Squeak


Environment
3.1 A Brief History of Smalltalk
3.2 “Everything is an Object”—Basic Smalltalk Syntax and
Semantics
3.2.1 Messages
3.2.2 Symbols
3.3 Names and Types
3.3.1 Dynamic Bindings and the Referencing Environment
3.3.2 Types
3.3.3 Type BlockContext
3.3.4 Basic Operators
3.3.5 The nil Object
3.3.6 Storage Management
3.4 Control Flow in a Smalltalk Program
3.5 The Squeak Dialect and Environment
3.5.1 Navigating Squeak
3.5.2 The Squeak Browser Window
3.6 Information Hiding in Smalltalk
3.7 Polymorphism in Smalltalk
3.8 Smalltalk Containers
3.9 The Model, View, Controller (MVC) and Morphic Patterns
3.10 Pixels, Graphics Objects, and Drawing
3.10.1 Important Data Types for Drawing
3.10.2 Drawing on a Canvas
3.10.3 Default Drawing Attributes
3.11 The Morphic Event Model
3.11.1 A First Exercise in the Use of the Morphic Framework
3.11.2 Maintaining a Persistent Display
3.11.3 Subclass for a Bouncing Ball
3.11.4 Adding a Slider Component
3.12 Case Study: Scoring a Bowling Game
3.12.1 The Interface to the Business Class
3.12.2 The BowlingFrameMorph Class
3.12.3 The BowlingScoreMorph Class
3.13 Summary

Chapter 4 C++ and Java Commonalities and


Similarities
4.1 Introduction: the C Heritage and a Divergence of Goals
4.1.1 C and C++ Evolution and Backward Compatibility
4.1.2 Java Abandons Compatibility
4.2 Declarations and Static Bindings
4.3 Files Involved in Translation
4.3.1 C++ Header Files, Source Files, and Object Files
4.3.2 Java Source Files, Class Files, and the JVM
4.4 Scope and Visibility of Names
4.4.1 Static Scopes
4.4.2 Global Scope Rules and Java Packages
4.4.3 C++ Namespaces
4.4.4 File Scope in C++
4.4.5 Class Scope
4.4.6 Lifetimes of Variables
4.5 Low-Level Operations
4.5.1 Translation of Expressions and Coercions
4.5.2 Basic Types, Arithmetic, and Bit-Level Operations
4.5.3 Programmer-Defined Operators and Boolean
Coercions
4.5.4 The C++ void* Data Type
4.5.5 Java Wrapper Classes
4.6 Console Output
4.7 Arrays and Subscripting
4.8 Control Flow
4.8.1 Expression-Level Sequence Control
4.8.2 Casts and Temporaries
4.8.3 Statement-Level Sequence Control
4.9 Class Concepts
4.9.1 Basic Syntax and Semantics
4.9.2 Value Semantics and Pointer Semantics
4.9.3 Single Inheritance
4.9.4 Abstract Classes vs. Concrete Classes
4.9.5 Overrides and Polymorphism
4.9.6 Run-Time Type Checking and Casting
4.9.7 Named Constants
4.10 Exception Handling
4.11 Library Commonalities
4.11.1 Heterogeneity and Genericity
4.11.2 The Vector Classes—Direct Access and Adjustable
Size
4.11.3 Iterators—Traversing a Container
4.11.4 The List Classes—Efficient Insertions and Deletions
4.11.5 Sets and Maps—Efficiently Searchable Trees
4.12 Summary

Chapter 5 Additional Concepts from the C++


Language
5.1 L-Values, Pointers, and References
5.1.1 L-Values and R-Values
5.1.2 Pointers
5.1.3 References
5.1.4 Pointers to Members
5.2 Storage Management and Class Destructors
5.3 Arrays, Strings, and Pointer Arithmetic
5.4 Parameter Transmission Modes and Mutability
5.4.1 Reference Parameters
5.4.2 Mutability and const Functions
5.5 Type Coercions, Parameter Matching, and Overload
Resolution
5.6 Stream Input and Output
5.6.1 Console Input
5.6.2 File I/O Using Streams
5.6.3 String Streams
5.7 File-Scope Variables and Procedure Definitions
5.8 Inline Implementation vs. Separate Compilation
5.9 Operator Overloading
5.10 More on C++ Header Files and Source Files
5.11 C++ Access Control and Inheritance Patterns
5.11.1 Protected Access and Friends
5.11.2 Protected and Private Inheritance
5.11.3 Multiple Inheritance
5.12 Slicing
5.13 Downcasting, Crosscasting, and Run-Time Type
Information
5.14 Macros and Function Templates
5.15 Class Templates and Member Function Templates
5.16 Hash Tables in C++
5.17 Summary

Chapter 6 Visual Studio and the Microsoft


Foundation Classes
6.1 Win32 Messages and the Message Loop
6.2 The MFC Library and the Document/View Architecture
6.3 Using the Code Generators to Develop an MFC Application
6.4 Device Contexts, Graphics, and Maintaining the View
Window
6.5 Colors, Pens, and Brushes
6.6 Using the Visual Studio “Properties” Window
6.7 Timers and Animations
6.8 A Persistent and Traversable AVM Game Class
6.9 An AVM Game Application Using the Document Class
6.10 Designing and Using a Dialog Box
6.11 Snapshots, Bit Block Transfers, and Accelerator Keys
6.12 Summary

Chapter 7 Java and the Swing Library


7.1 Text Input Operations and the Wrapper Classes
7.1.1 Stream Readers, Buffered Readers, and the readLine()
Method
7.1.2 The StringTokenizer Class
7.1.3 “Parsing” with the Wrapper Classes
7.2 Java Inheritance and Polymorphism
7.3 Java Interfaces
7.3.1 Sorting and Interface Comparable
7.3.2 Example: Interfaces for a Radix Sort
7.3.3 Interface Inheritance
7.3.4 Iterating through a Collection
7.3.5 Interface Cloneable—the Ramifications of Pointer
Semantics
7.4 Java Enumerations
7.5 Inner Classes in Java
7.5.1 Nonlocal References in Inner Classes
7.5.2 Using an Inner Class to Export an Interface
7.5.3 Anonymous Inner Classes
7.5.4 Adapters
7.6 Java Generics
7.6.1 Defining a Generic Container Class
7.6.2 Type Relationships Revisited
7.7 Java Hash Tables
7.8 Introduction to the Swing Library
7.8.1 The Graphics and Component Classes
7.8.2 Top-Level Components
7.8.3 Timer Example: A “Dropped Ball” Panel
7.8.4 Layouts
7.9 Serialization
7.9.1 Introduction to Java Serialization
7.9.2 Wrapping for Storage
7.9.3 Some Simple Examples
7.10 Menus, Dialogs, and a Complete Application
7.10.1 The JOptionPane Class
7.10.2 Building a Maze
7.10.3 The Maze Class
7.10.4 The MazePanel Class
7.10.5 Menus on a JFrame Object—The Maze Application
7.10.6 Custom Dialog Boxes
7.11 Gaining Run-Time Access to Type Information
7.12 Component-Level Programming
7.12.1 Bean Properties
7.12.2 A “Drag and Drop” Example
7.13 Applets
7.13.1 The Maze Application as an Applet
7.13.2 Security and the “Sandbox”
7.13.3 Applets and Threads
7.14 Summary

Chapter 8 C# and the Common Language


Infrastructure
8.1 Introduction to the Common Language Infrastructure
8.2 Some Interesting C# Design Choices
8.2.1 C# Control Flow
8.2.2 Value and Reference Types
8.2.3 Arrays and Multidimensional Arrays
8.2.4 Strings and Parsing
8.2.5 Parameter Transmission in C#
8.2.6 Variable-Sized Parameter Lists
8.2.7 Properties—Access Functions in Disguise
8.2.8 Indexers—Programmer-Defined Subscripting
8.2.9 Operator Overloading
8.2.10 C# Compilation Units
8.3 C# Types and Namespaces
8.3.1 C# Classes and Partial Classes
8.3.2 C# Structs
8.3.3 Interfaces
8.3.4 Enumerations
8.3.5 Namespaces and Namespace Aliases
8.3.6 Partial Methods
8.4 Additional Inheritance Considerations
8.4.1 Run-Time Polymorphism
8.4.2 Inline Implementation
8.5 C# Type Parameters
8.6 Some Important Library Interfaces
8.6.1 IDisposable and the using Statement
8.6.2 Anonymous IEnumerable Objects and yield Statements
8.6.3 Implementing IEnumerable<> and IEnumerator<>
8.6.4 The ICloneable Interface
8.6.5 The IComparable Interface
8.7 Function Types in C#
8.7.1 Delegates
8.7.2 Multicast Delegates
8.7.3 Lambda Expressions and Anonymous Methods
8.7.4 Captured Local Variables
8.7.5 Parameterized Delegates
8.7.6 Expression Trees
8.8 .NET Framework Collection Classes
8.9 Windows Forms and Controls
8.9.1 Starting a Windows Application in Visual Studio
8.9.2 Drawing on a Form
8.9.3 Events in C#
8.9.4 An Application Using Mouse Events and a Timer
8.10 Programmer-Defined Events
8.10.1 Event Syntax
8.10.2 A Bouncing Ball Class with a “Bounce” Event
8.10.3 Reacting to the Event—A Bouncing Ball Application
8.11 Unsafe Code
8.12 File I/O and Serialization
8.13 Summary

Chapter 9 Python
9.1 Python: a Highly Simulated OOPL with Unobtrusive Syntax
9.1.1 Indentation
9.1.2 Keyword Arguments
9.2 The IDLE Environment and Console I/O
9.2.1 Console Output
9.2.2 Console Input
9.3 Python Data Types
9.3.1 Numeric Types
9.3.2 NoneType and the Value None, and Uninitialized
Variables
9.3.3 Sequence Types
9.3.4 String Operations
9.3.5 Hashing and the Built-In Keyed Collections
9.4 Python Scopes and Information Layering
9.4.1 Function Definitions and Function Objects
9.4.2 Class Definitions
9.4.3 Modules
9.4.4 Decorating an Object
9.4.5 Storage Management and Dynamic Variable Deletion
9.5 Sequence Control in Python
9.5.1 Exception Handling
9.5.2 The with Construct
9.5.3 Operator Precedence
9.5.4 Statement-Level Sequence Control
9.5.5 Generators, Iterators, and Comprehensions
9.5.6 Operator Overloading
9.6 Inheritance and Polymorphism
9.7 Functional Features of Python
9.8 The External Environment
9.8.1 Files and I/O
9.8.2 Python Features for Persistence—pickle and shelve
9.9 The tkinter Library and GUI Applications
9.9.1 Creating a Root Window in tkinter
9.9.2 Adding a Button and a Label
9.9.3 Threads and Windows
9.9.4 “Modal” Windows
9.9.5 Widgets and Events in tkinter
9.9.6 Canvas Objects and How to Draw with Them
9.10 A Postscript: Python, Smalltalk, and a Culture of Reusability
9.11 Summary
Appendix A Event-Driven Project Ideas
Appendix B Answers to Odd-Numbered
Exercises
Appendix C About the CD-ROM
PREFACE

TO THE STUDENT
Each of you brings to the table a year or more of study in a
particular object-oriented programming language. Some of the
subtleties of those languages you have already encountered,
probably enough of them so that you have already experienced the
difficulty of mastering some of the intricate concepts of object-
oriented programming languages. Mixed in with the concepts of
inheritance, polymorphism, generic programming, and several
variants of information hiding and access control, there are
hundreds of smaller design decisions which impact these larger
issues and impact each other as well. Most of these design
decisions are treading in well-worn paths, because imbedded in
these newer languages are myriad concepts which have been used
in languages of the past.
Your instructor has carefully selected those chapters on which
you are going to concentrate, but I encourage you to read and study
the other chapters as time permits. There is great beauty in a
consistent programming language design, and there is much to be
learned even from some of the apparently poor design decisions
which were made. All programming languages have flaws, but
usually those flaws were deliberately accepted by the designer in
order to achieve a specific goal. You may agree or disagree with the
goal, but it is important to grasp the reasons why a design decision
was made.
Event-driven programming can be frustrating and challenging,
and certainly great fun. It is included here because it is an important
tool for producing more useful and creative software, but also
because it is a showcase for the advantages of object-oriented
design. From the beginning graphical user interfaces were a major
motivation for the design of object-oriented languages, because the
hierarchy of types of objects seen on a display device (and
interacted with using a mouse and keyboard) strongly suggests a
hierarchy of software types. We dip into several EDP environments
in this text, and our purpose is always to not only give the reader the
flavor of how it feels to develop applications in that environment, but
to actually cover enough of the details so that medium-sized
projects can be undertaken and completed by the student within the
framework of a semester of college.
Omitted from the historical context presented in this text are a
great variety of languages with unique and creative designs which
have motivated today's designs. A short list of missing languages
includes APL, LISP, PROLOG, FORTRAN, COBOL, Snobol, Pascal,
and Ada. Contrary to popular opinion, none of these languages is
“dead.” Variants of them are still in use, and it is likely that they will
continue to grow and evolve and be of continuing usefulness
indefinitely. The reason for their longevity lies in their inventiveness.
At the core of each lies an idea that motivated the design, and in all
cases where the idea was clear and communicated well, there was
staying power.
If you enjoy this text, you will also enjoy studying the design and
implementation issues encountered in other languages, object-
oriented or otherwise, and you are strongly encouraged to do so. It
is likely that during that study some new types of design solutions
will take shape in your mind that would otherwise never have
occurred to you. Since the invention of the wheel, our tools have
shaped our thinking. For this reason, programming language design
lies at the heart of the discipline of computer science. I hope this text
motivates you to continue your study in this very important area.

TO THE INSTRUCTOR
The last twenty years have seen a dramatic change in computer
science curricula, engendered in part by the introduction of object-
oriented languages into those curricula and by the near-universal
use of such languages as a tool for teaching software design and
construction principles to Computer Science majors. The large
majority of departments use either Java or C++ as the major
teaching language in their curricula, and object-oriented (OO)
programming languages (OOPLs) as a whole have become very
important in our curricula. Because of the breadth and density of
concepts in this set of languages, and the fact that each is
accompanied by a sophisticated library of container classes, classes
for graphics and event-driven programming, and other concept-
heavy classes, there is now room within the OO paradigm to discuss
a large part of what we have always taught in the Programming
Languages course, while building on a broad, established base of
familiarity on the part of our students. This text is meant to be a
resource for instructors wishing to teach programming language
design and implementation from that perspective.
The student using this text should have completed a year of
study in an object-oriented programming language. The text
generalizes from that year of experience in order to present the
foundational principles of programming languages, drawing on the
students' OO background while widening their perspectives. It uses
a historical approach to link the older procedural languages to
current object-oriented languages, tracing the roots of the latter to
their origins in Simula 67. The main body of the text teaches a
selected set of object-oriented languages from the standpoint of
language design and implementation, beginning with the historically
significant and highly original Smalltalk language. Enough
information is presented to allow the students to see the depth and
power of each language, and to be able to write some interesting
programs.
Recognizing the growing importance of language-integrated
libraries, the author presents in the context of each language a
sampling of library types, including the standard types of container
classes and associated iterators. In the same way, in keeping with
the historical and current symbiosis between OO languages and
event-driven programming (EDP), the text includes an early chapter
on the basics of EDP, and follows up on that theme by including a
detailed introduction to an EDP library for each of the languages
covered.
The historical theme is reinforced in a pivotal chapter on C++
and Java similarities, tracing those languages back to their roots in
C. The student is made to see how dramatically two languages can
diverge from a common base, given two different sets of design
goals. Further chapters complete the study of C++ and Java and
provide a detailed and critical introduction to C# and Python.
Common EDP themes such as graphics, animation, and user
controls are introduced for each language, using as vehicles the
MFC library (C++), Swing (Java), Windows Forms (C#), and Tkinter
(Python).
The object-oriented paradigm isn't perfect, and it is certainly true
that a design is not necessarily good just because it is object
oriented. But the object-oriented languages taken as a group are a
very rich and rewarding study. The sheer number of concepts
involved in learning Java or C++ or any other object-oriented
language, and the requirement we now place on our students to
learn those concepts early in the curriculum, has enriched our
curricula. The accompanying demand on our students for a higher
degree of sophistication has changed the way we teach
programming and software engineering.
A course based on this text makes a natural alternative or
companion to the traditional Programming Languages course. A
variety of ways suggest themselves to accommodate such a course
into the curriculum. One idea is to offer a two-course sequence in
Programming Languages, using this as either the first or the second
course. Or two alternative courses could be offered, perhaps during
alternate years. On the other hand, if this course is used as the only
Programming Languages course at the undergraduate level, there is
ample material in it to satisfy the ACM curriculum requirements.
Along with a good theory course, it should prepare the student well
for the study of the theory, design, and implementation of
programming languages at the graduate level.
ACKNOWLEDGMENTS

I wish to thank my mother, for always believing in me, for failing to


see my shortcomings, and for never being surprised at my
successes. I also wish to thank my wife, Carol, and son, John, and
various members of my extended family, for their patience as I have
shortened my times of fellowship with them, and perhaps also
shirked a few duties, in order to do this work. Professionally, I wish
to thank Terrence Pratt, out of whose classic textbook I taught for
many years, for first opening my eyes to the richness of
programming language design. My colleagues in the Computer
Science department at Grove City College have sacrificed to give
me the time to write, and I will always be grateful for their
unanimous support. Grove City College as an institution has done
far more than provide me with an office, computer, and network. It
has provided a unique atmosphere, a positive influence coming at
me from all directions, which makes it a joy for me to go to work
each day. The faculty and the student body are the largest part of
that, but sound institutional principles and an honest desire to
remain true to those principles are the guiding force. Thanks also go
to the Coffee Grove (now Beans on Broad), Purdy’s, and various
other coffee shops, for putting up with my Spartan patronage and
allowing me to use their space and wireless network when I wanted
a change of scenery as I worked.
CHAPTER 1

A CONTEXT-SENSITIVE
INTRODUCTION

B ecause this text is chiefly concerned with object-oriented


programming languages (OOPLs), we will begin it with an
attempt to characterize exactly what is meant by the term and
to supply a framework into which we can fit our study of OOPLs. We
assume up front that the reader already has a good foundation in
one such language. We cannot assume, however, that the reader
has a complete overview of where these languages fit in the design
space, their historical context, the elements of programming
language design, or even of what one means when one speaks of
“good” design. We also cannot assume that the reader has seen all
the concepts necessary for a broad comprehension of the design
and implementation issues encountered in a wider study of
programming languages. This chapter is meant to supply an
overview of these issues, and to provide a context for our study of
the widely and wildly varying possibilities which exist in the design of
an object-oriented language.

Throughout the text we will try to relate the language


elements we discuss to the people who will be
affected by their use. For greater clarity, we will
standardize our use of the terms “programmer,”
“client,” and “user.” The first term, programmer,
relates to you, our reader, as one who designs
software using a particular programming language.
The second, client, refers to another programmer who
will be the direct consumer of the software module
you are producing and whose work cannot proceed
without that module. The term user is the (probably
nontechnically oriented) user of a program written in
the language. We will also use the term “client” to
refer to software modules, so that program
component A is a client of program component B if it
makes reference to B or its contents in any way.

1.1 WHAT IS OBJECT-ORIENTED PROGRAMMING?


“Object-oriented” is a style of programming that has come into its
own in business, government, industry, and academic circles. It
promises a more natural, and therefore a more powerful, design
paradigm, to the extent that a programmer is more productive if his
software-constructed model conforms closely to the structure of the
problem being solved. To amplify this statement, let us say that we
equate “power” in a language with the ability that language has to
inspire good solutions in the mind of the programmer. What we
mean, then, by saying that an object-oriented language is more
powerful, is that its features allow the programmer solving a problem
to build constructs that reflect the structure of the world within which
that problem arose. The idea here is that familiarity with such a
language will be likely to open up avenues to a clear and natural
solution in the programmer's mind. Whether or not this is the case is
still being debated [Hadar08], but the paradigm has enough of a
track record to establish it as a powerful force, and it is likely to be a
dominant force in the programming world for many years to come.
The domination of object-oriented programming
(OOP) began with the rise of C++ and Java' in
academic circles in the nineties. In 1990, a panel
discussion at a national meeting for Computer
Science educators ([Bierbauer90]) was introduced
with the statement, “As object-oriented programming
becomes a main-stream technology, instructors are
wrestling with how to incorporate it into the Computer
Science curriculum.” This uncertainty on the part of
academic professionals did not last long. By 1998,
there was no longer any doubt that OOP was to be
the primary paradigm on which the curriculum would
be based in an overwhelming majority of computer
science departments around the country. That year
was the year that the College Board's Advanced
Placement (AP) computer science test was
redesigned to test proficiency in the C++ language.
(Before that date the test had been based on the
procedural language Pascal.) Today the OOP
paradigm remains dominant, but for a large number of
college and university computer science departments
the preferred teaching tool is Java.

In this section, we will take some time to review the primary


qualifications that a programming language must have before it can
be said to be object-oriented. Some of the discussion here
anticipates material to be encountered later in the chapter, where we
will go back and lay a more careful foundation for some of the terms
in this section. Our purpose at this stage is to carefully define what
we mean by an object-oriented programming language.
1.1.1 Data Abstraction and Information Hiding

A major breakthrough in programming language design occurred


when programmers were allowed to define their own data types. C.
A. R. Hoare's record class was the source of the idea and influenced
the design of the class construct in the Simula 67 language. But
initially few people knew of or cared for Simula; the version of the
programmer-defined data type used in the teaching language
Pascal ([Wirth70]) was much more widely used and accepted.
Pascal's data types incorporate only data. Actions performed on
the data are considered external to the data type itself, so that the
syntax of the language indicates only a grouping of data, as in the
following example.
type Point =
Record
x, y: integer;
end;
The above Pascal declaration introduces a data type called Point
which incorporates two integer components named x and y. (A
similar data type appears in every library for event-driven
programming (EDP) discussed in this text.) Thus, once the above
declaration has been made the Pascal programmer can use the
type name Point to instantiate as many data entities as desired. For
example, the following code declares two variables and an array, all
of type Point.
var
basepoint, corner: Point;
vertices: array [1..20] of Point;
The Point data type as given here is homogeneous, meaning
that all of its components are of the same type (integer in this case).
Pascal, however, does not restrict itself to homogeneous data types,
and indeed the record...end construct lends itself quite well to the
encapsulation of a variety of different types of components. In other
words, Pascal allows the creation of data types which are
heterogeneous, i.e., are aggregates whose individual elements can
be of different types. Pascal does not have the ability to incorporate
operations, as does the following Java segment.
class Point {
private int x, y;
public int getX() { return x; }
public int getY() { return y; }
public void setXY(int x, int y) {
if (x >= 0 && y >= 0) {
this.x = x;
this.y = y;
}
}
}
The above example illustrates another capability associated with
object-oriented languages, which is the ability to define an interface,
i.e., to specify the portions of the data type that are accessible from
outside. In the above example, public write access to x and y is
limited to the setXY() member function, because x and y themselves
are declared private. Thus, a language with true data abstraction
must have explicit interfaces.
There are, of course, two sides to this coin. As soon as we state
that a choice can be made as to what is visible from outside, we are
implying that what remains is hidden, in some sense. Thus,
information hiding goes hand in hand with the idea of explicit
interfaces.

Definition

A term which we define up front, in a very general fashion, is


the term encapsulate. Whereas many texts provide a rather
specialized meaning of this term, with many connotations, we
will restrict our definition to the simple statement that to
encapsulate a series of program elements is to provide
bracketing syntax that allows us to group those elements and
to think of the encapsulated set as a single entity. Such
encapsulation may or may not involve defining an interface, or
even naming the entity. An example of an encapsulation is the
C compound statement, in which a series of statements
preceded by the left set bracket (“{”) and followed by the right
set bracket (“}”) is considered to be a single statement in the
syntax of the language. Function and class definitions are also
examples of encapsulation.

Data abstraction, then, in its full power as a programming


language capability, requires (1) the ability of the programmer to
define and name his own data types, (2) the ability to incorporate
heterogeneous data structures into such data types, (3) the ability to
specify a set of operations included within the data type, and (4) the
ability to specify which portions of the data type are available to be
accessed from outside.

The term abstract data type (ADT) is often used to


refer to a data type that is constructed using the data
abstraction capabilities of some programming
language, but such a data type can be, and often is,
described and discussed in a totally language-
independent fashion, and used as a program design
tool whether or not the target language provides
complete support for data abstraction.

Here we introduce the term object. If we use the term in its most
general sense, we can call any data entity an object. In fact, the
term data object has been around a long time and has been used to
mean nothing more than a stored data value or aggregate of values,
to which a specific type has been assigned. But in the context of
object-oriented programming the term takes on additional
connotations. In that context, we speak of an object as consisting of
two parts: its attributes and its behaviors. Such an object is an
instantiation of an abstract data type, and in that context the
attributes are the data components of the ADT and the behaviors
are the included operations. But the strongest sense of the term
object is in the context of object-oriented languages, where more is
required to use the term than a simple abstract data type.

In this text, we will use the term object in both its


weak sense, i.e., as a stored data item, and also in its
strong, object-oriented sense. The context of the
discussion should always be more than sufficient to
distinguish the sense in which we use the term.

The active components of an ADT, in the context of object-


oriented programming languages, can be referred to using a number
of different terms. We have already used the terms operation and
behavior, which are somewhat abstract and refer to “capabilities” of
an object, but in the context of specific languages we may use the
term method or member function, both of which refer to the specific
program unit which defines the details of the way the behavior is
achieved. We use the term message, or a term such as method call,
method invocation, or member function call, to refer to the program
element which invokes the corresponding behavior for a given
object.
1.1.2 Inheritance

Relationships between types are important in a language. The


type equivalence relation, for example, establishes two types as
exactly the same, meaning not only that each type represents the
same set of possible data values, but also that two objects of the
two respective types are compatible across assignment statements,
at the parameter transmission and return level, and in comparisons
for equality.

One example of an early and persistent issue


concerning the relationship between types in a
language is the issue of structural equivalence versus
name equivalence. A language which uses structural
equivalence considers two types the same if they
have the same types of components in the same
order. Name equivalence is stricter and never
considers two types of different names to be
equivalent no matter what their internal structure.
Often a particular programming language design will
use a combination of these; using pure name
equivalence is too restrictive, and unrestricted
structural equivalence is insecure and complex.

Type relationships in object-oriented languages are enriched by


the presence of the inheritance and subtype relationships. These
add a new complexity to the type structure of a language. We say
that type B is derived from type A, or that B is a derived type of A,
provided that in the program some syntax has been employed which
guarantees that objects of type B have all the same attributes and
behaviors as objects of type A, possibly with some more of their
own. This relationship is the inheritance relationship, and we say
that B inherits these attributes and behaviors from A. We say that A
is the base type, or base class, from which B is derived. The terms
superclass and subclass are used interchangeably with the terms
base class and derived class, respectively.
The subtype relationship is similar to the inheritance relationship,
and in some languages it turns out to be equivalent. In order for a
subtype relationship to hold, objects of type B must be considered to
also be objects of type A. This means more than just saying that B
objects have all the same attributes as A objects; it means that B's
public interface is a superset of A's public interface. In other words,
whatever attributes and behaviors of type A are accessible to client
programmers are also accessible in type B. With this stipulation, B
objects can serve as arguments passed to parameters of type A. We
say that B is a subtype of A, or that A is a supertype of B.
Be careful of a common source of confusion here—it
seems counterintuitive that the subtype relationship
should apply in the direction given. Because B has
more attributes it would seem more intuitive to say
that B was the supertype. In fact, having a larger set
of attributes and behaviors makes B more specialized
and less general, and therefore representative of a
more constrained set of values. It is in that sense that
B is said to be a subtype of A.

We make two observations for clarity and further guidance here.


The first observation is that neither inheritance nor subtyping
reaches the level of type equivalence, because the relationships are
not symmetric. In neither case are objects of type A considered to
be objects of type B. The second observation is that in common
usage of the features of an object-oriented programming language,
wherever there is inheritance there is subtyping. We will not again
make an explicit distinction between the two until we encounter
cases where the distinction exists in specific languages.
A data type construction facility which incorporates inheritance is
universally referred to as a class construct, and such a data type is
called a class. For example, consider the class Point defined above
using the Java language. If we “fatten up” a point, we could call it a
Disk. For this, all we need are two more attributes: a radius and a
color. We still need the x and y attributes and the behaviors that
allow us to manipulate those attributes, but the point (x, y) is now
taken to be the coordinates of the center of the disk. We add to
these the two additional attributes and some other behaviors for the
purpose of manipulating the two new attributes. The result in Java
might be the following class description.
class Disk extends Point {
private double radius;
private Color color;
public double getRadius() { return radius; }
public void setRadius(double radius) {
if (radius > 0) this.radius = radius;
}
public Color getColor() { return color; }
public void setColor(Color color) { this.color = color; }
}
Inheritance does not necessarily change the way we use a
specific class. As with any class, using the above requires that we
(1) instantiate an object of the type represented by the class and (2)
use its public members and methods to modify it and access its
parts. Here is an example Java code sequence:
Disk d = new Disk();
d.setXY(100,210);
d.setRadius(25.7);
d.setColor(Color.red);
The act of executing the method call d.setXY(100,210) can be
referred to as sending a message to the object d. In particular, we
are sending d the setXY message with arguments 100 and 210. Note
that setXY() is a method in the base class, but the derived class
object d understands and is able to respond to it.
Most methods are instance methods, meaning that when we use
one of them to send a message that message is sent to an instance
of the class (an object), not to the class itself. When a message is
sent to the class instead of the object, we call the method
associated with that message a static method, or a class method,
and the language or its implementation must provide a way to
identify the method definition as being associated with the class, not
with objects instantiated from the class. In Java, C++, and C# we
use the attribute static to identify a class method. Smalltalk, a
minimalist language which is rather stingy with its allocation of
keywords, assumes the development environment will provide a
way to distinguish between class and instance methods.

As the usage given here illustrates, the keyword static


in many languages has a number of very specialized
meanings, but there is another quite general and
widely accepted meaning of the word. Accordingly,
the term static is generally used, and will consistently
be used throughout this text, in opposition to the word
dynamic. Generally speaking, “static” refers to
translation time and “dynamic” refers to run-time.
Thus, an expression which is “statically evaluable” is
an expression that can be evaluated by a compiler
once and for all; this situation is potentially
advantageous because the translator can substitute
the computed value for any occurrence in the
translated code and will not have to generate
executable object code to evaluate the expression
dynamically.

The addition of an inheritance mechanism to a data abstraction


facility carries with it immense power and proportionate
complications. Now instead of a collection of types which are
unrelated or related only by type equivalence we have the potential
for a complex hierarchy of types related by inheritance. Now in
describing the syntactic and semantic rules which define the
language we must potentially consider type-theoretic terms like
direct base class, indirect base class, common base class, etc.
These terms will be discussed in the remainder of the text, in the
contexts of the specific languages to which they are relevant.
1.1.3 Polymorphism

Considering that there are behaviors anyone would expect from a


certain class of objects, but that often a more specialized object
would perform that behavior in a different way, we are led inexorably
to the necessity to override base class behaviors. For example, let
us suppose we have a class called Automobile with a behavior called
accelerate. The base class might not support an acceleration any
faster than five miles per hour per second. So if familyCar is an
object of type Automobile, and one issues the message
familyCar.accelerate(60,3), requesting a total acceleration of 60
miles per hour in 3 seconds, the result might only be a total speed
increase of 30 miles per hour in the time specified. If on the other
hand familyCar was an object of the subtype Corvette, one might be
more realistic in expecting the command to be followed precisely.
Here we say that the definition of accelerate in the derived class
Corvette overrides the definition of that method in the base class
Automobile.
Let us consider an example of a more prosaic nature, this time
using C++ syntax. Suppose we have a base type Animal, with a
behavior called soundMade(), described as follows:
class Animal {
public:
char * soundMade() { return “generic animal sound”; }
};
Then when an object pet of type Animal is expected to furnish a
C-style string with the call pet.soundMade(), it will return a pointer to a
character location where the string “generic animal sound” is stored.
It is not much of a stretch to imagine the need for the derived class
(subclass) Cat, defined as follows:
class Cat: public Animal {
public:
char * soundMade() { return “meow”; }
};
After this declaration, if pet is declared to be of type Cat, the
pointer returned by pet.soundMade() is pointing to the string “meow”.
Consider now the situation in which pet refers to a Cat object,
but in fact is only known to be an Animal. (In other words, the only
declaration for pet assigns Animal as its type.) This can happen in
several ways. For example, pet could be a parameter of type Animal
to which has been transmitted an argument of type Cat. There are
two things that one might reasonably expect to happen:

1. Because the parameter is of type Animal, and the compiler is


able to statically ascertain this fact, it could simply generate
code to call the member function declared with that class (in
C++, the function Animal::soundMade()), resulting in a pointer to
the string “generic animal sound”.
2. Because the object transmitted is of type Cat, the compiler
might initiate some run-time actions to determine the location of
a compiled Cat::soundMade() function, and call that function,
which would return the result as a pointer to the literal “meow”.

It is response (2) above which we would label polymorphic


behavior. Interestingly enough, polymorphism is not the default
behavior in C++, and we would actually get response (1) in that
language. We can, however, request polymorphic behavior on a
method-by-method basis in the language by using the keyword
virtual in the base class as an attribute of the method, as follows:
class Animal {
public:
virtual char * soundMade() { return “generic animal sound”;
}
};
This one declaration makes the soundMade() method exhibit
polymorphic behavior in all overrides of all derived classes, direct or
indirect. So if this one addition is made to the declaration in the base
class, we would get behavior (2) and the call pet.soundMade() would
return “meow.”

What is polymorphism? Literally, it means “many


forms.” In this setting, it means that the one method
name may result in many forms of response
depending on where in the inheritance hierarchy we
happen to be, and the key ingredient is that the form
of response rests with the object, not the static type
structure of the language. It is the object, not a set of
statically determined characteristics of the variable by
which that object is referenced, which governs the
response to a message. This type of polymorphism is
an essential ingredient of object-oriented
programming as it is understood by the programming
community.

1.1.4 Related Concepts—Overloading and Generic Programming

Taking polymorphism in its most general sense (which is not the


sense in which the term is usually applied), we can say that it
involves similar syntax causing different forms of run-time actions
depending on context, whether that context is determined by static
program structure or by run-time history. Two language features
which are important, but are features for achieving “polymorphism”
only if we use the more general view, are overloading and generic
programming.

Definition

Overloading is the act of providing additional meanings for an


identifier, reserved word, or operator symbol, combined with a
plan for using context to resolve the question of which
meaning is needed in a particular circumstance. Overloading
adds additional meaning to a name and does not remove its
old meaning. The practice of introducing a new meaning for a
name that masks, or makes inaccessible, the old meaning is
called overriding. Overriding plays a prominent role in the
example of Section 1.1.3; indeed, the style of polymorphism
described there cannot be accomplished in a language that
does not permit overriding.

Although overloading is not polymorphism and technically has


nothing to do with object-orientation in a language, it needs to be
mentioned here because of its strong relationship with overriding
and polymorphism. Overloading a term has the result that it means
different things depending on the context in which it is used.
Consider, for example, the + symbol in just about any language with
which the reader is familiar. That symbol usually comes with an
overloaded meaning; that is, x + y means different things depending
on the types of the objects named by x and y. If they are both
integers, then the expression denotes integer addition. If they are
both floating point numbers, the expression denotes floating point
addition. If one is of an integer type and the other of a floating point
type, then the expression usually denotes a type conversion (integer
to float) followed by floating point addition. In some languages the
same + symbol might mean concatenation if one or both of x and y
happened to be a string.
Programmer-defined overloading takes this idea to the extreme,
and it is the key to another kind of polymorphism. If the programmer
is able to associate new meanings with, say, the + symbol, or with
an identifier which names one of the methods of a class, then the
programmer is introducing multiple behaviors identified with the
same name. This type of overloading is usually permitted in object-
oriented languages for methods named with identifiers. However,
whether or not overloading of operator symbols is allowed depends
on the language.
Let us turn now to a consideration of generic programming, our
second “polymorphic” language feature which does not fit the usual
definition of polymorphism. We begin with a discussion of how to
make method definitions “generic.”
Method definitions are a form of algorithm, and so a method
represents a prescribed sequence of actions which, taken in
concert, return a result or produce an internal change in the state of
an object. Let us take, for example, the following Java method for
the Point class above:
public void translate(int delta_x, int delta_y) {
x += delta_x;
y += delta_y;
}
The algorithm is simple. To translate a point (x,y) to a new
position in the coordinate plane, simply add a specific amount
delta_x to the x-coordinate and another amount delta_y to the y-
coordinate. But notice that although the method specifically uses the
integer data type for its parameters, the algorithm is in fact more
general than that. Addition makes sense across a range of several
different numeric types, so the pair (delta_x,delta_y) could be
assigned any combination of those types and the algorithm would
make perfectly good sense. Why then are the parameters declared
to be integers? It is because the syntax of the language requires the
assignment of a specific type to every parameter of a method.
Consider, by way of contrast, the Python method below,
assuming the Point class to be set up in a similar way in that
language:
def translate(self, delta_x, delta_y):
self.x += delta_x
self.y += delta_y
Notice that delta_x and delta_y are not assigned a type by the
syntax of the language. In fact, the success or failure of a call to this
method depends not on whether the correct types of arguments are
passed to it but rather on whether or not the += operation makes
sense when it is applied to each of those arguments.
Python achieves this degree of generality by delaying its
decision about what to do in response to the += operation until run-
time. This incurs a cost which languages like C++, and to a lesser
extent Java, cannot afford. The more decisions a language
postpones until run-time, the more slowly programs in that language
tend to run, simply because the decision must be made over and
over while the program executes. C++ puts a premium on fast
execution speeds; therefore, utilizing a design such as Python
employs is not an option.
C++ offers a variety of solutions to this problem. For example,
using a C++ version of the translate method above with arguments
which are not integer but are primitive numeric types would trigger a
coercion and produce at most a warning at compile time. But the
most general C++ solution to such problems is to use a construct
called a template, which allows automatic compile-time generation
of a new version of the method which fits each different use of that
method. The method itself is defined as a method template, not an
ordinary method, and its definition looks as follows:
template<class NumericType1, class NumericType2>
void translate(NumericType1 delta_x, NumericType2 delta_y) {
x += static_cast<int>(delta_x);
y += static_cast<int>(delta_y);
}
Here, NumericType1 and NumericType2 are template parameters
for which the call on translate will implicitly determine and transmit
actual types. Supposing, then, that p is a Point object, the two calls
p.translate(20,30) and p.translate(21.5,45.7) would actually call
into play two different functions, both named translate and both
generated from the template above. Because the types of the two
literals 20 and 30 are both int and those of 21.5 and 45.7 are
double, the effect is as if we had coded two functions, one with the
interface void translate(int,int) and the other with the interface
void translate(double,double). The template mechanism will, in fact,
generate as many different versions of the method as are needed.
This mechanism is clearly unrelated to the style of polymorphism
we described in Section 1.3, and it is not necessarily associated with
object-oriented programming. But it is nevertheless a very strong
kind of polymorphism. Because it is a compile-time mechanism, it is
often called “compile-time polymorphism.” Because templates work
by generating different versions of the same construct, all named
identically, compile-time polymorphism cannot be implemented in a
language that does not permit programmer-defined overloading.

Note the complementary sets of characteristics


applying to run-time and compile-time polymorphism.
With the first, we are able to define a large number of
different methods, all having the same interface, and
a run-time mechanism is used to select between
those methods. Each new method, however, requires
a separate definition and may use a totally different
algorithm. With the second, there is only one
definition of a construct (typically a method, function,
or class) in the program, yet all the different compile-
time-generated versions of the construct employ
different interfaces.

We use the term generic to refer to nontype-specific code. By


defining the term as the opposite of “type-specific,” we are admitting
the above Python method definition as a generic method, and the
reader should be aware that to some programmers the term would
not be used in this way. But by making our definitions language-
independent, we allow a broader discussion and room to compare
different ways of achieving the goals of a programming language
design. Using this definition allows us to state clearly that all the
languages discussed in this text provide some facilities for generic
programming. The thing that C++ templates (and Java generics as
well) provide is the ability to use a generic program construct to
generate at compile time multiple type-specific versions of that
construct.
Generic method definitions using type parameters are only one
way of using compile-time polymorphism. Once one admits the
concept of a parameter whose argument can be a type, any
encapsulated program unit potentially could be generalized to a
generic form. Commonly encountered examples of this are generic
classes and generic stand-alone procedures.

1.2 ALTERNATIVE LANGUAGE PARADIGMS


Higher-level languages structure the way we think about solving
problems, and each such language puts forth one or more
paradigms, or central ideas, about how to construct problem
solutions. Object-oriented is certainly not the first paradigm, nor will
it likely be the last. In this section, we will briefly discuss the major
alternatives which pre-date the object-oriented paradigm and are
still in use today.
1.2.1 Introduction—Some Basic Terminology

In the same sense as point and line are used as undefined terms in
geometry, we will start here with some undefined, or vaguely
defined, terms. To begin with, we will use the term symbol with only
the vague definition that it is a name with a meaning, either
predefined or programmer-defined. We use the term identifier to
mean a symbol with a name which is allowed to be multi-character,
which is used by the programmer for his own purposes, and which is
atomic, i.e., not divisible into component parts. An identifier might be
used, for example, to name a stored object or a type. There are in
any given language some simple formation rules for what
constitutes a valid identifier, and we will assume the reader has
experience using identifiers. A keyword is a symbol that may
conform to the rules for formation of identifiers, but which has a
language-defined meaning in certain contexts. Examples of symbols
often used as keywords are if, else, and while. A keyword which
cannot be used for any other purpose than its language-defined
meaning is called a reserved word.
We make only a weak attempt to define the term value. The term
is general enough to apply to a wide range of well-conceived and
rigorously defined entities, but in general it has two essential
aspects: it has meaning in some context, and it can be represented
by an encoding into a string of binary digits. A literal is a self-
defining symbol, i.e., one which has a value and whose name
describes its value. Some examples taken from the C-derived
languages are the character string literal “A string literal” and the
double-precision floating point literal 25.7. The term token is used to
refer to an indivisible symbol in the text of a program. Examples are
identifiers, keywords, operator symbols, literals, and bracketing
symbols (e.g., parenthesis characters and square bracket
characters).
A constant is a named, immutable value. Depending on the
implementation, the name of a constant refers to either (1) a storage
address which is initialized with the particular value at the time the
constant is defined and for which an attempt to change its value
causes an error condition, or (2) the value itself, which replaces the
name wherever it is used. A variable is a named storage location
whose value is subject to change.
An association is a (symbol, meaning) pair. In most languages
the only associations under the programmer's control are identifier
associations, in which the symbol used is formed as a valid identifier
in the language. In a few languages the programmer may also
introduce his own associations for operator symbols, such as the
plus sign. A scope rule is a rule for determining at any given time, or
at any given location in the text of a program, the set of associations
which currently applies.

The meaning of a symbol is in some languages totally


unambiguous at all points in the text of a program,
meaning that it can be traced back to exactly one
definition without examining its context in any detail.
That is not usually the case in modern object-oriented
languages, however. Most such languages allow the
programmer to overload the meanings of symbols, so
that multiple associations can exist at the same time
for one symbol, with detailed considerations of
context determining the precise meaning.

A symbol table is a table of associations. Symbol tables are used


in all language implementations, either during the translation of
source code, at run-time, or both. The structure of a symbol table is
typically that of a hash table, because it is necessary to fetch the
meaning of the identifier quickly and no advantage accrues by
keeping any particular order in the storing of associations, other
than a natural hierarchy imposed by the program structure itself. If
such a hierarchy exists, as it does in any language with any degree
of sophistication, then the symbol table will typically be a collection
of hash tables, the structure of which is dictated by the structure of
programs in the language, or a single hash table for which an
access using a particular symbol as key calls up an ordered list of
associations for that symbol.
A declaration is a program statement which provides information
concerning an association, information which can be recorded in a
symbol table. A definition is a declaration which provides a precise
and complete meaning for a symbol. A reference to an association
is a usage of the associated symbol in the text of a source code unit
which calls forth the particular meaning specified in the association.
The word “reference” can also be used as a verb, meaning to use a
symbol in a way which calls forth an association. The referencing
environment at any given time is the set of all associations which
are currently available for referencing.
A block is a sequence of executable statements, possibly
including some declarations, which is encapsulated by a procedure
definition framework or by bracketing symbols (begin and end, for
example, or C-style set braces). In most programming languages, a
block is considered a statement, so that the syntactic category
“statement” is recursively defined and therefore a block can be
nested inside a block, inside a block, etc., to any nesting level.
A static scope rule is a scope rule which is defined using textual
position. In other words, the meaning of a reference to a symbol x
depends on where x occurs in the text of the program unit. A
dynamic scope rule is a scope rule which is defined based on a
history of run-time actions. In this case, the meaning of x depends
on the particular pattern of the program's execution. The scope of an
association is therefore either the extent of program text at which a
reference to the given identifier or other symbol could be resolved
using that association (in the case of static scope rules) or the span
of program execution time during which a reference to the identifier
could be so resolved (in the case of dynamic scope rules).

Most languages which are currently in widespread


use employ static scope rules. An exception is the
special-purpose language Mathematica [Wolfram10],
whose programs are actually mathematical
documents with embedded, separately executable
cells. A Mathematica document has a single global
scope, and the meaning of any identifier at any point
in the document depends on which cells have been
evaluated and in what order.

A global association is one that applies in all contexts of the


program. The term local association can best be defined as one
which is not global, but it usually refers to an association with a very
limited scope, often qualified by a description of that program unit to
which it is local; for example, we could say that x is local to method
f(), or to a block within that method. In the same way, associations
which are not local in the most restrictive sense may be called
simply “nonlocal” or “local to” some program unit of intermediate
size.
1.2.2 The Imperative Programming Paradigm

The classical procedural languages (Algol, Fortran, Pascal, C, etc.)


are first of all imperative languages, meaning that work is
accomplished by the sequential execution of commands, each of
which may require the evaluation of one or more operations. Each
command changes the state of the executing program and its
environment, so that a correctly constructed program steers the
system into a sequence of target states which serve the purposes of
the user. The way that control is exerted over the sequence in which
those commands and operations are executed and evaluated (the
sequence control mechanisms of the language) varies somewhat
between imperative languages, but falls generally into two
categories: expression-level sequence control and statement-level
sequence control.

Definition

The arity of an operation is the number of operands it has. For


example, the prefix negation operation seen in the expression
−a has arity 1, whereas the same symbol denotes an arity 2
operation in the expression a − b. An arity 2 expression
formatted in this way, i.e., so that the operator symbol is
positioned between the two operands, is called an infix
expression.

The mechanisms typically used for expression-level sequence


control are operator precedence and associativity rules, which along
with the use of parentheses for overriding those rules will define the
order of execution down to the expression tree level. For example,
in most imperative languages the expression
a + b ∗ (c + d)/(7 ∗ n)
defines the expression tree in Figure 1.1. This tree does not provide
all the details of evaluation order, because the two multiplications
could take place in either order and still satisfy the requirements of
the tree. The choice of which multiplication to evaluate first is
typically up to the implementer of the language, not its designer.
There are some notable exceptions to this rule, in which the precise
order of evaluation of the nodes of the tree is specified in the
language definition, but such a policy hampers optimization of the
generated code by the compiler.
FIGURE 1.1 An expression tree.

In rare cases in practical programming, the programmer may be


vitally interested in knowing the order of evaluation beyond that
specified by the tree. If a function call is made which causes side
effects, that is, changes to the machine state that are not apparent
in the function's interface, then it may matter greatly whether a given
function has been called at a particular time. A case in point is short-
circuit Boolean operations, versions of the logical “and” and “or”
operations that sometimes evaluate only the left-hand operand.
Using “or” as an example, the Java or C++ expression
Another Random Document on
Scribd Without Any Related Topics
"'The Breton Mobiles! They are coming to the rescue of the
Mayors.' One saw the point of that. At all events, I saw it, even if the
others did not. The Breton Mobiles understood no word of French—
understood nothing but their own uncouth Celtic tongue. It would be
useless to harangue them on the sacred right of insurrection and
appeal to them to fraternise with people. They would sweep on, with
fixed bayonets, driving the Parisians before them, blind, deaf,
implacable as Destiny itself. For once in my life I perceived failure in
front of me, and I felt that I owed Fifine an apology.
"'Dear angel,' I said to her, 'this is not so brilliant a revolution as
I could wish, but it shall have its dramatic climax, all the same.
Observe!'
"Then I continued to elbow my way to the front, exclaiming—
"'Room there! Room for a lady! Room for Jean Antoine
Stromboli Kosnapulski.'
"The crowd parted as before, and I found myself close to the
table of the Mayors, with the pale face of the President immediately
in front of me. I pulled the rat out of my pocket and tossed it to him,
saying—
"'Thanks to your incapacity, the people of Paris are eating rats.
In the name of the Republic, I call upon you to eat a rat yourself.'
"The people who heard me cheered, but the Mayor of Paris tried
to fling the rat back into my face. I caught it in my right hand and
tendered it to him again with dignity.
"'Be reasonable,' I said. 'It is a present from Jean Antoine
Stromboli Kosnapulski. As those English say, you must put the gift-
horse in your mouth. In the name of the Republic, I call upon you to
eat the rat before us all, and to pretend that you enjoy it.'
"A tremendous cheer broke from the assembled revolutionists.
They shook their fists in his face and roared—
"'Let him eat the rat! Let him eat the rat!'
"He ate it, and we cheered him. Perhaps he was hungry, and
needed it, for, owing to the disturbances, he had been a long time
without refreshment; and though, to do him justice, he made little
pretence of appetite, one of the women—a good, thrifty soul—could
not resist exclaiming—
"'What a waste of a good rat! Why do you throw it away on
him, when the people of Paris are hungry?'
"That, however, was a question which, in spite of its
importance, I had no time to answer. At last the Mobiles were
coming—the Breton Mobiles, with whom it was impossible for the
Revolutionists to fraternise, because they did not know their
language. There was no purpose to be served by staying any longer,
the more especially as I had a lady in my charge.
"'Dear angel,' I whispered to Fifine, 'there is no more revolution
to be seen to-day. I will make haste and take you home.'
"It was more easily said than done, but I was not a man to be
deterred by obstacles. I shouted as before—
"'Room there! Room for a lady! Room for Jean Antoine
Stromboli Kosnapulski!'
"And room was made. I myself helped to make it, by pushing
vigorously with my strong arms. As the Bretons were entering by
one door, Fifine and I were issuing by another.
"It was all over—for the time. Many arrests were made; but, in
the confusion, Fifine and I escaped arrest, and it was not until the
next day that I knew that my behaviour had been remarked by any
public functionary. Then, however, I had a passage of arms with the
Père Dubois.
"'Rascal!' he said. 'I saw you.'
"'How now? What do you mean, Père Dubois?' I asked.
"'I was in the Hôtel de Ville, disarmed and helpless. But I saw
you, and now I go to denounce you to the Government.'
"I looked him straight and fearlessly in the eyes.
"'Remember your pact with me, Père Dubois,' I said.
"'My pact?' he repeated.
"'The pact we swore, like the Homeric heroes, that, even in a
revolution, we would spare each other. This time, as the revolution
has failed, it is I who am the gainer by it. Presently, when the
revolution is successful, it will be your turn to profit.'
"His eyes fell before my gaze as he replied—
"'If it were not for Fifine's sake, I would not do it.'
"To which I answered—
"'If it were not for Fifine's sake, I would not ask you.'
"'You think, then,' he continued scornfully, 'that the day will
come when it will be in your power to serve me?'
"'I am quite sure of it,' I answered, 'and when it comes, you
may rely upon me. Let us shake hands.'
"So we shook hands, and an armed truce was restored between
us; and the days rolled by, until the last great day came when I was
called upon to fulfil my obligations.
"Most of the events of those days belong to history. You know
how the Prussians at last starved Paris into surrender. You know how
we Communists seized the reins of Government in the month of
March. You know how Paris was besieged a second time, and how
the barricades sprang up, and how there were bloody battles in the
streets. I have nothing new to tell you of these things. I have only to
tell you of the service which I, at the last, rendered to the father of
Fifine.
"Fifine herself had been sent to visit friends in the country. Safe-
conducts being hard to get, it had been necessary to lower her in a
basket over the ramparts after nightfall. I well remember my last
talk with her before, with no more luggage than she could carry on
her arm, she disappeared into the darkness.
"'Sweetheart,' she said, 'I thought that revolutions were
wonderful, but now I only find them terrible.'
"'Sweetheart,' I answered, quoting the proverb, 'how shall we
make an omelette without breaking eggs?'
"That was too deep for her. She did not even ask whether the
omelette was worth the broken eggs, but came to the point without
either metaphor or simile.
"'Dearest,' she pleaded, 'I saw you begin the revolution. Can't
you promise, for my sake, that you will stop it?'
"I shook my head sadly. It was hard for me, as you can judge,
to confess that she had asked me a thing which it was beyond my
power to do for her.
"'Dear angel,' I answered, 'the revolution is irresistible as the
rising tide. A man may have the power to start it, but no man has
the power to stay it.'
"'But my father!' she pleaded. 'Tell me! The revolutionists have
no love for the police?'
"I was obliged to own, however regretfully, that they had not.
For what have policemen ever done, that revolutionists should love
them?
"'But, dear angel,' I added, 'one may make exceptions, if only
for the sake of proving rules. I wield influence, as you have seen,
and I will use it. They shall not hurt one hair upon the Père Dubois's
head.'
"Then we kissed each other and said good-bye. Fifine
disappeared, lowered over the ramparts by a sentinel; and it was
only two days afterwards that the Versailles soldiers entered Paris,
and the fighting in the streets began. I do not describe it to you. I
do not boast. One brave man behind a barricade, I take it, is very
like another. The tide of battle rolled us back from street to street.
The traitors slunk away and hid themselves. The day came when we
were only a handful of men, hemmed in by an army. Driven from my
lodging in Montmartre, I found a garret to sleep in in Belleville. I was
there, snatching the few hours' rest which I had earned, when a
child found me, and thrust a note, hastily scrawled in pencil, into my
hand.
"It was from the Père Dubois. How he had found the means of
sending it I do not know; but this is what he said—
"'I am a prisoner of the Commune, locked up with forty other
sergents de ville at La Roquette. Your Communists are murdering
their prisoners. For the love of God remember your promise to me
before it is too late!'
"My mind was made up instantly. Until then I had supposed that
a prison was the safest place in Paris in which a sergents de ville
could find himself; but since this was not so, I knew how to act.
"Springing from my truckle-bed, upon which I lay only half
undressed, I put on my frock-coat and my silk hat, and knotted my
red sash round my waist. Then I hurried down seven flights of stairs
and almost ran into the arms of our leader, Citizen Ferré.
"'Well, Ferré, how goes it now?' I asked him.
"'Badly,' he answered. 'It is all over with us. The Versaillais press
us hard. We have only just time to kill the prisoners.'
"At first I did not take him seriously.
"'Is that the way to raise the tone of revolutions?'
"He answered grimly—
"'Perfectly. We have dealt with the Archbishop; we have dealt
with the gendarmes. If we make haste, we shall just have time to
deal with the sergents de ville.'
"His brutal words horrified me, but I temporised. Time was
precious, and I would waste none of it in wrangling. If it had only
been the life of an ordinary hostage—an archbishop, for example—
that was at stake, I do not say; but the life at issue was the life of
the father of Fifine. Therefore, as I have said, I temporised.
"'You are right, Citizen Ferré,' I replied. 'We must indeed be
quick. Let us see which of us can be the quicker. I will race you to
the prison of La Roquette.'
"'Good,' he replied, and we both began to run with all our
speed. Picture us; for the picture must indeed have been a strange
one. The enemy surrounded us, and the crack of rifles and the
screech of mitrailleuses sounded from the barricades on every side.
The rival batteries on the Buttes Chaumont and the Buttes
Montmartre hurled their shells all over Paris. Red flames and black
clouds of smoke arose from the Tuileries, from La Villette, from the
Hôtel de Ville, from blazing buildings in every quarter of the city.
Dead bodies of men and horses lay here and there upon the
pavements. Mattresses were piled up at the windows to serve as a
screen against the bullets. And, in the midst of this, Citizen Ferré
and I—he in his soldier's uniform, and I in my frock-coat and silk hat
—raced each other to the prison of La Roquette. I was fleet of foot
in those days, and I outstripped him. Dashing through the open gate
in the prison yard, I called—
"'Where are the prisoners of the Commune? Where are the
sergents de ville?'
"There was no need to ask the question. I could see the heads
of several of them at the windows of the cells. So I continued—
"'I have the order for them to be shot. Let me go up to them
and I will tell them to come down.'
"The words were saluted by a bloodthirsty cheer. It occurred to
no one to dispute my authority or ask a question. The key was
handed to me and I went up to the second storey and entered the
door of the long corridor in which their cells were situated.
"'Gentlemen,' I began. 'I am Jean Antoine——'
"Before I could say more, a dozen strong arms had gripped me
and thrown me on the ground, and my wrists were tied fast with a
handcuff improvised from a piece of string.
"'A hostage! We also have a hostage,' they cried in an exultant
chorus.
"Then, just as I was fearing more rough usage, I heard the
voice of Père Dubois.
"'Be gentle with him. He is a friend of mine. Hear what he has
to say.'
"So the policeman who was seated on my chest got up again,
and I was able to proceed—
"'Gentlemen,' I gasped. 'Citizen Ferré is on his way here to have
you shot. I raced him here that I might warn you. I am Jean Antoine
Stromboli Kosnapulski.'
"They looked inquiringly at me and at each other, and in the
meantime there came what looked suspiciously like proof that I was
lying. Ferré had, at last, arrived, and a fresh messenger came to the
entrance of the corridor; though, with greater caution than I had
shown, he only spoke through the keyhole.
"'The order has come that all the prisoners of the Commune are
to be released. Descend at once, and you can go free.'
"Some of them flashed a look of triumph on me, seeming to
expect that I would blush for shame. But I did not blush. I sprang up
and stood with my back to the door, and retorted hotly—
"'Idiots! Are you taken in, then, by a simple trick like that? It is
a lie to get you down into the courtyard, and shoot you the more
easily.'
"This gave them pause.
"'There's reason in that,' they said. 'No doubt the hostage
knows the nature of the Communists. But what to do?'
"I was impatient.
"'What to do?' I shouted. 'Do you want a revolutionist to tell you
what to do? Barricade yourselves, idiots. Barricade yourselves, and
stand siege till the Versaillais come.'
"Their good sense prevailed; they jumped at the suggestion.
"'It is an idea; let us barricade ourselves. Untie the hostage's
hands, that he may help.'
"It was done, and I, who had shown the people how to build so
many barricades in the streets, now taught these forty-two
policemen to build a barricade in the corridor of the prison of La
Roquette. We made it by taking the mattresses from the beds in the
cells, and laying them one upon another carefully and symmetrically,
as one builds a wall with bricks. The barrier was so high that no one
could climb over it; so thick that no bullet could pass through it; so
solid that it could only be pulled down, piece by piece, by
unmolested labourers; and scarcely had we finished it before we
found the need of it. We heard the voice of Citizen Ferré himself, no
longer promising safe-conduct or immunity.
"'Since you won't come out of it by yourselves, we'll have to
fetch you out. Charge, my lads, charge, and we'll treat them as we
did the gendarmes in the Rue Haxo.'
"Hurling themselves against our woollen wall, they tried to push
it before them by sheer weight. It did not yield an inch. Was it not
built by a revolutionary leader? And were there not forty-two
sergents de ville supporting it with their weight upon the other side?
"'Pull it down, bit by bit, from the top, then,' Ferré shouted; and
we heard a noise as of a man being hoisted on to another's
shoulders, and, for an instant, had a glimpse of a villainously ugly
face between the barrier and the ceiling.
"But only for an instant. Père Dubois—he also hoisted on to a
neighbour's shoulders—hurled at the man a piece of crockery
intended for a very different purpose. It smote him full upon the
jaw, knocking teeth down his throat. Swearing a terrible oath, he
disappeared, and no one took his place. Carried away by the joy of
battle, I shouted to the Communist, who had so lately been my
friend and ally—
"'Citizen Ferré! Is this the way you raise the tone of revolutions?'
"'Pig! We are not beaten yet,' my old friend answered; and, as
we heard him retreating down the staircase, we wondered what
fresh devilry he had in his mind.
"Presently we heard a fresh noise above our heads. Somebody
was breaking through the ceiling. Armed though we were, after a
fashion, with cudgels and lances, which we had made by breaking
up the woodwork of the beds, we knew that we could not hold out
long against an assault from that place of vantage. There seemed
nothing to be done save to sell our lives as dearly as we could. But,
just as we had made up our minds to this, we heard a voice that
reassured us.
"'Hush! Do not be afraid! We are your fellow-prisoners.' And the
head which revealed itself through the broken planks—the head at
which Père Dubois was preparing to hurl a fresh piece of crockery—
proved to be the head of one of the parish priests of Belleville,
whom the Communists had locked up as their hostages. The
sergents de ville greeted him with shouts of welcome.
"'Listen!' said the good old man. 'We have barricaded ourselves,
and shall fight for our lives if need be. But, in the meantime, as your
lives also are in danger, we would strengthen you with our prayers
and with our blessing. Kneel, my brothers, kneel.'
"We knelt. It was a strange ceremony—such a ceremony as has
never been, perhaps, in the world, before or since. There was no
confession. The time was precious and too short for that. But, as we
fell upon our knees and bowed our heads, the holy man solemnly
pronounced absolution and chanted benediction. Even I—Jean
Antoine Stromboli Kosnapulski, of whom priests in a general way do
not approve—took absolution and benediction with the rest. Then
the cry was raised—
"'Look out! They are returning!'
"We went to our post again, wondering what fresh device our
enemies had hit upon. It was not long before we knew. They had
released the convicts—the thieves and murderers who had been in
prison long before the Commune made special prisoners of its own—
and had enlisted them as willing allies against their natural enemies,
the sergents de ville. We heard them fraternising in the yard.
"'Long live the Communists!' cried the one.
"'Long live the convicts!' replied the others.
"And then, once more, we heard the brutal voice of Citizen
Ferré—
"'Now, pigs! Your hour is come. Since you won't come out any
other way, we're going to burn you out.'
"In another instant they had poured petroleum over our
mattress barricade and set light to it. It burnt slowly, for wool,
packed close, is but a poor combustible, and there was no draught
to coax the flames. The whole corridor, however, was filled with a
suffocating stench. We coughed and choked, though we had burst
every window open. It was only a question of time. Our barricade
must ultimately yield to this attack.
"'Water! Oh, for water!' was the cry that went up on every
hand. We had no water save the filthy stuff in which the prisoners
had washed, over and over again, since their cells had last been
cleaned. So far as we could, we soaked the mattresses with these
slops. They added to the stench, but hardly helped to quench the
fire. With luck we might hold out for half an hour. Longer we could
not hope to hold.
"The sergents de ville were losing heart and energy. They had
thrown themselves on the floor, because the smoke was less there,
and lay about the passage like so many dying men. And Père Dubois
whispered to me—
"'Oh, think of something! For Fifine's sake, think of something!'
"An inspiration came to me. I ran to the window, braving the
risk of rifle-bullets, and put my head out of it, and shouted with all
my might—
"'The Versaillais! The Versaillais! Hold out! Hold out! I see the
Versaillais coming!'
"The effect was marvellous. The sergents de ville leapt to their
feet again. The convicts scurried down the staircase, tumbling over
each other in their haste. They streamed out into the courtyard and
became a frightened mob. Their terror was contagious, and every
man sought to save his skin. They peeped cautiously through every
open door, and when they saw the coast clear made a run for it.
They fetched ladders out of unexpected places and scaled the prison
walls with them. Citizen Ferré himself attempted to swarm up a
water-pipe.
"And there were no Versaillais coming. I had invented them
because I saw that they were necessary to save the situation. They
did not actually come until more than two hours afterwards; though,
in the meantime, we saw nothing of my old friends, Citizen Ferré
and his companions.
"At last, however, the little men with the red trousers came
marching into the courtyard, and I said—
"'Let me go down and explain. The Colonel will be surprised to
see me.'
"Well might he be surprised, even though he failed to recognise
me. My frock-coat was singed and torn; my silk hat was battered,
and the nap on it was ruffled; my face was as black as a negro's
from the smoke. I must, indeed, have looked a pitiable object as I
issued from the door, exclaiming—
"'Welcome, M. le Colonel. I am Jean Antoine——'
"A bullet splashed against the wall beside me, and I withdrew.
Tearing off my red sash, and borrowing a helmet and a tunic from
one of the sergents de ville, I reappeared and resumed my friendly
greeting.
"'Welcome, M. le Colonel. Herewith I restore to you forty-two
policemen whom my old friend Ferré would have shot. I have raised
the tone of revolution. I am Jean Antoine Stromboli Kosnapulski.'
"I bowed profoundly, and this time no rifle-bullets interrupted
my discourse.
"The Colonel merely said—
"'Whoever you are, you'll remain under arrest while the truth of
your story is inquired into.'
"'That, M. le Colonel,' I said, 'is only reasonable. I am sorry that
I have no sword to surrender to you. My only weapon has been a
piece of crockery. If you wish that it should be formally handed to
you, I will go and fetch it.'
"He did not wish it, but proceeded to try me by drum-head
court-martial on the spot. With what result you can conjecture. A
prisoner who has forty-two policemen vying with each other to give
evidence in his favour has little to fear even from an improvised
military tribunal.
"In consideration of my services to the police I was dismissed,
within two minutes, without a stain upon my character, and even
thanked for what I had done to raise the tone of revolution.
"To think that, after that, I should have lived to be chased by
policemen, as I was yesterday, through the kitchen and offices, out
of the back door! Fifine, my angel Fifine! what would you have said
if you had lived to hear of it?"

THE SECRET SOCIETY.

There is no more mysterious, and no more misrepresented society


than the Camorra. I never understood its nature or its objects until I
heard Stromboli's story. He went to Naples and discovered the
Camorra. He investigated it and found out exactly what manner of
society it was. But let him tell the story in his own words:—

"I had no sooner come to Naples," he said, "than the Camorra


forced itself upon my notice. Even as I landed from the steamer, I
observed the boatman who had brought ashore my modest luggage
surreptitiously slipping a small coin into the hand of a stalwart
bystander, gaudily attired in the costume that one associates with
brigandage, who had all the air of accepting it, not as an alms, but
his due. My watchful curiosity was at once excited.
"'Who is that man, then?' I asked the sailor curtly.
"'It is the Camorrista, signor—it is the Camorra man, sir,' he
answered, in matter-of-fact tones, as he lifted my luggage into a
carriage.
"I began to wonder.
"My carriage rattled over the stones and set me down in my
hotel. Another stalwart individual was waiting there. He, too, was an
ornamental person; he wore wide velvet breeches with gold lace
upon them, a loose white shirt, a red sash, and a gaudy silk
handkerchief knotted over his head. And he, too, reached out his
hand to claim a coin which my driver dropped into his palm.
"'Who is that man?' I asked again, and got the same answer as
before—
"'It is the Camorrista, signor—it is the Camorra man.'
"'And why do you give him money?' I inquired further.
"'Because he demands it, signor,' the man replied; and he
jumped on to his box and drove away before I had time to pursue
the subject any further.
"I went on wondering.
"Evidently this was a strange country to which I had come—a
country in which you had only to demand money in the name of a
mysterious society in order to obtain it. Would people also give
money to me, in case of need, if I also dressed gaudily and stepped
forward with a bold address, saying 'I am the Camorra man'? The
question furnished food for thought.
"'To-morrow,' I said to myself, 'I will investigate this matter. In
the meantime, I will dismiss it from my mind, and dine.'
"I ceased wondering, therefore, and ate my dinner, and strolled
out into the city to divert myself.
"My diversion took the form of a game of billiards in a café,
which was not, I must admit, one of the most fashionable cafés in
the city. It was, in fact, a café in the dark and narrow street known
as the Tre Capelle—the street of the Three Hats. There was a better
opportunity of observing the life of the people there than in the
more fashionable quarters.
"But I did not merely observe the life of the people. I also won
the people's money. My skill at billiards was not, in those days,
inconsiderable. In several successive games I was the victor, and
each game was played for a higher stake than the game preceding
it. Altogether, perhaps, I won enough to pay my hotel bill for a
week. Then I pocketed my profits and bade the company a
courteous 'Good evening.'
"'Addio!' I said, waving my broad-brimmed hat and smiling; and
then took my umbrella—for it had been raining—and stepped
jauntily into the street.
"Hardly had I gone half-a-dozen steps when a stranger stepped
out of the shadow and approached me.
"The street was dimly lighted with oil lamps, and I could not see
him well, but I saw that he, too, was gaudy and robust. His small
round felt hat had cocks' feathers in it, and he wore earrings which
glittered in the lamplight. He brandished a cudgel in his right hand,
while his left was extended like a mendicant's.
"'Our share, signor?' he asked peremptorily, if not quite
truculently.
"'Whose share? And whom may I have the honour of
addressing?' I retorted with no less determination.
"'Il Camorrista—the Camorra man,' he rejoined, in just such
accents as he might have used had he been able to announce
himself as the policeman on duty in the neighbourhood.
"A sudden curiosity seized me. How would this imperious man
behave, I wondered, if I were to prod him quite suddenly and very
violently in the pit of the stomach with the point of my umbrella? It
seemed an interesting experiment, and one well worth trying.
"'Here, take your share!' I cried, and lunged at him with the skill
and rapidity of one accustomed to the foils.
"My eye and aim were sure, and the result was satisfactory. The
ferrule struck my antagonist just beneath the breast-bone—at that
sensitive point, in fact, which your prizefighters always aim at.
"He uttered a cry of pain, staggered, doubled up, and fell in a
heap upon the ground.
"'Addio, Camorrista—farewell, Camorra man,' I said, and strode
away with dignity, to the amazement and admiration of the
onlookers.
"But my experience had interested me. I felt that I had lighted
upon a mystery, and I was resolved to probe it to the bottom. To
that end I rang my bedroom bell the next morning and put a
question to the chambermaid who answered it.
"'Tell me, Lucia, what is the Camorra?'
"She stared at me as blankly as though I had requested her to
define space or time.
"'What is the Camorra, signor? The Camorra, signor—it is the
Camorra,' she replied.
"It was an inadequate explanation, but I thought I might
succeed better if I tried a gentler method. So I kissed her and took
her hand caressingly.
"'Voyons, sweetheart!' I said. 'There is no need for you to be
afraid. I will protect you. Tell me everything that you know about
this Camorra.'
"To my amazement, she snatched her hand away and ran
screaming down the corridor.
"I changed my tone.
"'Voyons, baby! Send up the landlord to me!' I shouted after
her.
"He came with the indignant air of a man whose establishment I
had outraged by the commission of an impropriety; but I received
him with an indignation equal to his own.
"'Voyons, landlord!' I exclaimed. 'What is the meaning of all
this? Is this house a lunatic asylum?'
"He replied that it was nothing of the kind.
"'It is because my house is not a lunatic asylum,' he added, 'that
I invite the signor to leave it without delay.'
"It was natural that I should express myself strongly.
"'Leave your house!' I said. 'Neither your manners nor your
macaronis tempt me to make a long stay in it. But before I go, I
must have an answer to a question. I insist. Attend!'
"He glared, as though knowing that the question would be an
awkward one. I met his gaze and put the question firmly.
"'What I want to know is this: What is the Camorra? Why have I
been invited—unceremoniously and with menaces—to subscribe to
it? To what purpose would my subscription have been devoted had I
paid it instead of felling the agent of the society—the collector of its
tribute—with an unexpected blow?'
"But I did not get the plain answer to the plain question which I
thought I had a right to. Nor did I get admiration for my courageous
feat of arms. My landlord's face expressed only amazement and
dismay. He threw up his arms with the gesture of a man abandoning
hope.
"'The signor struck the Camorrista?'
"'I have already told you that I struck him with great force, to
the astonishment of the spectators. I left him in the gutter of the
street of——'
"'Then the life of the signor is in peril, and my life also. The
vengeance of the Camorra——'
"'What is this Camorra, then?' I interrupted.
"'The Camorra is——"
"'Well?'
"'The Camorra is the Camorra. It is forbidden to say more.'
"'But I command you to say more.'
"My tone—perhaps my movements also—implied a vague threat
of violence. But the landlord did not wait for me to lay hands on him.
He fled, as the chambermaid had fled; but he slammed the door
after him and turned the key and locked me in. Then he called
through the key-hole—
"'Will the signor forgive me? It is the only way. I will arrange for
the signor's safety before the Camorra——'
"I heard no more, for I was hanging on to the knob, rattling the
door, and kicking at the panels.
"They would not yield, being solid, as though built in the old
days when any house might be required at any time to stand a
siege. I assailed the door, first with a chair, and then with a wash-
hand jug, with no result except that I broke both of them. Then I sat
down and reflected. My window was on the fourth floor and looked
on the hotel courtyard, so that escape in that direction was
impossible. But there still remained one other plan. I had my
revolver.

"I assailed the door, first with a chair."


"'Stand clear there, everybody, while I shoot!' I called through
the key-hole; and then I pulled the trigger and blew away the lock.
"In the silence which followed the report I heard the tramp of
heavy footsteps in the corridor. Still gripping the smoking weapon, I
stepped outside to receive my visitors.
"Imagine my surprise when I saw that they were policemen,
and that my landlord was guiding them to my apartment, carrying
the key. His language was polite, however, and he offered an
explanation.
"'It is arranged,' he said. 'If the signor will be so kind as to pay
his bill, these gentlemen will afford the signor the protection that is
necessary for him.'
"'And the Camorra?' I asked.
"'Hush!' he replied, lifting both his hand to enjoin silence.
"So I paid my bill and accompanied my police escort, trying to
think more kindly of my landlord.
"'The good man means well," I said to myself. 'He fears lest I
should be assassinated by this terrible and all-pervading society. He
procures me police protection. I will write to him and say that it was
quite unnecessary, but that I am nevertheless obliged to him.' Then,
as we got out into the street, I proceeded to enter into conversation
with my escort.
"'Voyons!' I said to them. 'You, at least, my friends, will be able
to give me some information about this mysterious Camorra.'
"'Silence!' in authoritative accents was the only answer that I
got.
"'Have a glass of wine with me, then, before we go any further,'
I suggested.
"They agreed to that, and sat round me outside a café and
drank at my expense; but the refreshment did not make them much
more communicative. The Camorra was the Camorra. It was secret;
it was powerful. It helped its friends, and punished its enemies
without mercy. The people who did not belong to it had to pay
tribute to those who did. That was all the information I could get.
"'It must be a society that works for the revolution,' I suggested.
"'Silence!' came the answer again, in accents half savage and
half scared; and we left the café and marched on.
"It occurred to me that we had gone far enough, and that I did
not need police protection any longer. I said so, adding:
"'Where are you taking me, my friends? To the railway-station,
or to the steamboat?'
"They laughed. It is not often that a policeman laughs, but
these policemen laughed like countrymen at the theatre seeing their
first farce.
"'Where are we taking you?' they cackled, with horrible
grimaces.
"'Precisely. That is my question?'
"'Well, to the prison, of course. Where else?'
"'To the prison, indeed! But I am under police protection!'
"They roared with laughter.
"'Under police protection! It is a way of putting it, when one has
a light heart and loves a joke.'
"'A joke'?"
"'Certainly, seeing that you are under arrest.'
"'On what charge?'
"They shrugged their shoulders like one man.
"'Who knows? There may be a charge; there may be none. It
may be sustained; it may break down. Who knows?"
"'Do you mean to tell me that at Naples a stranger may be
arrested——'
"'Obviously.'
"'With no more ceremony than if he were being asked to
dinner? I do not believe it. There is some mystery here. The
Camorra——'
"'Silence!'
"'The Camorra is at the bottom of this. The Camorra and the
landlord are in a conspiracy against me——'
"'It is possible. We have no information on the subject.'
"'But I will resist their machinations. I will confound them. I will
probe the mystery to the bottom. I am Jean Antoine——'
"'It is possible—we have no information. But here is the prison.'
"Resistance was out of the question. It seemed likely, indeed,
that I should be safer in the prison than outside it. There, at least, I
might find some intelligent person who would listen to my
explanation; there, at least, I should have respite from the
attentions of the Camorra, and a plain answer to a civil question.
"Patience!" I said to myself, as the great gate clanged behind
me; and it soon became evident that I should have need of
patience. For this Neapolitan prison was quite different from any
other prison that I had ever been confined in.
"There was no ceremonious reception of new-comers by the
authorities; they did not even trouble to ask who one was.
"There was no privacy. Separate cells were only provided for
prisoners condemned to death—a heavy price to pay for such a
privilege. For the rest, the inmates were herded together in great
courtyards, with no distinction between those convicted and those
awaiting trial, and no one, so far as I could see, to supervise their
conduct. It was, as it were, a republic of evil-doers in which I was
turned loose to take my chance and find my level.
"'There are your quarters. Soup and macaroni are served out
twice daily. The other prisoners will tell you where you can sleep,'
said the gaoler curtly.
"'But I demand to know——' I protested.
"'Silence! Don't bother me with your foolish questions,' he
replied, and slammed a door and disappeared.
"So I got no satisfaction from him, and my heart sank within
me. A period of ennui—a term of weary waiting, with discomfort but
without excitement—that seemed to be the fate in store for me. But
once more—so far, at least, as the excitement was concerned—I was
mistaken. A fellow prisoner provided me with immediate excitement.
"He was tall, lithe, masterful in demeanour. He approached me,
like the man whom I had prodded in the stomach after my game of
billiards, with one hand extended for a donation, and the other
brandishing a cudgel.
"'The due?' he demanded curtly.
"'What due?' I asked calmly.
"'To buy oil for the lamp of the Madonna.'
"It was a formula, though I did not know it. But I was not, as
you may suppose, in a conciliatory temper. I drew myself up
haughtily and said: 'My good man, I was not aware that I had the
pleasure of your acquaintance.'
"He introduced himself.
"'Io sono il Camorrista—I am the Camorra man.'
"It was a blow to me. Were my footsteps to be dogged there,
even in prison, by the representatives of this mysterious society? It
seemed so. Yet, in a sense, I was glad to meet it there. It was a
chance of solving the perplexing mystery, and I determined to solve
it, even at the risk of a temporary misunderstanding.
"I fixed my eyes on the man, showing that I was ready to
defend myself, and spoke to him seriously.
"'Voyons!' I said to him. 'The last Camorra man who was rude to
me is now suffering from a pain in the pit of the stomach, and he
wasn't either so rude or so ugly as you are.'
"'Corpo di Baccho!' the man exclaimed, making as though he
would strike me, yet hesitating before my determined attitude.
"'But let us be reasonable,' I continued. 'Let me make a
proposal to you.'
"'Speak!'
"'Ever since my arrival at Naples, I have been curious to know
what your Camorra is, and what it does with the money which it
collects with such systematic industry. If you will tell me, I will give
you a piece of gold; and if you do not tell me, I will give you
nothing.'
"Would he have yielded if we had been alone? I cannot say. A
knot of our fellow prisoners had gathered round us, and his pride
was at stake.
"'Silence! You have not to ask questions, but to pay.'
"My temper was roused, and I resolved to precipitate the crisis.
I flung a piece of gold—part of my winnings at the billiard-table—on
the ground, and challenged him.
"'Voyons!' I cried. 'No one shall say that Jean Antoine Stromboli
Kosnapulski is mean. There is your money, and I will fight you for it.'
"A fierce cry of approval went up from the bystanders.
"'A duel! A duel!' they exclaimed in chorus, and the
representative of the Camorra—to do him justice—did not shrink
from the encounter.
"'Antonio!' he called to a companion, 'fetch knives!' And I made
the strange discovery that, in a Neapolitan prison, the prisoners
were allowed to borrow knives for the settlement of their affairs of
honour.
"But I would not have a knife. It is a weapon in the use of
which I have had little practice.
"'No, no!' I cried. 'I will take no unfair advantage of you. It shall
be your knife against my umbrella. Does that seem fair to you?'
"He seemed to hesitate, as one who dreads an unfamiliar
danger; but the public opinion of the prison was in favour of my
proposal. It had novelty; it promised strange spectacular effects
calculated to relieve the tedium of prison life. So my opponent found
it impossible to refuse.
"'As you prefer,' he said; and seconds were appointed and a
space was cleared. At the given word, we advanced to meet each
other from opposite corners of the court-yard.
"Do not ask me for details of the combat! I am not vain.
Therefore I will not dwell upon them at undue length.
"It was like this. The Camorrista at first advanced stealthily, with
long, catlike strides; and I on my part advanced firmly, holding
myself upright, like a master of fencing of the French rather than the
Italian school. Then the Camorrista launched himself upon me like
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

You might also like