SlideShare a Scribd company logo
Objects First With Java A Practical Introduction
Using Bluej 1st Edition David J Barnes download
https://ebookbell.com/product/objects-first-with-java-a-
practical-introduction-using-bluej-1st-edition-david-j-
barnes-973080
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.
Objects First With Java A Practical Introduction Using Bluej 5th David
J Barnes
https://ebookbell.com/product/objects-first-with-java-a-practical-
introduction-using-bluej-5th-david-j-barnes-51623770
Objects First With Java A Practical Introduction Using Bluej 4 Ed
Barnes
https://ebookbell.com/product/objects-first-with-java-a-practical-
introduction-using-bluej-4-ed-barnes-22004612
Objects First With Java A Practical Introduction Using Bluej 5th
Edition David J Barnes
https://ebookbell.com/product/objects-first-with-java-a-practical-
introduction-using-bluej-5th-edition-david-j-barnes-4541212
Objects First With Java A Practical Introduction Using Bluej 6th David
J Barnes Michael Klling
https://ebookbell.com/product/objects-first-with-java-a-practical-
introduction-using-bluej-6th-david-j-barnes-michael-klling-10670742
Objects First With Java A Practical Introduction Using Bluej 6th
Edition David Barnes
https://ebookbell.com/product/objects-first-with-java-a-practical-
introduction-using-bluej-6th-edition-david-barnes-12118812
Objects First With Java A Practical Introduction Using Bluej David J
Barnes
https://ebookbell.com/product/objects-first-with-java-a-practical-
introduction-using-bluej-david-j-barnes-4333392
Lets Hope Theyre Friendly The Kaikoura Ufos First Verified Film
Encounter With Unidentified Flying Objects Quentin Fogarty
https://ebookbell.com/product/lets-hope-theyre-friendly-the-kaikoura-
ufos-first-verified-film-encounter-with-unidentified-flying-objects-
quentin-fogarty-36046516
Objectrole Modeling Fundamentals A Practical Guide To Data Modeling
With Orm First Terry Halpin
https://ebookbell.com/product/objectrole-modeling-fundamentals-a-
practical-guide-to-data-modeling-with-orm-first-terry-halpin-5526556
A First Course In Computational Physics And Objectoriented Programming
With C Hardback With Cdrom David Yevick
https://ebookbell.com/product/a-first-course-in-computational-physics-
and-objectoriented-programming-with-c-hardback-with-cdrom-david-
yevick-47506166
Objects First With Java A Practical Introduction Using Bluej 1st Edition David J Barnes
1
David Barnes Michael Kölling
Objects First with Java
A Practical Introduction using BlueJ
FOR EVALUATION ONLY
NOT FOR DISTRIBUTION
Copyright © Barnes, Kölling, 2002
Pearson Education / Prentice Hall
ISBN 0-13-044929-6
2
Contents
LIST OF PROJECTS DISCUSSED IN DETAIL IN THIS BOOK 11
PREFACE TO THE INSTRUCTOR 14
PART I: Foundations of object orientation
CHAPTER 1 OBJECTS AND CLASSES 23
1.1 Objects and classes 23
1.2 Creating objects 24
1.3 Calling methods 25
1.4 Parameters 26
1.5 Data types 27
1.6 Multiple instances 28
1.7 State 28
1.8 What is in an object? 29
1.9 Object interaction 31
1.10 Source code 32
1.11 Another example 33
1.12 Return values 33
1.13 Objects as parameters 34
1.14 Summary 36
Terms introduced in this chapter 36
Concept summary 36
CHAPTER 2 UNDERSTANDING CLASS DEFINITIONS 38
2.1 Ticket machines 38
2.1.1 Exploring the behavior of a naïve ticket machine 39
2.2 Examining a class definition 39
2.3 Fields, constructors, and methods 42
2.3.2 Fields 43
2.3.3 Constructors 44
2.4 Passing data via parameters 46
2.5 Assignment 47
2.6 Accessor methods 48
2.7 Mutator methods 50
2.8 Printing from methods 52
2.9 Summary of the naïve ticket machine 54
3
2.10 Reflecting on the design of the ticket machine 55
2.11 Making choices: the conditional statement 56
2.12 A further conditional-statement example 59
2.13 Local variables 60
2.14 Fields, parameters, and local variables 61
2.15 Summary of the better ticket machine 62
2.16 Reviewing a familiar example 62
2.17 Summary 65
Terms introduced in this chapter 66
Concept summary 66
CHAPTER 3 OBJECT INTERACTION 70
3.1 The clock example 70
3.2 Abstraction and modularization 71
3.3 Abstraction in software 72
3.4 Modularization in the clock example 72
3.5 Implementing the clock display 73
3.6 Class diagrams versus object diagrams 74
3.7 Primitive types and object types 75
3.8 The ClockDisplay source code 76
3.8.1 Class NumberDisplay 77
3.8.2 String concatenation 78
3.8.3 The modulo operator 80
3.8.4 Class ClockDisplay 80
3.9 Objects creating objects 83
3.10 Multiple constructors 84
3.11 Method calls 85
3.11.1 Internal method calls 85
3.11.2 External method calls 85
3.11.3 Summary of the clock display 87
3.12 Another example of object interaction 87
3.12.1 The mail system example 88
3.12.2 The this keyword 89
3.13 Using a debugger 91
3.13.2 Setting breakpoints 91
3.13.3 Single stepping 93
3.13.4 Stepping into methods 94
3.14 Method calling revisited 95
3.15 Summary 96
Terms introduced in this chapter 96
Concept summary 97
CHAPTER 4 GROUPING OBJECTS 98
4.1 Grouping objects in flexible-size collections 98
4.2 A personal notebook 99
4.3 A first look at library classes 99
4.3.1 An example of using a library 99
4.4 Object structures with collections 101
4
4.5 Numbering within collections 103
4.6 Removing an item from a collection 103
4.7 Processing a whole collection 104
4.7.1 The while loop 105
4.7.2 Iterating over a collection 107
4.7.3 Index access versus iterators 108
4.8 Summary of the notebook example 108
4.9 Another example – an auction system 109
4.9.1 The Lot class 109
4.9.2 The Auction class 110
4.9.3 Casting 112
4.10 Fixed-size collections 113
4.10.1 A log-file analyzer 114
4.10.2 Declaring array variables 116
4.10.3 Creating array objects 117
4.10.4 Using array objects 118
4.10.5 Analyzing the log file 119
4.10.6 The for loop 119
4.11 Summary 123
Terms introduced in this chapter 123
Concept summary 123
CHAPTER 5 MORE SOPHISTICATED BEHAVIOR 125
5.1 Documentation for library classes 126
5.2 The TechSupport System 127
5.2.1 Exploring the TechSupport System 127
5.2.2 Reading the code 131
5.3 Reading class documentation 132
5.3.2 Interfaces versus implementation 133
5.3.3 Using library-class methods 134
5.3.4 Checking string equality 136
5.4 Adding Random behavior 136
5.4.1 The Random class 137
5.4.2 Random numbers with limited range 138
5.4.3 Generating random responses 139
5.5 Packages and import 141
5.6 Using maps for associations 142
5.6.2 The concept of a map 143
5.6.3 Using a HashMap 143
5.6.4 Using a map for the TechSupport system 144
5.7 Using sets 146
5.8 Tokenizing Strings 147
5.9 Finishing the TechSupport system 148
5.10 Writing class documentation 150
5.10.1 Using javadoc in BlueJ 151
5.10.2 Elements of class documentation 151
5.11 Public versus private 153
5.11.1 Information hiding 154
5.11.2 Private methods and public fields 154
5.12 Learning about classes from their interfaces 155
5.13 Class variables and constants 158
5
5.13.2 The static keyword 158
5.13.3 Constants 160
5.14 Summary 160
Terms introduced in this chapter 160
Concept summary 161
CHAPTER 6 WELL-BEHAVED OBJECTS 163
6.1 Introduction 163
6.2 Testing and debugging 164
6.3 Unit testing within BlueJ 164
6.3.1 Using inspectors 168
6.3.2 Positive versus negative testing 170
6.4 Test automation 170
6.4.1 Regression testing 170
6.4.2 Automated checking of test results 173
6.5 Modularization and interfaces 174
6.6 A debugging scenario 176
6.7 Commenting and style 176
6.8 Manual walkthroughs 177
6.8.1 A high-level walkthrough 178
6.8.2 Checking state with a walkthrough 180
6.8.3 Verbal walkthroughs 182
6.9 Print statements 183
6.9.2 Turning debugging information on or off 185
6.10 Debuggers 186
6.11 Putting the techniques into practice 187
Terms introduced in this chapter 187
Concept summary 187
CHAPTER 7 DESIGNING CLASSES 188
7.1 Introduction 188
7.2 The world-of-zuul game example 190
7.3 Introduction to coupling and cohesion 192
7.4 Code duplication 193
7.5 Making extensions 196
7.5.1 The task 196
7.5.2 Finding the relevant source code 196
7.6 Coupling 198
7.6.1 Using encapsulation to reduce coupling 198
7.7 Responsibility-driven design 202
7.7.1 Responsibilities and coupling 202
7.8 Localizing change 205
7.9 Implicit coupling 205
7.10 Thinking ahead 208
7.11 Cohesion 209
7.11.1 Cohesion of methods 209
7.11.2 Cohesion of classes 210
7.11.3 Cohesion for readability 211
6
7.11.4 Cohesion for reuse 212
7.12 Refactoring 213
7.12.1 Refactoring and testing 213
7.12.2 An example of refactoring 214
7.13 Design guidelines 217
7.14 Executing without BlueJ 218
7.14.1 Class methods 218
7.14.2 The main method 219
7.14.3 Limitations of class methods 220
7.15 Summary 220
Terms introduced in this chapter 220
Concept summary 220
PART II: Application structures
CHAPTER 8 IMPROVING STRUCTURE WITH INHERITANCE 223
8.1 The DoME example 223
8.1.1 DoME classes and objects 224
8.1.2 DoME source code 226
8.1.3 Discussion of the DoME application 231
8.2 Using inheritance 232
8.3 Inheritance hierarchies 234
8.4 Inheritance in Java 235
8.4.1 Inheritance and access-rights 236
8.4.2 Inheritance and initialization 236
8.5 DoME: Adding other item types 238
8.6 Advantages of inheritance (so far) 240
8.7 Subtyping 240
8.7.1 Subclasses and subtypes 242
8.7.2 Subtyping and assignment 242
8.7.3 Subtyping and parameter passing 243
8.7.4 Polymorphic variables 244
8.8 The Object class 245
8.9 Polymorphic collections 246
8.9.1 Element types 246
8.9.2 Casting revisited 247
8.9.3 Wrapper classes 248
8.10 The collection hierarchy 249
8.11 Summary 249
Terms introduced in this chapter 250
Concept summary 250
CHAPTER 9 MORE ABOUT INHERITANCE 252
9.1 The problem: DoME’s print method 252
9.2 Static type and dynamic type 253
7
9.2.2 Calling print from Database 255
9.3 Overriding 257
9.4 Dynamic method lookup 258
9.5 Super call in methods 261
9.6 Method polymorphism 262
9.7 Object methods: toString 262
9.8 Protected access 265
9.9 Another example of inheritance with overriding 267
9.10 Summary 270
Terms introduced in this chapter 270
Concept summary 270
CHAPTER 10 FURTHER ABSTRACTION TECHNIQUES 271
10.1 Simulations 271
10.2 The foxes-and-rabbits simulation 272
10.2.1 The foxes-and-rabbits project 273
10.2.2 The Rabbit class 275
10.2.3 The Fox class 278
10.2.4 The Simulator class – setup 280
10.2.5 The Simulator class – a simulation step 283
10.2.6 Taking steps to improve the simulation 284
10.3 Abstract classes 285
10.3.2 The Animal superclass 285
10.3.3 Abstract methods 286
10.3.4 Abstract classes 288
10.4 More abstract methods 290
10.5 Multiple inheritance 292
10.5.1 An Actor class 292
10.5.2 Flexibility through abstraction 293
10.5.3 Selective drawing 294
10.5.4 Drawable actors: multiple inheritance 295
10.6 Interfaces 295
10.6.1 An Actor interface 295
10.6.2 Multiple inheritance of interfaces 297
10.6.3 Interfaces as types 297
10.6.4 Interfaces as specifications 298
10.6.5 A further example of interfaces 299
10.6.6 Abstract class or interface? 301
10.7 Summary of inheritance 301
10.8 Summary 301
Terms introduced in this chapter 302
Concept summary 302
CHAPTER 11 HANDLING ERRORS 303
11.1 The address-book project 304
11.2 Defensive programming 307
11.2.1 Client-server interaction 307
11.2.2 Argument checking 309
11.3 Server error reporting 310
8
11.3.2 Notifying the user 311
11.3.3 Notifying the client object 311
11.4 Exception-throwing principles 314
11.4.1 Throwing an exception 314
11.4.2 Exception classes 315
11.4.3 The effect of an exception 317
11.4.4 Unchecked exceptions 317
11.4.5 Preventing object creation 319
11.5 Exception handling 320
11.5.1 Checked exceptions: the throws clause 320
11.5.2 Catching exceptions: the try block 320
11.5.3 Throwing and catching multiple exceptions 322
11.5.4 Propagating an exception 323
11.5.5 The finally clause 323
11.6 Defining new exception classes 324
11.7 Error recovery and avoidance 326
11.7.1 Error recovery 326
11.7.2 Error avoidance 327
11.8 Case study: Text input-output 329
11.8.1 Readers, writers, and streams 330
11.8.2 The address-book-io project 330
11.8.3 Text output with FileWriter 332
11.8.4 Text input with FileReader 333
11.8.5 Object serialization 334
11.9 Summary 335
Terms introduced in this chapter 335
Concept summary 335
CHAPTER 12 DESIGNING APPLICATIONS 336
12.1 Analysis and design 336
12.1.1 The verb/noun method 337
12.1.2 The cinema booking example 337
12.1.3 Discovering classes 337
12.1.4 Using CRC cards 338
12.1.5 Scenarios 339
12.2 Class design 343
12.2.1 Designing class interfaces 344
12.2.2 User interface design 345
12.3 Documentation 345
12.4 Cooperation 346
12.5 Prototyping 346
12.6 Software growth 347
12.6.1 Waterfall model 347
12.6.2 Iterative development 348
12.7 Using design patterns 349
12.7.1 Structure of a pattern 350
12.7.2 Decorator 350
12.7.3 Singleton 351
12.7.4 Factory method 352
12.7.5 Observer 352
12.7.6 Pattern summary 354
9
12.8 Summary 355
Terms introduced in this chapter 355
Concept summary 355
CHAPTER 13 A CASE STUDY 357
13.1 The case study 357
13.1.1 The problem description 357
13.2 Analysis and design 358
13.2.1 Discovering classes 358
13.2.2 Using CRC cards 359
13.2.3 Scenarios 360
13.3 Class design 362
13.3.1 Designing class interfaces 362
13.3.2 Collaborators 362
13.3.3 The outline implementation 363
13.3.4 Testing 367
13.3.5 Some remaining issues 367
13.4 Iterative development 367
13.4.1 Development steps 367
13.4.2 A first stage 369
13.4.3 Testing the first stage 372
13.4.4 A later stage of development 373
13.4.5 Further ideas for development 375
13.4.6 Reuse 375
13.5 Another example 376
13.6 Taking things further 376
APPENDIX A WORKING WITH A BLUEJ PROJECT 377
A.1 Installing BlueJ 377
A.2 Opening a project 377
APPENDIX B JAVA DATA TYPES 378
B.1 Primitive types 378
B.2 Object types 379
APPENDIX C JAVA CONTROL STRUCTURES 380
C.1 Selection statements 380
C.2 Loops 382
13.7 Exceptions 383
APPENDIX D OPERATORS 384
D.1 Arithmetic expressions 384
10
APPENDIX E RUNNING JAVA WITHOUT BLUEJ 385
E.1 Executing without BlueJ 385
E.2 Creating executable Jar files 387
E.3 Developing without BlueJ 387
APPENDIX F CONFIGURING BLUEJ 388
11
List of projects discussed in detail in this book
shapes chapter 1
Simple drawing with some geometrical shapes; illustrates creation of objects,
method calling, and parameters.
picture chapter 1
An example using shape objects to draw a picture; introduces source code, Java
syntax, and compilation.
lab-classes chapter 1, chapter 2, chapter 8
A simple example with classes of students; illustrates objects, fields, and
methods. Used again in chapter 8 to add inheritance.
ticket-machine chapter 2
A simulation of a ticket vending machine for train tickets; introduces more
about fields, constructors, accessor and mutator methods, parameters, and
some simple statements.
book chapter 2
Storing details of a book. Reinforcing the constructs used in the ticket-machine
example.
clock-display chapter 3
An implementation of a display for a digital clock; illustrates the concepts of
abstraction, modularization and object interaction.
mail system chapter 3
A simple simulation of an email system. Used to demonstrate object creation
and interaction.
notebook chapter 4
An implementation of a (simple) electronic note book; used to introduce
collections and loops.
auction chapter 4
An auction system. More about collections and loops, this time with iterators.
weblog-analyzer chapter 4
A program to analyze web access log files; introduces arrays and for loops.
12
tech-support chapter 5
An implementation of an Eliza-like dialog program used to provide "technical
support" to customers; introduces use of library classes in general and some
specific classes in particular; reading and writing of documentation.
balls chapter 5
A graphical animation of bouncing balls; demonstrates
interface/implementation separation and simple graphics.
diary chapter 6
The early stages of an implementation of a diary storing appointments; used to
discuss testing and debugging strategies.
calculator chapter 6
An implementation of a desk calculator. This example reinforces concepts
introduced earlier, and is used to discuss testing and debugging.
bricks chapter 6
A simple debugging exercise; models filling palettes with bricks for simple
computations.
world-of-zuul chapter 7, chapter 9
A text based, interactive adventure game. Highly extendable, makes a great
open-ended student project. Used here to discuss good class design, coupling,
and cohesion. Used again in chapter 9 as an example for use of inheritance.
dome chapter 8, chapter 9
A database of CDs and videos. This project is discussed and then extended in
great detail to introduce the foundations of inheritance and polymorphism.
foxes-and-rabbits chapter 10
A classic predator-prey simulation; reinforces inheritance concepts and adds
abstract classes and interfaces.
address-book chapter 11
An implementation of an address book with an optional GUI interface. Lookup
is flexible: entries can be searched by partial definition of name or phone
number. This project makes extensive use of exceptions.
cinema-booking-system chapter 12
A system to manage advance seat bookings in a cinema. This example is used in
a discussion of class discovery and application design. No code is provided as
the example represents developing an application from a blank sheet of paper.
13
taxi chapter 13
The taxi example is a combination of a booking system, management system,
and simulation. It is used as a case study to bring together many of the concepts
and techniques discussed throughout the book.
14
Preface to the instructor
This book is an introduction to object-oriented programming for beginners. The main
focus of the book is general object-oriented and programming concepts from a
software engineering perspective.
While the first chapters are written for students with no programming experience,
later chapters are suitable for more advanced or professional programmers as well. In
particular, programmers with experience in a non-object-oriented language who wish
to migrate their skills into object orientation should also be able to benefit from the
book.
We use two tools throughout the book to enable the concepts introduced to be put into
practice: These tools are the Java programming language and the Java development
environment BlueJ.
Java
Java was chosen because of a combination of two aspects: the language design and its
popularity. The Java programming language itself provides a very clean
implementation of most of the important object-oriented concepts, and serves well as
an introductory teaching language. Its popularity ensures an immense pool of support
resources.
In any subject area, having a variety of sources of information available is very
helpful, for teachers and students alike. For Java in particular, countless books,
tutorials, exercises, compilers, environments, and quizzes already exist, in many
different kinds and styles. Many of them are online and many are available free of
charge. The large amount and good quality of support material makes Java an
excellent choice as an introduction to object-oriented programming.
With so much Java material already available, is there still room for more to be said
about it? We think there is, and the second tool we use is one of the reasons ...
BlueJ
The second tool, BlueJ, deserves more comment. This book is unique in its
completely integrated use of the BlueJ environment.
BlueJ is a Java development environment that was designed at Monash University,
Australia, explicitly as an environment for teaching introductory object-oriented
programming. It is better suited to introductory teaching than other environments for a
variety of reasons:
• The user interface is much simpler. Beginning students can typically use the
BlueJ environment in a competent manner after 20 minutes of introduction.
From then on, instruction can concentrate on the important concepts at hand –
15
object orientation and Java – and no time needs to be wasted talking about
environments, file systems, class paths, DOS commands or DLL conflicts.
• The environment supports important teaching tools not available in other
environments. One of them is visualization of class structure. BlueJ
automatically displays a UML-like diagram representing the classes and
relationships in a project. Visualizing these important concepts is a great help
to both teachers and students. It is hard to grasp the concept of an object when
all you ever see on the screen is lines of code! The diagram notation is a
simple subset of UML, again tailored to the needs of beginning students. This
makes it easy to understand, but also allows migration to full UML in later
courses.
• One of the most important strengths of the BlueJ environment is the user’s
ability to create directly objects of any class, and then to interact with their
methods. This creates the opportunity for direct experimentation with objects,
for little overhead in the environment. Students can almost ‘feel’ what it
means to create an object, call a method, pass a parameter or receive a return
value. They can try out a method immediately after it has been written,
without the need to write test drivers. This facility is an invaluable aid in
understanding the underlying concepts and language details.
BlueJ is a full Java environment. It is not a cut down, simplified version of Java for
teaching. It runs on top of Sun Microsystems' Java Development Kit, and makes use
of the standard compiler and virtual machine. This ensures that it always conforms to
the official and most up-to-date Java specification.
The authors of this book have several years of teaching experience with the BlueJ
environment (and many more years without it before that). We both have experienced
how the use of BlueJ has increased the involvement, understanding and activity of
students in our courses. One of the authors is also a developer of the BlueJ system.
Real objects first
One of the reasons for choosing BlueJ was that it allows an approach where teachers
truly deal with the important concepts first. “Objects first” has been a battle cry for
many textbook authors and teachers for some time. Unfortunately, the Java language
does not make this noble goal very easy. Numerous hurdles of syntax and detail have
to be overcome before the first experience with a living object arises. The minimal
Java program to create and call an object typically includes:
• writing a class;
• writing a main method, including concepts such as static methods, parameters,
and arrays in the signature;
• a statement to create the object (‘new’);
• an assignment to a variable;
• the variable declaration, including variable type;
• a method call, using dot notation;
• possibly a parameter list.
16
As a result, textbooks typically either
• have to work their way through this forbidding list, and only reach objects
somewhere around chapter 4; or
• use a “Hello, world”-style program with a single static main method as the
first example, thus not creating any objects at all.
With BlueJ, this is not a problem. A student can create an object and call its methods
as the very first activity! Because users can create and interact with objects directly,
concepts such as classes, objects, methods and parameters can easily be discussed in a
concrete manner before looking at the first line of Java syntax. Instead of explaining
more about this here, we suggest that the curious reader dip into Chapter 1 – things
will quickly become clear then.
An iterative approach
Another important aspect of this book is that it follows an iterative style. In the
computing education community, a well-known educational design pattern exists that
states that important concepts should be taught early and often.1
It is very tempting for
textbook authors to try and say everything about a topic at the point where it is
introduced. For example, it is common, when introducing types, to give a full list of
built-in data types, or to discuss all available kinds of loops when introducing the
concept of a loop.
These two approaches conflict: we cannot concentrate on discussing important
concepts first, and at the same time provide complete coverage of all topics
encountered. Our experience with textbooks is that much of the detail is initially
distracting, and has the effect of drowning the important points, thus making them
harder to grasp.
In this book, we touch on all of the important topics several times, both within the
same chapter and across different chapters. Concepts are usually introduced at a level
of detail necessary for understanding and applying the task at hand. They are revisited
later in a different context, and understanding deepens as the reader continues through
the chapters. This approach also helps to deal with the frequent occurrence of mutual
dependencies between concepts.
Some teachers may not be familiar with an iterative approach. Looking at the first few
chapters, teachers used to a more sequential introduction will be surprised about the
number of concepts touched on this early. It may seem like a steep learning curve.
It is important to understand that this is not the end of the story. Students are not
expected to understand everything about these concepts immediately. Instead, these
fundamental concepts will be revisited again and again throughout the book, allowing
students to get a deeper and deeper understanding over time. Since their knowledge
level changes as they work their way forward, revisiting important topics later allows
them to gain a deeper understanding overall.
1
The ‘Early Bird’ pattern, in J. Bergin: ‘Fourteen Pedagogical Patterns for Teaching Computer
Science’, Proceedings of the Fifth European Conference on Pattern Languages of Programs
(EuroPLop 2000), Irsee, Germany, July 2000.
17
We have tried this approach with students many times. It seems that students have
fewer problems dealing with it than some long time teachers. And remember: a steep
learning curve is not a problem as long as you ensure that your students can climb it!
No complete language coverage
Related to our iterative approach is the decision not to try to provide complete
coverage of the Java language within the book.
The main focus of this book is to convey object-oriented programming principles in
general, not Java language details in particular. Students studying with this book may
be working as software professionals for the next 30 or 40 years of their life – it is a
fairly safe bet that the majority of their work will not be in Java. Every serious
textbook must of course attempt to prepare them for something more fundamental
than the language flavor of the day.
On the other hand, many Java details are important for actually doing the practical
work. In this book, we cover Java constructs in as much detail as is necessary to
illustrate the concepts at hand and implement the practical work. Some constructs
specific to Java have been deliberately left out of the discussion.
We are aware that some instructors will choose to cover some topics that we do not
discuss in detail. That is expected and necessary. However, instead of trying to cover
every possible topic ourselves (and thus blowing the size of this book out to 1500
pages), we deal with it using hooks. Hooks are pointers, often in the form of questions
that raise the topic and give references to an appendix or outside material. These
hooks ensure that a relevant topic is brought up at an appropriate time, and leaves it
up to the reader or the teacher to decide to what level of detail that topic should be
covered. Thus, hooks serve as a reminder of the existence of the topic and a
placeholder indicating a point in the sequence where discussion can be inserted.
Individual teachers can decide to use the book as it is, following our suggested
sequence, or to branch out into sidetracks suggested by the hooks in the text.
Each chapter also includes several questions suggesting discussion material related to
the topic, but not discussed in this book. We fully expect teachers to discuss some of
these questions in class, or students to research the answers as homework exercises.
Project-driven approach
The introduction of material in the book is project driven. The book discusses
numerous programming projects and provides many exercises. Instead of introducing
a new construct and then providing an exercise to apply this construct to solve a task,
we first provide a goal and a problem. Analyzing the problem at hand determines
what kinds of solutions we need. As a consequence, language constructs are
introduced as they are needed to solve the problems before us.
Almost all chapters provide at least two discussion examples. These are projects that
are discussed in detail to illustrate the important concepts of each chapter. Using two
very different examples supports the iterative approach: each concept is revisited in a
different context after it is introduced.
18
In designing this book, we have tried to use a large number and wide variety of
different example projects. This will hopefully serve to capture the reader's interest,
but it also helps to illustrate the variety of different contexts in which the concepts can
be applied. Finding good example projects is hard. We hope that our projects serve to
give teachers good starting points and many ideas for a wide variety of interesting
assignments.
The implementation for all our projects is written very carefully, so that many
peripheral issues may be studied by reading the projects’ source code. We are strong
believers in the benefit of learning by reading and imitating good examples. For this
to work, however, one must make sure that the examples students read are well
written and worth imitating. We have tried to do this.
All projects are designed as open-ended problems. While one or more versions of
each problem are discussed in detail in the book, the projects are designed so that
further extensions and improvements can be done as student projects. Complete
source code for all projects is included. A list of projects discussed in this book is
provided on page 11.
Concept sequence rather than language constructs
One other aspect that distinguishes this book from many others is that it is structured
along fundamental software development tasks and not necessarily according to the
particular Java language constructs. One indicator of this is the chapter headings. In
this book, you will not find many of the traditional chapters titles, such as ‘Primitive
data types’ or ‘Control structures’. Structuring by fundamental development tasks
allows us to give a much more general introduction that is not driven by intricacies of
the particular programming language utilized. We also believe that it is easier for
students to follow the motivation of the introduction, and that it makes it much more
interesting.
As a result of this approach, it is less straightforward to use the book as a reference
book. Introductory textbooks and reference books have different, partly competing,
goals. To a certain extent, a book can try to be both, but compromises have to be
made at certain points. Our book is clearly designed as a textbook, and wherever a
conflict occurred, the textbook style took precedence over its use as a reference book.
We have, however, provided support for use as a reference book by listing the Java
constructs introduced in each chapter in the table of contents and the chapter
introduction. We also provide a separate Java language construct index at the back of
the book.
Chapter sequence
Chapter 1 deals with the most fundamental concepts of object-orientation: objects,
classes and methods. It gives a solid, hands-on introduction to these concepts without
going into the details of Java syntax. It also gives a first look at some source code. We
do this by using an example of graphical shapes which can be interactively drawn,
and a second example of a simple laboratory class enrolment system.
19
Chapter 2 opens up class definitions and investigates how Java source code is written
to create behavior of objects. We discuss how to define fields and implement
methods. Here, we also introduce the first types of statements. The main example is
an implementation of a ticket machine. We also look back to the laboratory class
example from chapter 1 to investigate that a bit further.
Chapter 3 then enlarges the picture to discuss interaction of multiple objects. We see
how objects can collaborate by invoking each other’s methods to perform a common
task. We also discuss how one object can create other objects. A digital alarm clock
display is discussed that uses two number display objects to show hours and minutes.
As a second major example, we examine a simulation of an email system in which
messages can be sent between mail clients.
In Chapter 4, we continue by building more extensive structures of objects. Most
importantly, we start using collections of objects. We implement an electronic
notebook and an auction system to introduce collections. At the same time, we discuss
iterations over collection and have a first look at loops. The first collection being used
is an ArrayList. In the second half of the chapter we introduce arrays as a special
form of a collection, and the for loop as another form of a loop. We discuss an
implementation of a web log analyzer as an example for array use.
Chapter 5 deals with libraries and interfaces. We introduce the Java standard library
and discuss some important library classes. More importantly, we explain how to read
and understand the library documentation. The importance of writing documentation
in software development projects is discussed, and we end by practicing how to write
suitable documentation for our own classes. Random, Set and Map are examples of
classes that we encounter in this chapter. We implement an Eliza-like dialogue system
and a graphical simulation of a bouncing ball to apply these classes.
Chapter 6, titled Well-behaved objects, deals with a whole group of issues connected
to producing correct, understandable, and maintainable classes. It covers issues
ranging from writing clear, understandable code – including style and commenting –
to testing and debugging. Test strategies are introduced and a number of debugging
methods are discussed in detail. We use an example of a diary for appointment
scheduling and an implementation of an electronic calculator to discuss these topics.
In Chapter 7, we discuss more formally the issues of dividing a problem domain into
classes for implementation. We introduce issues of designing classes well, including
concepts such as responsibility-driven design, coupling, cohesion, and refactoring. An
interactive, text-based, adventure game (World of Zuul) is used for this discussion.
We go through several iterations of improving the internal class structure of the game
and extending its functionality, and end with a long list of proposals for extensions
that may be done as student projects.
Chapters 8 and 9 introduce inheritance and polymorphism with many of the related
detailed issues. We discuss a simple database of CDs and videos to illustrate the
concepts. Issues of code inheritance, subtyping, polymorphic method calls and
overriding are discussed in detail.
20
In Chapter 10 we implement a predator/prey simulation. This serves to discuss
additional abstraction mechanisms based on inheritance, namely interfaces and
abstract classes.
Chapter 11 then picks up the difficult issue of how to deal with errors. Several
possible problems and solutions are discussed, and Java’s exception handling
mechanism is discussed in detail. We extend and improve an address book application
to illustrate the concepts.
Chapter 12 steps back to discuss in more detail the next level of abstraction: how to
structure a vaguely described problem into classes and methods. In previous chapters
we have assumed that large parts of the application structure already exist, and we
have made improvements. Now it is time to discuss how we can get started from a
clean slate. This involves detailed discussion of what the classes should be that
implement our application, how they interact, and how responsibilities should be
distributed. We use class-responsibilities-collaborators (CRC) cards to approach this
problem, while designing a cinema booking system.
In Chapter 13, we try to bring everything together and integrate many topics from the
previous chapters of the book. It is a complete case study, starting with the application
design, through design of the class interfaces, down to discussing many important
functional and non-functional characteristics and implementation details. Topics
discussed in earlier chapters (such as reliability, data structures, class design, testing,
extendibility, etc.) are applied again in a new context.
Discussion group
The authors maintain an active email discussion group for the purpose of facilitating
exchange of ideas and mutual support for and by readers of this book and other BlueJ
users. Postings to this list are archived and publicly accessible. Using this list,
teachers can receive support and ideas from other teachers and the authors of this
book. The mail address for this list is bluej-discuss@bluej.org. Interested people
can join the list or browse the archives at
http://lists.bluej.org/mailman/listinfo/bluej-discuss
Additional material
This book includes all projects used as discussion examples and exercises on a CD.
The CD also includes the Java development environment (JDK) and BlueJ for various
operating systems.
There is a support web site for this book at
http://www.bluej.org/objects-first
On this web site, updates to the examples can be found, and additional material is
provided. For instance, the style guide used for all examples in this book is available
on the web site in electronic form, so that instructors can modify it to meet their own
requirements.
21
The web site also includes a password protected, teacher-only section that provides
additional material, such as solutions to exercises.
A set of slides to teach a course with this book is also provided.
22
Part I:
Foundations of object orientation
23
Chapter 1 Objects and classes
Main concepts discussed in this chapter:
• objects
• classes
• methods
• parameters
This chapter is the start of our journey into the world of object-oriented programming.
Here we introduce the most important concepts you will learn about: objects and
classes. At the end of the chapter, you should have an understanding of what objects
and classes are, what they are used for, and how to interact with them. This chapter
forms the basis of all other explorations in the book.
1.1 Objects and classes
[concept box: objects] If you write a computer program in an object-oriented
language, you are creating, in your computer, a model of some part of the world. The
parts that the model is built up from are the objects that appear in the problem
domain. These objects must be represented in the computer model being created.
Objects may be categorized and a class describes, in an abstract way, all objects of a
particular kind.
We can make these abstract notions clearer by looking at an example. Assume you
want to model a traffic simulation. One kind of entity you then have to deal with is
cars. What is a car in our context: is it a class or an object? A few questions may help
us to make a decision.
What color is a car? How fast can it go? Where is it right now?
[concept box: classes] You will notice that we cannot answer these questions until we
talk about one specific car. The reason is that the word “car” in this context refers to
the class car – we are talking about cars in general, not about one particular car.
If I say, “My old car that is parked at home in my garage,” we can answer the
questions above. That car is red, it doesn’t go very fast, and it is in my garage. Now I
am talking about an object – about one particular example of a car.
We usually refer to a particular object as an instance. We will use the term “instance”
quite regularly from now on. Instance is roughly synonymous with object – we refer
to objects as instances when we want to emphasize that they are of a particular class
(such as, “this object is an instance of class car”).
24
Before we continue this rather theoretical discussion, let us look at an example.
1.2 Creating objects
Start BlueJ and open the example named shapes.2
You should see a window similar to
that shown in Figure 1.
Figure 1: The shapes project in BlueJ
In this window, a diagram should become visible. Every one of the colored rectangles
in the diagram represents a class in our project. In this project we have classes named
Circle, Square, Triangle and Canvas.
Right-click on the Circle class and choose
new Circle()
from the popup menu. The system asks you for a “name of the instance” – click Ok,
the default name supplied is good enough for now. You will see a red rectangle
towards the bottom of the screen labeled “circle_1” (Figure 2).
2
We regularly expect you to undertake some activities and exercises while reading this book. At this
point we assume that you already know how to start BlueJ and open the example projects. If not, read
[Appendix A] first.
25
Figure 2: An object on the object bench
You have just created your first object! “Circle”, the rectangular icon in Figure 1,
represents the class Circle, “circle_1” is an object created from this class. The area at
the bottom of the screen where the object is shown is called the object bench.
Convention: We start names of classes with capital letters (such as Circle)
and names of objects with lowercase letters (such as circle_1). This helps to
distinguish what we are talking about.
Exercise:
1-1 Create another circle. Then create a square.
1.3 Calling methods
Right-click on one of the circle objects (not the class!) and you will see a popup menu
with several operations. Choose makeVisible from the menu – this will draw a
representation of this circle in a separate window (Figure 3).
Figure 3: A drawing of a circle
You will notice several other operations in the circle’s menu. Try invoking
moveRight and moveDown a few times to move the circle closer to the center of the
screen. You may also like to try makeInvisible and makeVisible to hide and show
the circle.
26
Exercise:
1-2 What happens if you call moveDown twice? Or three times? What
happens if you call makeInvisible twice?
[concept box: methods] The entries in the circle’s menu represent operations that you
can use to manipulate the circle. These are called methods in Java. Using common
terminology, we say that these methods are called or invoked. We will use this proper
terminology from now on. We might ask you to “invoke the moveRight method of
circle_1”.
1.4 Parameters
[concept box: parameters] Now invoke the moveHorizontal method. You will see a
dialog appear that prompts you for some input (Figure 4). Type in 50 and click Ok.
You will see the circle move 50 pixels to the right.3
Figure 4: A method call dialog
The moveHorizontal method that was just called is written in such a way that it
requires some more information to execute. In this case, the information required is
the distance – how far the circle should be moved. Thus, the moveHorizontal method
is more flexible than the moveRight or moveLeft methods. The latter always move
the circle a fixed distance, whereas moveHorizontal lets you specify how far you
want to move the circle.
Exercise:
1-3 Try invoking the moveVertical, slowMoveVertical and changeSize
methods before you read on. Find out how you can use moveHorizon-
tal to move the circle 70 pixels to the left.
The additional values that some methods require are called parameters. A method
indicates what kinds of parameters it requires. When calling, for example, the
moveHorizontal method as shown in Figure 4, the dialog displays the line
void moveHorizontal(int distance)
3
A pixel is a single dot on your screen. Your whole screen it made up of a grid of single pixels.
27
near the top. This is called the signature of the method. [concept box: signature] The
signature provides some information about the method in question. The part between
the parenthesis (int distance) is the information about the required parameter. For
each parameter, it defines a type and a name. The signature above states that the
method requires one parameter of type int named distance. The name gives a hint
about the meaning of the data expected.
1.5 Data types
A type specifies what kind of data can be passed to a parameter. [concept box: types]
The type “int” signifies whole numbers (also called “integer” numbers, therefore the
abbreviation “int”).
In the example above, the signature of the moveHorizontal method states that, before
the method can execute, we need to supply a whole number specifying the distance to
move. The data entry field shown in Figure 4 then lets you enter that number.
In the examples so far, the only data type we have seen is int. The parameters of the
move methods and the changeSize method are all of that type.
Closer inspection of the object’s popup menu shows that the method entries in the
menu include the parameter types. If a method has no parameter, the method name is
followed by an empty set of parentheses. If it has a parameter, the type of that
parameter is displayed. In the list of methods for a circle, you will see one method
with a different parameter type: the changeColor method has a parameter of type
String.
The String type indicates that a section of text (for example a word or a sentence) is
expected. Strings are always enclosed within double quotes. For example, to enter the
word red as a string, type
"red"
The method call dialog also includes a section of text called a comment above the
method signature. Comments are included to provide information to the (human)
reader and are described in [Chapter 2]. The comment of the changeColor method
describes what color names the system knows about.
Exercise:
1-4 Invoke the changeColor method on one of your circle objects and enter
the String “red”. This should change the color of the circle. Try other
colors.
1-5 This is a very simple example, and not many colors are supported. See
what happens when you specify a color that is not known.
1-6 Invoke the changeColor method, and write the color into the parameter
field without the quotes. What happens?
28
Pitfall: A common error for beginners is to forget the double quotes when
typing in a data value of type String. If you type green instead of “green”,
you will get an error message saying something like “Error: undefined
variable” (or something similar).
Java supports several other data types including, for example, decimal numbers and
characters. We will not discuss all of them right now, but rather come back to this
issue later. If you want to find out about them now, look at [Appendix B].
1.6 Multiple instances
Exercise:
1-7 Create several circle objects on the object bench. You can do so by
selecting new Circle() from the popup menu of the Circle class. Make
them visible, then move them around on the screen using the “move”
methods. Make one big and yellow, make another one small and green.
Try the other shapes too: create a few triangles and squares. Change
their positions, sizes and colors.
[concept box: multiple instances] Once you have a class, you can create as many
objects (or instances) of that class as you like. From the class Circle, you can create
many circles. From Square, you can create many squares.
Every one of those objects has its own position, color and size. You change an
attribute of an object (such as its size) by calling a method on that object. This will
affect this particular object, but not others.
You may also notice an additional detail about parameters. Have a look at the
changeSize method of the triangle. Its signature is
void changeSize(int newHeight, int newWidth)
Here is an example of a method with more than one parameter. This method has two,
and a comma separates them in the signature. Methods can, in fact, have any number
of parameters.
1.7 State
[concept box: state] The set of values of all attributes defining an object (such as x-
position, y-position, color, diameter and visibility status for a circle) is also referred to
as the object’s state. This is another example of common terminology that we will use
from now on.
In BlueJ, the state of an object can be inspected by selecting the Inspect function from
the object’s popup menu. When an object is inspected, a window similar to that
shown in Figure 5 is displayed. This window is called the object inspector.
Exercise:
29
1-8 Make sure you have several objects on the object bench and then
inspect each of them in turn. Try changing the state of an object (for
example by calling the moveLeft method) while the object inspector is
open. You should see the values in the object inspector change.
Some methods, when called, change the state of an object. For example, moveLeft
changes the xPosition attribute. Java refers to these object attributes as fields.
Figure 5: An object inspection dialog
1.8 What is in an object?
On inspecting different objects you will notice that objects of the same class all have
the same fields. That is, the number, type and names of the fields are the same, while
the actual value of a particular field in each object may be different. In contrast,
objects of a different class may have different fields. A circle, for example, has a field
“diameter”, while a triangle has fields for “width” and “height”.
The reason is that the number, types, and names of fields are defined in a class, not in
an object. So the class Circle defines that each circle object will have five fields,
named diameter, xPosition, yPosition, color and isVisible. It also defines the
types for these fields. That is, it specifies that the first three are of type int, while the
color is of type String and the isVisible flag is of type boolean. (Boolean is a type
that can represent two values: true and false. We will discuss it in more detail
later.)
When an object of class Circle is created, the object will automatically have these
fields. The values of these fields are stored in the object. That ensures that each circle
has a color, for instance, and each can have a different color (Figure 6).
30
Figure 6: A class and its objects with fields and values
The story is similar for methods. Methods are defined in the class of the object. As a
result, all objects of a given class have the same methods. However, the methods are
invoked on objects. This makes it clear which object to change when, for example, a
moveRight method is invoked.
Exercise:
1-9 Use the shapes from the shapes project to create an image of a house
and a sun, similar to that shown in Figure 7. While you are doing this,
write down what you have to do to achieve this. Could it be done in
different ways?
31
Figure 7: An image created from a set of shape objects
1.9 Object interaction
For the next section, we will work with a different example project. Close the shapes
project if you still have it open, and open the project called picture.
Exercises:
1-10 Open the picture project. Create an instance of class Picture and
invoke its draw method. Also, try out the setBlackAndWhite and
setColor methods.
1-11 How do you think the Picture class draws the picture?
Four of the classes in the project are identical to the classes in the shapes project. But
we now have an additional class: Picture. This class is programmed to do exactly
what we have done by hand in exercise 1-9.
In reality, if we want a sequence of tasks done in Java, we would not normally do it
by hand as in exercise 1-9. Instead, we create a class that does it for us. This is the
Picture class.
The Picture class is written in a way that, when you create an instance, that instance
creates two square objects (one for the wall, one for the window), a triangle and a
circle, moves them around, changes their color and size, until it looks like the picture
we see in Figure 7.
[concept box: method-calling] The important point here is: objects can create other
objects and they can call each other’s methods. In a normal Java program you may
well have hundreds or thousands of objects. The user of a program just starts the
program (which typically creates a first object), and all other objects are created –
directly or indirectly – by that object.
32
The big question now is: how do you write the class for such an object?
1.10 Source code
[concept box: source code] Each class has some source code associated with it. The
source code is text that defines the details of the class. In BlueJ, the source code of a
class can be viewed by selecting the Open Editor function from the class’s popup
menu, or by double-clicking the class icon.
Exercise:
1-12 Look at the popup menu of class Picture again. You will see an option
labeled Open Editor. Select it. This will open a text editor displaying
the source code of the class.
The source code is text written in the Java
programming language. It defines what fields
and methods a class has, and precisely what
happens when a method is invoked. In the next
chapter we will discuss exactly what the source
code of a class contains and how it is
structured.
A large part of learning the art of programming
is learning how to write these class definitions.
To do this, we will learn to use the Java
language (although there are many other
programming languages that could be used to
write code).
When you make a change to the source code
and close the editor,4
the icon for that class
appears striped in the diagram. The stripes
indicate that the source has been changed. The
class now needs to be compiled by clicking the
Compile button. (You may like to read the
“About compilation” sidebar for more
information about what is happening when you
compile a class.) Once a class has been compiled, objects can be created again and
you can try out your change.
Exercises:
1-13 In the source code of class Picture, find the part that actually draws
the picture. Change it so that the sun will be blue rather than yellow.
1-14 Add a second sun to the picture. To do this, pay attention to the field
definitions close to the top of the class. You will find this code:
4
In BlueJ, there is no need to save the text in the editor explicitly before closing. If you close the
editor, the source code will automatically be saved.
About compilation
When people write computer programs, they
typically use a “higher level” programming
language, such as Java. A problem with that is
that a computer cannot execute Java source
code directly. Java was designed to be
reasonably easy to read for humans, not for
computers. Computers, internally, work with a
binary representation of a machine code, which
looks quite different from Java. The problem for
us is: it looks so complex that we do not want
to write it directly. We prefer to write Java.
What can we do about this?
The solution is a program called the compiler.
The compiler translates the Java code into
machine code. We can write Java, run the
compiler – which generates the machine code
– and the computer can then read the machine
code. As a result, every time we change the
source code we must first run the compiler
before we can use the class again to create an
object. Otherwise the machine code version
that the computer needs does not exist.
33
private Square wall;
private Square window;
private Triangle roof;
private Circle sun;
You need to add a line here for the second sun, For example:
private Circle sun2;
Then write the appropriate code for creating the second sun.
1-15 Challenge exercise: (This means that this exercise might not be solved
quickly. We do not expect everyone to be able to solve this at the
moment. If you do – great. If you don’t, then don’t worry. Things will
become clearer as you read on. Come back to this exercise later.) Add a
sunset to the single-sun version of Picture. That is: make the sun go
down slowly. Remember: The circle has a method slowMoveVertical
that you can use to do this.
1-16 Challenge exercise: If you added your sunset to the end of the draw
method (so that the sun goes down automatically when the picture is
drawn), change this now. We now want the sunset in a separate method,
so that we can call draw and see the picture with the sun up, and then
call sunset (a separate method!) to make the sun go down.
1.11 Another example
In this chapter, we have already discussed a large number of new concepts. To help in
understanding these concepts, we will now revisit them in a different context. For
this, we use a different example. Close the picture project if you still have it open, and
open the lab-classes project.
This project is a simplified part of a student database designed to keep track of
students in laboratory classes and to print class lists.
Exercise:
1-17 Create an object of class Student. You will notice that this time you
are not only prompted for a name of the instance, but also for some
other parameters. Fill them in before clicking Ok. (Remember that
parameters of type String must be written in double-quotes.)
1.12 Return values
As before, you can create multiple objects. And again, as before, the objects have
methods which you can call from their popup menu.
Exercise:
34
1-18 Create some student objects. Call the getName method on each object.
Explain what is happening.
When calling the getName method of the Student class, we notice something new:
methods may return a result value. [concept box: results] In fact, the signature of each
method tells us whether or not it returns a result, and what the type of the result is.
The signature of getName (as shown in the object’s popup menu) is defined as:
String getName()
The word String before the method name specifies the return type. In this case it
states that calling this method will return a result of type String. The signature of
changeName states:
void changeName(String)
The word void indicates that this method does not return any result.
Methods with return values enable us to get information from an object via a method
call. This means that we can use methods either to change an object’s state or to find
out about its state.
1.13 Objects as parameters
Exercises:
1-19 Create an object of class LabClass. As the signature indicates, you
need to specify the maximum number of students in that class (an
integer).
1-20 Call the numberOfStudents method of that class. What does it do?
1-21 Look at the signature of the enrolStudent method. You will notice
that the type of the expected parameter is Student. Make sure you have
two or three students and a LabClass object on the object bench, then
call the enrolStudent method of the LabClass object. With the input
cursor in the dialog entry field, click on one of the student objects – this
enters the name of the student object into the parameter field of the
enrolStudent method (Figure 8). Click Ok, and you have added the
student to the LabClass. Add one or more other students as well.
1-22 Call the printList method of the LabClass object. You will see a list
of all the students in that class printed to the BlueJ terminal window
(Figure 9).
35
Figure 8: Adding a student to a tutorial
Figure 9: Output of the LabClass project’s class listing
As the exercises show, objects can be passed as parameters to methods of other
objects. In the case where a method expects an object as a parameter, the expected
object’s class name is specified as the parameter type in the method signature.
Explore this project a bit more. Try to identify the concepts discussed in the shapes
example in this context.
Exercises:
1-23 Create three students with the following details:
Snow White, student ID: 100234, credits: 24
Lisa Simpson, student ID: 122044, credits: 56
Charlie Brown, student ID: 12003P, credits: 6
Then enter all three into a lab and print a list to the screen.
1-24 Use the inspector on a LabClass object to discover what fields it has.
1-25 Set the instructor, room, and time for a lab and print the list to the
terminal window to check that these new details appear.
36
1.14 Summary
In this chapter, we have explored the basics of classes and objects. We have discussed
the fact that objects are specified by classes. Classes represent the general concept of
a thing, while objects represent concrete instances of a class. We can have many
objects of any class.
Objects have methods which we use to communicate with them. We can use a method
to make a change to the object or to get information from the object. Methods can
have parameters, and parameters have types. Methods have return types, which
specify what type of data they return. If the return type is void, they do not return
anything.
Objects store data in fields (which also have types). All the data values of an object
together are referred to as the object’s state.
Objects are created from class definitions that have been written in a particular
programming language. Much of programming in Java is about learning to write class
definitions. A large Java program will have many classes, each with many methods
which call each other in many different ways.
To learn to develop Java programs, we need to learn how to write class definitions,
including fields and methods, and how to put these classes together well. The rest of
this book deals with these issues.
Terms introduced in this chapter
object, class, instance, method, signature, parameter, type, state, source
code, return value, compiler.
Concept summary
• Java objects model objects from a problem domain. [objects]
• Objects are created from classes. The class describes the kind of object; the
objects represent individual instantiations of the class. [classes]
• We can communicate with objects by invoking methods on them. Objects
usually do something if we invoke a method. [methods]
• Methods can have parameters to provide additional information for a task.
[parameters]
• The header of a method is called its signature. It provides information needed
to invoke that method. [signatures]
• Parameters have types. The type defines what kinds of values a parameter can
take. [types]
• Many similar objects can be created from a single class. [multiple instances]
• Objects have state. The state is represented by storing values in fields. [state]
• Objects can communicate by calling each other’s methods. [method-calling]
• The source code of a class determines the structure and the behavior (the fields
and methods) of each of the objects in that class. [source code]
• Methods may return information about an object via a return value. [results]
Exercise:
37
1-26 In this chapter, we have mentioned the data types int and String.
Java has more predefined data types. Find out what they are and what
they are used for. To do this, you can check [Appendix B], look it up in
another Java book or in an online Java language manual. One such
manual is at
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
38
Chapter 2 Understanding class definitions
Main concepts discussed in this chapter:
• fields
• constructors
• methods (accessor, mutator)
• parameters
• assignment and conditional statement
Java constructs discussed in this chapter:
field, constructor, comment, parameter, assignment (=), block, return statement, void,
compound assignment operators (+=, -=), if
In this chapter, we take our first proper look at the source code of a class. We will
discuss the basic elements of class definitions: fields, constructors, and methods.
Methods contain statements and initially we look at methods containing only simple
arithmetic and printing statements. Later we introduce conditional statements that
allow choices between different actions to be made within methods.
We will start by examining a new project in a fair amount of detail. This project
represents a naïve implementation of an automated ticket machine. As we start by
introducing the most basic features of classes, we will quickly find that this
implementation is deficient in a number of ways. So we will then proceed to describe
a more sophisticated version of the ticket machine that represents a significant
improvement. Finally, in order to reinforce the concepts introduced in this chapter, we
take a look at the internals of the lab-classes example encountered in [Chapter 1].
2.1 Ticket machines
Train stations often provide ticket machines that print a ticket when a customer inserts
the correct money for their fare. In this chapter, we will define a class that models
something like these ticket machines. As we will be looking inside our first Java
example classes, we will keep our simulation fairly simple to start with. That will give
us the opportunity to ask some questions about how these models differ from the real
world versions, and how we might change our classes to make the objects they create
more like the real thing.
Our ticket machines work by customers ‘inserting’ money into them, and then
requesting a ticket to be printed. A machine keeps a running total of the amount of
money it has collected throughout its operation. In real life, it is often the case that a
ticket machine offers a selection of different types of ticket from which customers
choose the one they want. Our simplified machines only print tickets of a single price.
39
It turns out to be significantly more complicated to program a class to be able to issue
tickets of different values than it does to have a single price. On the other hand, with
object-oriented programming it is very easy to create multiple instances of the class,
each with its own price setting, to fulfill a need for different types of ticket.
2.1.1 Exploring the behavior of a naïve ticket machine
Open the naive-ticket-machine project in BlueJ. This project contains only one class –
TicketMachine – that you will be able to explore in a similar way to the examples we
discussed in [Chapter 1]. When you create a TicketMachine instance, you will be
asked to supply a number that corresponds to the price of tickets that will be issued by
that particular machine. The price is taken to be a number of cents, so a positive
whole number such as 500 would be appropriate as a value to work with.
Exercises:
2-1 Create a TicketMachine object on the object bench and take a look at
its methods. You should see the following: getBalance, getPrice,
insertMoney, and printTicket. Try out the getPrice method. You
should see a return value containing the price of the tickets that was set
when this object was created. Use the insertMoney method to simulate
inserting an amount of money into the machine and then use
getBalance to check that the machine has a record of the amount
inserted. You can insert several separate amounts of money into the
machine, just like you might insert multiple coins or notes into a real
machine. Try inserting the exact amount required for a ticket. As this is
a simple machine, a ticket will not be issued automatically, so once you
have inserted enough money, call the printTicket method. A
facsimile ticket should be printed in the BlueJ terminal window.
2-2 What value is returned if you check the machine’s balance after it has
printed a ticket?
2-3 Experiment with inserting different amounts of money before printing
tickets. Do you notice anything strange about the machine’s behavior?
What happens if you insert too much money into the machine – do you
receive any refund? What happens if you do not insert enough and then
try to print a ticket?
2-4 Try to obtain a good understanding of a ticket machine’s behavior by
interacting with it on the object bench before we start looking at how
the TicketMachine class is implemented in the next section.
2-5 Create another ticket machine for tickets of a different price. Buy a
ticket from that machine. Does the printed ticket look different?
2.2 Examining a class definition
Examination of the behavior of TicketMachine objects within BlueJ reveals that they
only really behave in the way we might expect them to if we insert exactly the correct
40
amount of money to match the price of a ticket. As we explore the internal details of
the class in this section, we will begin to see why this is so.
Take a look at the source code of the TicketMachine class by double-clicking its
icon in the class diagram. It should look something like Figure 10.
Figure 10: The BlueJ editor window
The complete text of the class is shown in Figure 11. By looking at the text of the
class definition piece by piece we can flesh out some of the object-oriented concepts
that we talked about in [Chapter 1].
/**
* TicketMachine models a naive ticket machine that issues
* flat-fare tickets.
* The price of a ticket is specified via the constructor.
* It is a naive machine in the sense that it trusts its users
* to insert enough money before trying to print a ticket.
* It also assumes that users enter sensible amounts.
*
* @author David J. Barnes and Michael Kölling
* @version 2002.02.06
*/
public class TicketMachine
{
// The price of a ticket from this machine.
private int price;
// The amount of money entered by a customer so far.
private int balance;
// The total amount of money collected by this machine.
41
private int total;
/**
* Create a machine that issues tickets of the given price.
* Note that the price must be greater than zero, and there
* are no checks to ensure this.
*/
public TicketMachine(int ticketCost)
{
price = ticketCost;
balance = 0;
total = 0;
}
/**
* Return the price of a ticket.
*/
public int getPrice()
{
return price;
}
/**
* Return the amount of money already inserted for the
* next ticket.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money in cents from a customer.
*/
public void insertMoney(int amount)
{
balance += amount;
}
/**
* Print a ticket.
* Update the total collected and
* reduce the balance to zero.
*/
public void printTicket()
{
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("##################");
System.out.println();
// Update the total collected with the balance.
total += balance;
// Clear the balance.
balance = 0;
}
}
Figure 11: The TicketMachine class
42
2.3 Fields, constructors, and methods
The source of most classes can be broken down into two main parts: a small outer
wrapping that simply names the class, and a much larger inner part that does all the
work. In this case, the outer wrapping appears as follows:
public class TicketMachine
{
Inner part of the class omitted.
}
The outer wrappings of different classes all look pretty much the same; their main
purpose is to provide a name for the class.
Exercise:
2-6 Write out what you think the outer layers of the Student and LabClass
classes might look like – do not worry about the inner part.
The inner part of the class is where we define the fields, constructors, and methods
that give the objects of that class their own particular characteristics and behavior. We
can summarize the essential features of those three components of a class as follows:
• The fields store data for each object to use.
• The constructors allow each object to be set up properly when it is first created.
• The methods implement the behavior of the objects.
In Java, there are very few rules about the order in which you choose to define the
fields, constructors, and methods within a class. In the TicketMachine class, we have
chosen to list the fields first, the constructors second, and finally the methods (Figure
12). This is the order that we will follow in all of our examples. Other authors choose
to adopt different styles, and this is mostly a question of preference. Our style is not
necessarily better than all others. However, it is important to choose one style and
then to use it consistently because then your classes will be easier to read and
understand.
public class ClassName
{
Fields
Constructors
Methods
}
Figure 12: Our ordering of fields, constructors and methods
Exercises:
2-7 From your earlier experimentation with the ticket machine objects
within BlueJ, you can probably remember the names of some of the
methods – printTicket, for instance. Look at the class definition in
43
Figure 11 and use this knowledge, along with the additional information
about ordering we have given you, to try to make a list of the names of
the fields, constructors and methods in the TicketMachine class. Hint:
There is only one constructor in the class.
2-8 Do you notice any features of the constructor that make it significantly
different from the other methods of the class?
2.3.2 Fields
[concept box: fields] The TicketMachine class has three fields: price, balance, and
total. Fields are also known as instance variables. We have defined these right at the
start of the class definition (Figure 13). All of the fields are associated with monetary
items that a ticket machine object has to deal with:
• The price field stores the fixed price of a ticket.
• The balance field stores the amount of money inserted into the machine by a user
prior to asking for a ticket to be printed.
• The total field stores a record of the total amount of money inserted into the
machine by all users since the machine object was constructed.
public class TicketMachine
{
private int price;
private int balance;
private int total;
Constructor and methods omitted.
}
Figure 13: The fields of the TicketMachine class
Fields are small amounts of space inside an object which can be used to store values.
Every object, once created, will have some space for every field declared in its class.
Figure 14 shows a diagrammatic representation of a ticket machine object with its
three fields. The fields have not yet been assigned any values – once they have, we
can write each value into the box representing the field. The notation is similar to that
used in BlueJ to show objects on the object bench, except that we show a bit more
detail here. In BlueJ, for space reasons, the fields are not displayed on the object icon.
We can, however, see them by opening an inspector window.
44
Figure 14: An object of class TicketMachine
Each field has its own declaration in the source code. On the line above each, in the
full class definition, we have added a single line of text – a comment – for the benefit
of human readers of the class definition:
// The price of a ticket from this machine.
private int price;
[concept box: comments] A single-line comment is introduced by the two characters,
‘//’, which are written with no spaces between them. More detailed comments, often
spanning several lines, are usually written in the form of multi-line comment. These
start with the character pair, ‘/*’ and end with the pair ‘*/’. There is a good example
preceding the header of the class in Figure 11.
The definitions of the three fields are quite similar.
• All definitions indicate that they are private fields of the object – we will have
more to say about what this means in [Chapter 5], but for the time being we will
simply say that we always define fields to be private.
• All three fields are of type int. This indicates that each can store a single whole
number value, which is reasonable given that we wish them to store numbers that
represent amounts of money in cents.
Because fields can store values which can vary over time, they are also known as
variables. The value stored in a field can be changed if we wish to. For instance, as
more money is inserted into a ticket machine we will want to change the value stored
in the balance field. In the following sections, we will also meet other kinds of
variables in addition to fields.
The price, balance, and total fields are all the data items that a ticket machine
object needs to fulfill its role of receiving money from a customer, printing tickets,
and keeping a running total of all the money that has been put into it. In the following
sections, we will see how the constructor and methods use those fields to implement
the behavior of naïve ticket machines.
2.3.3 Constructors
[concept box: constructors] The constructors of a class have a special role to fulfill –
it is their responsibility to put each object of that class into a fit state to be used once it
has been created. This is also called initialization. The constructor initializes the
45
object to a reasonable state. Figure 15 shows the constructor of the TicketMachine
class.
One of the distinguishing features of constructors is that they have the same name as
the class in which they are defined – TicketMachine in this case.
public class TicketMachine
{
Fields omitted.
/**
* Create a machine that issues tickets of the given price.
* Note that the price must be greater than zero, and there
* are no checks to ensure this.
*/
public TicketMachine(int ticketCost)
{
price = ticketCost;
balance = 0;
total = 0;
}
Methods omitted.
}
Figure 15: The constructor of the TicketMachine class
The fields of the object are initialized in the constructor. Some fields, such as
balance and total can be set to sensible initial values by assigning a constant
number, zero in this case. With others, such as the ticket price, it is not that simple
since we do not know the price that tickets from a particular machine will have until
that machine is constructed – recall that we might wish to create multiple machine
objects to sell tickets with different prices, so no one initial price will always be right.
You will recall from experimenting with creating TicketMachine objects within
BlueJ that you had to supply the cost of the tickets whenever you created a new ticket
machine. An important point to note here is that the price of a ticket is initially
determined outside of the ticket machine, and then has to be passed into a ticket
machine object. Within BlueJ, you decide the value and enter it into a dialogue box.
One task of the constructor is to receive that value and store it into the price field of
the newly created ticket machine so that the machine can remember what that value
was without you having to keep reminding it. We can see from this that one of the
most important roles of a field is to remember information, so that it is available to an
object throughout that object’s lifetime.
Figure 16 shows a ticket machine object after the constructor has executed. Values
have now been assigned to the fields. From this diagram, we can tell that the ticket
machine was created by passing in 500 as the value for the ticket cost.
In the next section, we discuss how values are received by an object from outside.
46
Figure 16: A TicketMachine object after initialization (created for 500 cent tickets)
Note: In Java, all fields are automatically initialized to a default value if they
are not explicitly initialized. For integer fields, this default value is 0. So,
strictly speaking, we could have done without setting balance and total to 0,
relying on the default value to give us the same result. However, we prefer to
write the explicit assignments anyway. There is no disadvantage to it, and it
serves well to document what is actually happening. We do not rely on a
reader of the class knowing what the default value is, and we document that
we really want this value to be zero, and have not just forgotten to initialize it.
2.4 Passing data via parameters
The way in which both constructors and methods receive values is via their
parameters. You may recall that we briefly encountered parameters in [Chapter 1].
Parameters are defined in the header of the constructor or method:
public TicketMachine(int ticketCost)
This constructor has a single parameter, ticketCost, which is of type int – the same
type as the price field it will be used to set. Figure 17 illustrates how values are
passed via parameters. In this case, a BlueJ user enters a value into the dialogue box
when creating a new ticket machine (shown on the left), and that value is then copied
into the ticketCost parameter of the new machine’s constructor. This is illustrated
with the arrow labeled (A). The additional box in the ticket machine object in Figure
17, labeled “TicketMachine (constructor)” is additional space for the object that is
created only when the constructor executes. We will call it the constructor space of
the object (or method space when we talk about methods instead of constructors,
since the situation there is the same). The constructor space is used to provide space
to store the values for the constructor’s parameters (and other variables that we will
come across later).
47
Figure 17: Parameter passing (A) and assignment (B)
We distinguish between parameter names inside a constructor or method, and
parameter values outside by referring to the names as formal parameters and the
values as actual parameters. So ticketCost is a formal parameter, and a user-
supplied value, such as 500, is an actual parameter. Because they are able to store
values, formal parameters are another sort of variable. In our diagrams, all variables
are represented by white boxes.
[concept box: scope] A formal parameter is only available to an object within the
body of a constructor or method that declares it. We say that the scope of a parameter
is restricted to the body of the constructor or method in which it is declared. In
contrast, the scope of a field is the whole of the class definition – it can be accessed
from anywhere in the same class.
[concept box: lifetime] A concept related to variable scope is variable lifetime. The
lifetime of a parameter is limited to a single call of a constructor or method. Once that
call has completed its task, the formal parameters disappear and the values they held
are lost. In other words, when the constructor has finished executing, the whole
constructor space (see Figure 17) is removed, along with the parameter variables held
within it.
In contrast, the lifetime of a field is the same as the lifetime of the object to which it
belongs. It follows that if we want to remember the cost of tickets held in the ticket-
Cost parameter, we must store the value somewhere more persistent – that is, in the
price field.
2.5 Assignment
In the previous section, we noted the need to store the short-lived value of a parameter
into somewhere more permanent – a field. In order to do this, the body of the
constructor contains the following assignment statement:
price = ticketCost;
Assignment statements are recognized by the presence of an assignment operator,
such as ‘=’ in the example above. Assignment statements work by taking the value of
48
what appears on the right-hand side of the operator and copying that value into a
variable on the left-hand side. This is illustrated in Figure 17 by the arrow labeled (B).
[concept box: assignment] The right-hand side is called an expression: expressions are
things that compute values. In this case, the expression just consists of a single
variable but we will see some examples of more complicated expressions containing
arithmetic operations later in this chapter. One rule about assignment statements is
that the type of the expression must match the type of the variable to which it is
assigned. So far we have met three different types: int, String, and (very briefly)
boolean. This rule means that we are not allowed to store an integer-type expression
into a string-type variable, for instance. This same rule also applies between formal
parameters and actual parameters; the type of an actual-parameter expression must
match the type of the formal-parameter variable. For now, we can say that the types of
both must be the same, although we will see in later chapters that this is not the whole
truth.
2.6 Accessor methods
The TicketMachine class has four methods: getPrice, getBalance, insertMoney,
and printTicket. We will start our look at the source code of methods by
considering getPrice (Figure 18).
public class TicketMachine
{
Fields omitted.
Constructor omitted.
/**
* Return the price of a ticket.
*/
public int getPrice()
{
return price;
}
Remaining methods omitted.
}
Figure 18: The getPrice method
[concept box: methods] Methods have two parts: a header and a body. Here is the
method header for getPrice:
/**
* Return the price of a ticket.
*/
public int getPrice()
The first three lines are a comment describing what the method does. The fourth line
is also known as the method signature. It is important to distinguish between method
signatures and field declarations, because they can look quite similar. We can tell that
getPrice is a method and not a field because it is followed by a pair of parentheses:
'(' and ')'. Note, too, that there is no semicolon at the end of the signature.
49
The method body is the remainder of the method after the header. It is always
enclosed by a matching pair of curly brackets: '{' and '}'. Method bodies contain
the declarations and statements that define what happens inside an object when that
method is called. In our example above the method body contains a single statement,
but we will see examples very soon where the method body consists of many lines of
both declarations and statements.
Any set of declarations and statements between a pair of matching curly brackets is
known as a block. So the body of the TicketMachine class and the bodies of all the
methods within the class are blocks.
There are at least two significant differences between the signatures of the
TicketMachine constructor and the getPrice method:
public TicketMachine(int ticketCost)
public int getPrice()
• The method has a return type of int but the constructor has no return type. A
return type is written just before the method name.
• The constructor has a single formal parameter, ticketCost, but the method has
none – just a pair of empty parentheses.
It is an absolute rule in Java that a constructor may not have a return type. On the
other hand, both constructors and methods may have any number of formal
parameters, including none.
Within the body of getPrice there is a single statement:
return price;
This is a return statement. It is responsible for returning an integer value to match the
int return type in the method’s signature. Where a method contains a return
statement, it is always the final statement of that method, because no further
statements in the method will be executed once the return statement is executed.
The int return type of getPrice is a form of promise that the body of the method
will do something that ultimately results in an integer value being calculated and
returned as the method’s result. You might like to think of a method call as being a
form of question to an object, and the return value from the method being the object’s
answer to that question. In this case, when the getPrice method is called on a ticket
machine, the question is, “What do tickets cost?” A ticket machine does not need to
perform any calculations to be able to answer that, because it keeps the answer in its
price field. So the method answers by just returning the value of that variable. As we
gradually develop more complex classes, we will inevitably encounter more complex
questions that require more work to supply their answers.
[concept box: accessor methods] We often describe methods such as the two get
methods of TicketMachine (getPrice and getBalance) as accessor methods (or
just accessors). This is because they return information to the caller about the state of
an object – they provide access to that state. An accessor usually contains a return
50
statement in order to pass back that information as a particular value, but this is not
exclusively the case. A method that prints information about an object’s state may
also be classified as an accessor.
Exercises:
2-9 Compare the getBalance method with the getPrice method. What are
the differences between them?
2-10 If a call to getPrice can be characterized as, “What do tickets cost?”
how would you characterize a call to getBalance?
2-11 If the name of getBalance is changed to getAmount, does the return
statement in the body of the method need to be changed, too? Try it out
within BlueJ.
2-12 Define an accessor method, getTotal, that returns the value of the
total field.
2-13 Try removing the return statement from the body of getPrice. What
error message do you see now when you try compiling the class?
2-14 Compare the method signatures of getPrice and printTicket in
Figure 11. Apart from their names, what is the main difference between
them?
2-15 Do the insertMoney and printTicket methods have return
statements? Why do you think this might be? Do you notice anything
about their headers that might suggest why they do not require return
statements?
2.7 Mutator methods
The get methods of a ticket machine perform similar tasks – returning the value of
one of their object’s fields. The remaining methods – insertMoney and printTicket
– have a much more significant role; primarily because they change the value of one
or more fields of a ticket machine object each time they are called. We call methods
that change the state of their object, mutator methods (or just mutators.) [concept box:
mutator methods]
In the same way as we think of accessors as requests for information (questions), we
can think of mutators as requests for an object to change its state.
One distinguishing effect of a mutator is that an object will often exhibit slightly
different behavior before and after it is called. We can illustrate this with the
following exercise.
Exercise:
2-16 Create a ticket machine with a ticket price of your choosing. Before
doing anything else, call the getBalance method on it. Now call the
Exploring the Variety of Random
Documents with Different Content
It was Harry Tynan—a tall, handsome lad with dark hair inclined
to curl, and big brown eyes; the type of boy who from childhood is
petted and spoilt by mothers and aunts. Unless such an one
possesses an exceptionally strong character the result is fatal, and
Tynan showed a weak mouth and chin.
“The Padre’s” owner caught the whisper.
“More fool you, you young idiot!” Markham genially observed, as
the silly youngster turned away with a muttered curse.
Miss Woodburn’s congratulations were even more welcome than
the praises of his comrades.
“I’m proud of my future brother,” she said. “You rode just
splendidly. Oh, it was exciting! I gave up all hope at the last water-
jump.... And then when you began to overhaul him down the incline!
Didn’t the shouting affect your nerves?”
Ted shook his head. “I don’t remember hearing anything. For all I
knew there might not have been a single person within miles except
me and Spencer—I mean Spencer and I—Spencer and myself, I
should say.”
“I could hardly hold myself in,” went on Ethel. “I was dancing up
and down—screaming, I’m afraid.”
“You were indeed, madame,” interposed Jim. “You were making a
most discreditable exhibition.”
“Ted,” exclaimed the girl, “will you marry me? I’m tired of your
brother.”
“That I will!” replied Ted. “To-morrow if you like. I never could
imagine what you could see in that chap, you know.”
“Very well, I’ll abandon him to his fate. He was actually cheering
on that Guide fellow during the last hundred yards.”
“The brute!”
“Isn’t he?”
“Who—the Guide fellow?”
With this embarrassing query Lieutenant Spencer joined the
party. Ethel blushed crimson, and for once in her life was at a loss
for a remark. Jim chuckled away to himself at his sweetheart’s
discomfiture in most brutal fashion.
“That’s right, Spencer,” said he. “Come and back me up, I’m in a
minority here.”
Miss Woodburn recovered from her confusion. She had already
been introduced by Jim to “that Guide fellow”.
“I really beg your pardon, Lieutenant Spencer. We were indulging
in a little inter-regimental chaff and abuse. Captain Russell had
dared to applaud you rather than his brother at the final burst. And
you don’t understand how fond we all are of ‘The Padre’. He’s the
regimental horse.”
“Please don’t apologize,” Miss Woodburn. “I quite understand and
sympathize with you. Indeed, I’m glad you’re scorching him, for he
needs it. And so he was cheering me in preference to your favourite?
He must have most execrable taste.”
“Thank you, Spencer!” Jim hurriedly and joyfully broke in.
“Thanks!... Be grateful, Ethel. Don’t you see how very
complimentary to you that remark is?”
For a few moments Miss Woodburn struggled with her
amusement, but laughter mastered her, and she could not speak
before Spencer had partially recovered his senses and recognized
what a left-handed compliment he had paid her. The Guides
lieutenant was far more confused and nervous now than at any time
during the steeple-chase.
With crimson face he offered reparation.
“It’s my turn to apologize now, Miss Woodburn. I think you’ll
forgive me, though. It’s my misfortune that I’m not very intelligent.”
“I couldn’t dream of doing so, Lieutenant Spencer,” Ethel
asserted, still laughing. “You paid me out nicely, and I’m sure you
did it wilfully; it was far too smart to be unintentional.”
“’Pon my honour, I didn’t. I’m not half sharp enough to say
anything of that kind except by accident. One can’t be perfect, you
know, and we must take into account that Russell did show poor
taste in applauding the inferior horse and rider—especially going
against your opinion, though we must acknowledge his perfect taste
in at least one respect.”
“I must forgive you after that, Mr. Spencer, though it was rather
crude,” said the girl, shaking her head.
“And I say, Spencer,” Jim interposed, “don’t talk about ‘inferior
rider’. We all know, and Ted knows, that you are a far better
horseman than he.”
“Of course I do,” the ensign heartily agreed.
“Too much praise isn’t good for a youngster,” the elder brother
sagaciously opined.
Spencer placed a hand on Ted’s shoulder.
“All the same, young ’un, you won the Aurungpore Cup, and you
deserved to win.”
The party of four came to a halt opposite Colonel Woodburn’s
bungalow.
“What time shall we start back for Murdan to-morrow?” asked
the lieutenant.
“We must leave early,” Jim replied. “Will eight o’clock suit?”
“Very good,” Spencer assented; “the young ’un and I will leave
you here.”
“But you must not think of leaving us yet, Mr. Spencer. Won’t you
come in? My father would be delighted to know you.”
“Couldn’t dream of it, Miss Woodburn, delighted though I should
be to make the colonel’s acquaintance. It will be some time before
Russell gets leave again, and your last evening shall be sacred.
Good-bye, Miss Woodburn! I’m very glad to have met you. And may
I congratulate you both? I’ve known Russell well for some years, and
I can congratulate you, and—forgive me for saying it—I’ve known
you for a couple of days, and I do most sincerely congratulate him.”
Ethel pressed the “horrid Guide man’s” hand, and when he and
Ted had departed, observed:
“Whilst congratulations are passing round, Jim, I congratulate
you on your friend.”
Ted shared a small, one-story residence just outside the town
with his chum Ensign Paterson. His bedroom was only just large
enough to allow sleeping-room for Jim, but hearing that Captain
Russell’s comrade of the Guides was coming to Aurungpore,
Paterson had placed his equally limited accommodation at Spencer’s
disposal. Arrived at home, Ted doffed the pigskin and discussed
horses and riding with his guest until the time came for them to sally
forth once more. A dinner was to be given by the officers of the
193rd in honour of the triumph of their regiment. For the third time
in succession they had won the Aurungpore Cup, and Ted was the
hero of the hour. He enjoyed the rôle until, his health having been
drunk with acclamation, he was called upon for a speech.
Such an ordeal had never been contemplated, and he had to be
dragged to his feet, a victim of nervous funk. As he faced his
quizzing comrades his mind was a blank; he stammered a few
incoherent sentences intended for thanks, and abruptly sat down
again, feeling convinced that he had qualified for a place in any
home for the feeble-minded. Yet the older officers liked him better
for this lack of self-confidence than had he shown no sign of
confusion. In reply to the toast, “Our Guests”, Lieutenant Spencer
made a neat and witty speech that set everyone at his ease.
The ordeal over, Spencer, Paterson, and Ted returned to the little
bungalow, and settled down to await Jim’s arrival. Lieutenant
Spencer filled his pipe and lay back in the one chair that the
apartment boasted, Paterson sat straddle-legged across a camp-
stool, and Ted squatted on a box with his back to the wall and his
legs dangling. The room was lighted by a candle stuck in a bottle,
for were they not in the “Gorgeous East” where luxury and
splendour reign supreme?
“So you fellows of the 193rd are proud of your regiment!” the
Guides’ officer observed.
“It’s a first-class corps,” Ted replied. “They fought like good ’uns
throughout both Sikh wars. You see, we’ve Bhurtpore as well as
Sobraon, Moodkee, and Gujerat on the colours; and the colonel says
he’d lead ’em anywhere—they’d follow their officers to the death.
Markham’s the favourite with the men, though they’re very fond of
the ‘old man’ and Major Munro.”
“Yours is a queer corps, is it not, Lieutenant Spencer?” Paterson
asked.
Spencer chuckled.
“It is! But I’m proud of being in the Guides.”
“They say,” continued the Scotch boy, “that you have all the
frontier races in the corps—Afridis, Afghans, and other Pathan tribes,
Sikhs and Gurkhas—and that some of them have been robbers and
outlaws, and murderers even. Is that true?”
Spencer chuckled still more.
“Quite true. We have all sorts—men with the best of characters,
men with the worst, and men with no characters at all. We’ve
outlaws and dacoits, thieves and murderers—though they don’t call
themselves murderers; they resemble the border raiders of Scotland
of some hundreds of years ago. But every man who joins the Guides
has to be strong, healthy, active, brave as a lion, able to track like a
Red Indian, climb mountains, and think for himself. Lumsden gets
hold of the most daring men on the border, such as Dilawur Khan
and Futteh Khan and Bahram Khan, and makes Guides of them.
They don’t get coddled; and I guess we shall have more work to do
in the future than any regiment in India. We’ve men of all races and
creeds and men of no race or creed—mostly big truculent Pathans,
and nearly a hundred jolly little Gurkhas sent us by the King of Nepal
at Sir Henry Lawrence’s request. Oh, it’s a grand corps! and we can
get as many men as we like—scores apply for every vacancy. Why,
there are dozens of fellows learning the drill at their own expense,
both cavalry and infantry, waiting for an opportunity to join us.
There’s no other regiment in India or England can say the same.”
“Well, I’d rather serve in the 193rd B.N.I.,” Ted declared. “I
shouldn’t care to trust your Guides very far. Why, many of your Sikhs
must have fought against us eight years ago; and as for the Afridis
and Yusufzais, they’re always raiding British territory and killing our
men, whilst the sepoys of the 193rd have fought under British
colours for half a century.”
“That’s right, young ’un; stick up for your regiment.”
“Jim was going to tell me,” Ted remarked, “something about that
Pathan officer who was speaking to you this morning. Who is he?”
“Bahram Khan, do you mean?”
“Yes, that’s the man. We noticed the natives shrinking from him
when he looked at them. Why was that?”
The lieutenant lay back in his chair and smiled.
“His is a queer story and typical of the Guides,” he replied. “A few
years ago he was a well-known outlaw and brigand chief, who raided
and burnt villages and robbed right and left. We could never catch
him, so Lumsden, our colonel, offered to make him an officer if he’d
join the Guides, and he consented and brought his brigands with
him.”
Paterson regarded the speaker curiously.
“Is that a fact?” he asked.
“It is an absolute fact.”
“We’d keep that sort of ruffian out of the 193rd, wouldn’t we,
Paterson?” Ted asserted. “Aren’t you afraid that you’ll wake up some
morning with all your throats cut?”
“Not in the least. I’d rather be with the Guides than any corps.
With all respect to your sepoys of the 193rd, they’ve neither the
stamina nor the resource of our fellows.”
“H’m! you’re welcome to them. Eh, Paterson?”
“I agree with you, Ted. Have you ever seen Colonel Nicholson,
Lieutenant Spencer?”
“Jan Nikkulseyn? Rather. I sha’n’t forget the first time I met him.
It was south of Peshawur, close to the border, where a gang of
Afghan labourers were making a road, protected by a half-company
of sepoys under an English subaltern, for it was in a wild district. It
was just after the rains, and a bullock-cart had stuck fast in the deep
mud; and the bullocks, not having the grit of a horse, wouldn’t make
any efforts. I happened to be riding past with a couple of troopers. A
big fellow standing by in civilian dress had taken his coat off and put
his shoulder to the wheel, but they couldn’t move it. This civilian,
whom I took to be the man in charge of the work, then asked the
lieutenant and the sepoys to lend a hand. But the sepoys coolly
informed him that they had enlisted to fight, not to do menial work,
and the officer said:
“‘It’s no business of mine. I’m here to protect the road-makers,
not to do their work.’
“I dismounted, and so did one of my two men. The other, Hafiz
Khan, bent down and whispered:
“‘I go to get help, Lieutenant Sahib’; and before I could stop him
he was galloping away. Well, we two turned the scale—though the
big civilian was worth us both—and at last we got the cart out and
trotted away. A mile or two farther on we saw Hafiz Khan waiting for
us, and when I slanged him for not staying to help us, he replied:
“‘But he once threatened to hang me, Lieutenant Sahib, and Jan
Nikkulseyn never breaks his word’.
“‘Who?’ I asked, quite taken aback.
“‘Jan Nikkulseyn. I am not afraid of a little pushing and pulling,
but of Jan Nikkulseyn are we all afraid.’
“The civilian was Colonel Nicholson. Hafiz Khan had been
engaged in two or three raids before he had enlisted, and, bold as
they are, there’s not a Pathan along the border dare look Nicholson
between the eyes.”
“And what became of the lieutenant?” asked Ted.
“He applied for an important appointment at Peshawur a month
later. He found out his mistake then, and felt sorry he’d ever been
born.”
A clatter of hoofs interrupted their talk, and Ted ran to the outer
door to admit his brother. Captain Russell was quiet and grave, for
his happy days had come to an end, and to-morrow the dull routine
of regimental work would begin again. He was evidently little
inclined for conversation, and before long the four officers passed off
into the adjoining bedrooms.
Captain Russell was well liked by about one-half of his
acquaintances, and disliked by a good proportion of the remainder.
His friends knew him for a brave, good-hearted, conscientious man,
and his detractors termed him a prig. The fault was in his manner, at
times heavy, awkward, and solemn, largely the result of shyness, for
with intimate friends he could be lively and full of fun.
Serious thoughts occupied his mind as he undressed. Ought not
he, the elder brother and man of experience, to give the youngster a
few words of advice, before leaving him, on some subjects more
serious than steeple-chasing? But how to begin? Jim Russell knew
his own failings, and dreaded lest Ted should sneer at him as a prig;
and he envied his chum, Spencer, who, he felt sure, could have
given the lad sound advice and warning without the least suspicion
of preaching. However, Jim was conscientious, and he resolved to
take the risk.
The ensign’s evident esprit de corps and delight in his regiment
furnished an admirable opening, and sitting on the low bed half-
undressed, the elder brother spoke like a father to the younger
concerning his duty to the regiment.
Then, as the captain was an enthusiastic admirer of the great
brothers Henry and John Lawrence, and of their band of devoted
followers, the first topic naturally led to a eulogy of the Punjab
leaders; and Jim explained to the ensign how Henry Lawrence had
begun, and how John Lawrence was now carrying on the work of
showing to the wild Sikhs, Jats, and Mohammedans of the Punjab
the highest ideal of British justice and uprightness.
Ted listened attentively, but said nothing. He too was already
filled with admiration for those Christian soldiers and statesmen who
were soon to save India.
“Not that I want you to be an objectionable young prig,” the
captain went on; “there’s a big difference between that and the
genuine article. You know what I mean?”
The ensign nodded, and Jim continued:
“I like your chum—Paterson; he seems a very decent lad. And I
noticed on one occasion that he showed he was not ashamed of his
religion. Why should we so-called Christians be so afraid of acting up
to what we profess to believe? Look at the Lawrences and Herbert
Edwardes, three of the greatest men in India! They are true
Christians, and where could you find finer soldiers and braver men?
It’s a poor soldier who’s ashamed of his colours.”
Ted nodded assent, and, feeling that he had done his duty, Jim
bade him good-night and blew out the candle.
An early breakfast next morning, and our ensign and his two
visitors were in the saddle by seven o’clock. Ten minutes later Ethel
Woodburn cantered up, attended by a sais, and Spencer and Ted
ambled along, keeping well ahead of the lovers.
“I suppose that’s the fort over there?” Spencer asked, and
pointed to an ugly square building of dark sandstone that dominated
the town.
“Yes, it’s an arsenal too. There’d be a big smash in Aurungpore if
it was to blow up,” said Ted, who little thought of the influence that
forbidding fortress would exert upon his career.
“It has half-ruined the town already by its ugliness,” Spencer
mused. “That mosque on the left is a little gem, and that dome is
perfect, but the arsenal spoils them as completely as a factory
chimney spoils a view at home. The Moslems beat us at
architecture.”
“I think I must be turning back now,” Ted presently observed, “I
have plenty to do before parade.”
They came to a halt and awaited the arrival of the others. The
lovers parted, Ted shook hands with Jim and Spencer, and nodded in
response to his brother’s parting injunction to take care of Ethel.
Miss Woodburn stayed, waving her handkerchief, until a bend of the
road hid her betrothed from view. Joining Ted, she touched her bay
lightly with the whip, and they trotted home without exchanging a
word.
CHAPTER IV
The Fanatics
In spite of our hero’s recent disgust he had quickly become
reconciled to the sweet girl who was to be his brother’s wife. There
was no resisting her charms. He found her as full of fun and as fond
of adventure as any boy could wish, and he soon grew very anxious
to win her good opinion, even attempting to show off occasionally
for her benefit. Ethel had become no less attached to the honest,
healthy-minded, plucky lad, and wrote warningly to Jim that she had
fallen desperately in love with his jolly young brother.
A few weeks had elapsed since Captain Russell’s departure, when
something happened to attach them still more closely. One beautiful
winter day Ethel asked the ensign if he would care to stroll through
the native bazar with her, and the lad willingly complied.
Not being of a very curious disposition, he had hitherto neglected
this quarter of the town, and had spent most of his leisure time
riding and shooting in the country beyond. But on this occasion the
girl was able to make the visit much more interesting than he had
anticipated. She knew the people and more than one of the many
dialects fairly well, and she pointed out to her companion the men of
various nationalities and religions who swarmed in the narrow
streets. He noticed with amazement the difference between the
strong fighting men of the North-west—the sturdy Jat and stalwart
Pathan—and the fat, mild, shrinking Babu from Bengal, or the
slender and weaker Hindu from the South.
This part of the town was quite distinct from the quarter in which
the Europeans lived, and was much more picturesque, if also more
dirty. In the narrow streets all the goods of the small shops were
exposed to the passer-by. Workmen could be seen plying their trade,
undisturbed by the inquisitive glances of the lookers-on. And what
clumsy tools they had! It would have been impossible for such
delicate, exquisite work to have been turned out therewith, had not
the artisans put their whole soul into the labour: for to do his work
thoroughly and beautifully is a religious duty with the Hindu.
Passing the stalls of the money-changers, fruit-sellers, and
dealers in native sweetmeats, their attention was attracted by
certain curios in one of the queer shops, and our ensign looked
about for something worth sending home. He fixed upon a queer
silver bangle, set with turquoises. The setting was uncommon, but
the stones were only poor. The turbaned, white-robed shopkeeper
rose and came forward at once, salaaming profoundly, and putting
on one side the hubble-bubble he was smoking. After a lengthy
argument, in which Ted failed to understand the man’s rapid
utterance, and his own Hindustani was beyond comprehension, Miss
Woodburn came to the rescue, fixed the price, and concluded the
business.
Attracted by the sahib’s curious rendering of their native tongue,
a number of the many idlers around had drawn near. At a corner of
the narrow street, not fifty paces distant, voices had been
meanwhile raised in earnest and violent harangue. Having learned
even during his short sojourn in the land how furious an altercation
may arise over a matter of a couple of annas, Ted had not paid
much attention to the noise; but now the speakers rose and came
towards them. Foremost was a tall, half-naked man, with long and
flowing beard—a mass of dirt and evil smells; for with these strange
people cleanliness is not on speaking terms with godliness, and the
most holy men are the most filthy. His eyes were inflamed, and his
looks and gestures wild. Ethel, from her longer experience, saw that
the mullah had rendered himself mad with bhang, and that two of
his companions were in a similar condition.
Pointing to the Feringhis, the mullah’s voice rose to a wild shriek.
“What do these offspring of the evil one here? O followers of the
Prophet, how long will ye allow yourselves to be denied by these
kafirs. The time is even now at hand when Allah shall no longer
permit this: then shall his wrath fall upon them, and they shall be
swept from the face of the earth. The hundred years of the white
man’s raj[1] are fulfilled, and the curse shall be lifted from us!”
[1] dominion.
The fanatic’s voice rose to a wild shriek as he concluded the
harangue. Ted could not follow the speech: he could only gather
from the tone and gestures that he and his companion were the
objects of abuse, and he guessed from the half-angry, half-cringing
manner of the tradesman that something serious was being said.
Ethel, however, understood every word, and was alarmed.
They tried to leave the bazar, but found their progress barred.
“Out of the way, there!” the ensign commanded, but no one
moved.
“Kill the kafir pigs!—there is no one to see!” called out a voice
from the rear.
“No, no!” objected others hastily. “What harm have they done?
And will not the vengeance of the Whites be upon us all? Make way
there for the sahib-log!”
But another of the bhang-drugged fanatics, who had been
swaying to and fro in his delirium, screamed:
“Aye! Why not kill now?” and he roughly seized the white-faced
girl.
With a savage exclamation the English boy sprang forward and
struck the speaker behind the ear with all his force. Not for nothing
had Edward Russell been trained in gymnastics, in boxing and
fencing—the fellow dropped like a log. But before Ted could turn or
draw his sword the mullah had plucked a knife from beneath his
scanty garment and plunged it in the lad’s side.
“Die, unbeliever!” he cried.
As the ensign pressed his hands to his side and dropped to the
earth with a feeble moan, the screaming and jabbering of the by-
standers ceased as if by magic. Even the mullah and his disciples
drew back appalled at what they had done, while the more timid of
the crowd fled to their homes in dread of the consequences and the
sure wrath of the sahibs, fearing lest vengeance should fall on
innocent and guilty alike for this murder of a white man. The
merchants before whose shops the act had been committed wrung
their hands in despair, shrieking imprecations down upon the heads
of the fanatics, who stood gazing at their handiwork.
The mullah’s hesitation lasted but a second. He turned towards
the trembling girl, and called to his abettors:
“Finish off the lad while I slay the woman!”
Ethel Woodburn was a soldier’s daughter: she had more than
once looked danger in the face bravely and calmly. Had she been
alone she might have hesitated, or had her companion been in a
condition to protect her she might have relied on him. But, seeing
the boy of whom she was so fond stretched at her feet, cruelly
wounded and helpless, and at the mercy of these madmen, her
instinct prompted her to do the right thing without a moment’s
hesitation, and she blessed the father who had taught her to carry
and use a pistol.
The little weapon was hardly more than a toy, but it checked the
assassins sufficiently to enable her to bend down swiftly and snatch
Ted’s sword from its scabbard. The murderer was but a pace away
when she pulled the trigger and stepped back. He fell, writhing, the
bullet in his chest. The second received the point of the sword under
his arm-pit as he raised his hand to strike. The third assailant, dazed
by the blow from Ted’s fist, had now risen, and was hesitating as to
his next step, when a couple of native police, attracted by the report
and noise, ran up, and, being Sikhs, they had no hesitation in
securing the uninjured Mohammedan, and they also prevented the
crowd from carrying off the wounded Wahabis.[1]
[1] The most fanatical and implacable Moslem sect.
Never losing her presence of mind, Ethel bound the unconscious
lad’s wound to stop the bleeding, and ordered the by-standers to
carry him to his quarters, where the regimental surgeon attended to
the injury. The bangle had disappeared.
A few weeks later, when the injured persons had recovered, the
three would-be assassins were tried on the charge of attempted
murder, and were sentenced to long terms of imprisonment.
Some time elapsed before Ted was able to get about as usual.
Had it not been for the bandage so promptly applied by Ethel he
must have bled to death, so she had saved his life in two different
ways. During his slow and painful recovery he was nursed untiringly
by his new sister; and though she made light of her heroic deed, the
girl’s courage and presence of mind were the chief themes of
conversation with the officers who frequently visited his bed-side,
and the ensign’s lucky brother became more envied than ever. Ethel
invariably checked his expressions of gratitude, and would not allow
him to talk about the incident.
“Bosh, Ted!” she would say; “I was in such a state of abject fear
that I didn’t know what I was doing. I only shot the man because
my hand trembled so that the trigger went off, and he happened to
be in front.”
“Certainly, Ethel, I quite understand. I’ll just read you a letter I
had this morning from Jim. You’d p’r’aps like to hear his opinion?”
“Oh, that boy’s demented! I had a note also from him this
morning. He’s quite wild.”
“Good chap Jim,—knows a thing or two!” said Ted, nodding his
head sagely.
CHAPTER V
The Cad of the Regiment
“This is the place where I was knifed, Paterson,” said Ted, “and
there’s the old boy I had been bargaining with. Watch him eyeing
me; he looks rather scared, don’t he?”
The wound was now quite healed, and impelled doubtless by a
magnetic attraction, akin perhaps to that said to be exercised on
murderers by the scenes of their crimes, our ensign had induced his
chum Paterson to stroll with him through the bazar one evening
after duty was over for the day.
While Ted had been down with his wound Alec Paterson had
opened out in a remarkable manner and thrown down the last
barriers of reserve. Ensign Paterson had only recently admitted Ted
into close friendship. He was a Scottish lad, hailing from Lanarkshire,
and no better choice of a friend could have been made. Physically he
was tall and well-formed, intellectually he was ahead of most of his
brother ensigns, and in moral character strong, upright, and healthy.
He was very reserved, difficult to know, chary of his intimacy, and
slow of speech. Tynan termed him a “saint”, and cordially disliked
him; and in return Paterson disproved the accusation of saintliness
by being obnoxiously polite and somewhat ponderously playful in his
dealings with the regimental bête noir.
“He does look scared,” Alec replied. “He must think you were
killed, and that your ghost has come to jump down his throat or ride
on his back, or whatever it is that their evil spirits do. You had better
speak and reassure him.”
As Ted approached the stall, the hand of the sleek Hindu shot
forth across the boards on which his wares were displayed and
snatched something from the front row. Not, however, before our
hero had recognized the identical bangle that he had bought and
paid for on the occasion of his previous visit. His face flushed.
“That is mine,” he asserted. “I bought and paid for it.”
Understanding that the bangle had been seen, and that denial
was useless, the shopkeeper salaamed and unabashed replied: “Nay,
sahib, the one you bought you took away, and I have never set eyes
on it since.”
“But you told me it was unique—that there was not another like
it in the country.”
“I am the sahib’s slave, and I spoke truth. There was not another
like it in the Punjab. But since the Heaven-born’s visit a Kazilbash
merchant from Kabul, with whom I deal in turquoises, has sold me
this. It is indeed similar to the one I sold the sahib, but the
turquoises are larger and better. Welcome is the sight of the Heaven-
born in the eyes of his servant, who has suffered great anxiety.”
“What’s the row, Ted?” Paterson asked. And matters being
explained, he at once enquired of the Hindu why he had been so
anxious to prevent the bangle being seen if he had come by it
honestly. But the “Aryan brown” was more than their match in guile.
“In truth I remembered how the former one had brought ill-luck
to the young sahib, and I feared lest he might take a fancy to this
one also. And I know that the sahibs are reckless in such matters,
not believing in omens. Rather would I lose business than bring
misfortune upon the head of the young sahib.”
Alec Paterson laughed.
“I’m afraid it’s no go, Russell,” he whispered. “The rascal is too
deep for us, and we cannot prove that it really is the same article.”
“But it’s robbery pure and simple!” Ted indignantly declared. “I
know it’s the same that I lost during the scuffle.”
The shopkeeper regarded them gravely and sadly, as though he
felt deeply the doubts they had cast upon his honesty. He produced
one article after another, tempting them in vain to buy. At length,
guessing that the boy had set his heart upon the bangle, he offered
him the pretty toy for thirty rupees, assuring him that he had given
twice that sum to the Kazilbash.
“I’ll give you fifteen,” said Ted, “and not an anna more.”
The Hindu shook his head.
“I am poor man,” said he, “else would I gladly beg the sahib to
accept it as a present.”
“Very well,” Ted firmly rejoined. “Come along, Alec.”
They turned to go, but the Hindu hastily recalled them.
“Nay,” said he, “I had forgotten that the sahib had to suffer the
loss of the first one. For twenty rupees will I sell it, or, in truth, give
it away, rather than that the Heaven-born should be disappointed.”
“Fifteen,” was all Ted’s answer; and once more the bangle
changed hands, and the ensign left the shop. On the way to
cantonments they overtook Harry Tynan, the object of their mutual
dislike, and were about to pass with a nod as devoid of cordiality as
decency would permit, when Tynan spoke, or rather sneered: “Why,
Russell, I thought you always took a girl to protect you whenever
you went into the bazar!”
“Did you really now?” asked Ted banteringly. “Wasn’t it an
effort?”
“What do you mean? Was what an effort?”
“To think—so unusual, you know, for you.”
“Oh how clever you are! But how aren’t you keeping an eye on
Brother Jim’s future wife, according to instructions? I saw her this
evening flirting as usual with the Commissioner Sahib. You are not
doing your duty. Captain Russell ’ud be angry if he knew.”
“Come along, Russell; what’s the use of talking to that cad?”
whispered Paterson. “Contemptible toad!”
But his friend’s ire had been aroused by the last remark. He
halted and faced Tynan.
“What d’you mean?” he demanded.
Tynan slowly drew a huge cheerot from his lips and attempted to
blow rings of smoke before replying.
“You know well enough. Stunnin’ little flirt is Ethel—deuced
stunnin’! Shouldn’t be surprised if she threw Brother Jim over!”
“What do you mean?” repeated Ted with still greater heat.
“Don’t be an ass, Ted. Leave the cad alone,” Paterson again
whispered.
Tynan was Russell’s senior by nearly a couple of years, and he
stood a clear three inches taller. Ted’s anger amused him.
“Why—don’t you know?” he innocently enquired. “You see, our
little Ethel had been setting her cap at Sir Arthur Fletcher for months
before she saw your brother. But Arthur knows what’s what, and the
little darling has had to put up with a mere captain of the Guides.
But she still hankers after the commissioner, and sighs for the handle
to her name.”
“Ye leein’ hyæna!” Paterson burst out, his native dialect rising to
the surface in his excitement. “Keep a ceevil tongue in your heid, or
I’ll knock ye down!”
“No, you don’t, Paterson,” broke in Ted. “That’s my business. You
cad, to lie like that about a girl you’re not fit to speak to! Take that!”
Our ensign struck his comrade across the face—a resounding
smack with the open palm.
The fight was very short. Though tall enough, Tynan was weedy
and unfit. For several years he had considered himself a man of the
world, and one of the chief aims—if not the chief—of his life had
been to convince his associates that he was well qualified for that
dignified position, and the attainment of this object had, of course,
necessitated abundant smoking and drinking. Wonderful to relate,
no one had so far seemed greatly impressed!
Five minutes after the first blow, with bleeding nose and
damaged eye, the contemptible fellow was sullenly admitting that he
had had enough.
“Think it over the nicht,” Paterson suggested. “If ye hev not I’ll
just gie ye seemilar satisfaction. And I’d hev ye obsairve it wad be
safer to cam’ oot wi’ no mair lees o’ that sort. Cam’ awa’, Russell!”
“Wait a moment, I’ve not done yet,” said Ted. “Let me inform you
now, you cad, what I would not waste my breath in telling you
before—that Miss Woodburn had refused Sir Arthur Fletcher before
she became engaged to my brother, and that he has congratulated
my brother, and is a loyal, honourable gentleman, of whose
friendship Miss Woodburn is proud; and don’t let me hear you
speaking of her again as you did just now.”
The chums left the miserable being—neither man nor boy—to
follow as he chose.
“What garred ye say that last, Russell?” asked the Scottish lad,
who was still labouring under strong excitement, as soon as they
had passed out of hearing.
“What? About Fletcher?”
“Yea You’d no right to drag his refusal into the affair!” Paterson
dropped the tell-tale accent as he spoke more slowly. “That’s
between him and Miss Woodburn, and he wouldn’t thank you if he
knew, nor would she. It was perhaps very satisfying to you, but they
don’t need to be defended from a fellow like our friend yonder.”
“I’m very sorry—I’m a fool! I was so angry I didn’t stop to think.
Bah! he leaves a bad taste in the mouth, that fellow!”
“We should have passed him without taking any notice,” Paterson
went on. “But it served him right!”
For the future Tynan gave his conqueror a wide berth, and Ted
ignored his existence as far as their respective duties, would permit.
Returning from the officers’ mess that evening, Ted was accosted
by Pir Baksh, the Mohammedan captain.
“I saw you fight with Ensign Tynan,” said he. “He is the kind of
officer to ruin a regiment. Once he dared to call me a soor (pig)
before my men, and I thank you, sahib, for teaching him a lesson.”
CHAPTER VI
The Outbreak of the Mutiny
On the night of Monday, May 11, some weeks after Ted’s
recovery, Ethel’s twenty-first birthday was celebrated, Colonel
Woodburn entertaining the officers and British residents of
Aurungpore. The season was too warm for more than occasional
dancing, and conversation was the order of the night—conversation
serious and frivolous, harmless flirtations between the younger
members, and solemn interchange of views concerning the
rumoured dissatisfaction prevailing amongst the native troops, a
subject pooh-poohed by some and laughed at by others, but gravely
regarded by a few—when an orderly entered and handed a missive
to the colonel. As he opened it and read he gave a start, and his
face paled for one brief second, but soon resumed its ordinary
aspect as he slowly folded the paper and placed it in his pocket.
A few moments later he crossed over to Major Munro, who at
once left the room after speaking to the adjutant and another officer.
These two also took their departure before long, and one by one the
remainder of the officers were spoken to and retired to their mess-
room, where they were shortly joined by Colonel Woodburn.
“I have terrible news,” he informed them, “but we must try to
avoid alarming either the ladies or the sepoys. The 3rd Native
Cavalry and the 11th and 20th Native Infantry have broken into
mutiny at Meerut, killed some of their officers, and, so the message
runs, are sacking the town and murdering right and left.”
“At Meerut!” gasped Major Munro. “How at Meerut of all places?
They couldn’t—it’s simply impossible!”
“It must be true,” declared the colonel, “though it certainly does
seem impossible. One would think they would have broken out at
Cawnpore, or Benares, or Allahabad, or here, or anywhere rather
than Meerut. But this report must be exaggerated! How could they
sack the town and murder in the face of those English regiments and
the Artillery? It’s incomprehensible!”
Now even Ensign Russell, a mere griffin, knew that Meerut—a
large station more than fifty miles north-east of Delhi—was
considered a model cantonment, and contained the strongest British
force in all India. Could a revolt seem more hopeless than at this
station, where the three native corps were more than
counterbalanced by a regiment of British dragoons, the 60th Rifles,
and two batteries of the finest artillery in the world—a force
sufficient to repress any rising within ten minutes—whereas
throughout the seven hundred and fifty miles of territory along the
Ganges, in the districts containing the large towns of Agra,
Allahabad, Benares, Cawnpore, Lucknow, and Patna, there were only
three weak British corps to oppose nearly a score of sepoy regiments
and many thousands of armed rebels?
“There’s no saying how it will spread,” continued the colonel. “We
must take all precautions, though I believe our men are perfectly
trustworthy. There must be some mistake, and I’ve no doubt that we
shall hear to-morrow that the rebels have been cut to pieces. I’m
afraid the silly fellows will be slaughtered by hundreds.”
But the news of the morning and of the succeeding days was no
less hard to understand. Eighty-five men of the 3rd Native Cavalry (a
corps composed of Hindus and Mohammedans) had refused to use
the cartridges served out, alleging that the fat of pigs and of cows
had been employed in the manufacture.
As most readers will know, the pig is regarded as unclean by all
Moslems, and the cow is holy to Hindus, so that to touch the fat of
these animals would imperil their salvation and shut them out of
Paradise. The mullahs and fakirs had been poisoning the minds of
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Core Java Volume I Fundamentals 12th Horstmann Cay
PPT
01-introduction OOPS concepts in C++ JAVA
PPT
01-introductionto Object ooriented Programming in JAVA CS.ppt
PPT
38 object-concepts
PPT
38-object-concepts.ppt
PPT
38 object-concepts (1)
PPT
oops -concepts
PDF
MCA NOTES.pdf
Core Java Volume I Fundamentals 12th Horstmann Cay
01-introduction OOPS concepts in C++ JAVA
01-introductionto Object ooriented Programming in JAVA CS.ppt
38 object-concepts
38-object-concepts.ppt
38 object-concepts (1)
oops -concepts
MCA NOTES.pdf

Similar to Objects First With Java A Practical Introduction Using Bluej 1st Edition David J Barnes (20)

PDF
Download full ebook of Java Cookbook Ian F Darwin Darwin Ian F instant downlo...
PDF
[FREE PDF sample] Object Oriented Programming and Java Second Edition Danny P...
PDF
M.c.a. (sem iv)- java programming
PPTX
Object Oriented Programming
PDF
PDF
Basic object oriented concepts (1)
PDF
java-language-programação.2-PDF Room.pdf
PPT
Object concepts
PDF
Learning Java 4th Edition Patrick Niemeyer Daniel Leuck
PPT
Polymorphism 9
PPT
Polymorphism 9
PDF
Objectoriented Programming And Java 2nd Ed Danny C C Poo Derek Beng Kee Kiong...
PPT
Chapter08
PPTX
Effective Java
PDF
Java classes in karve nagar pune
PPT
chapter07 - well-behaved object buku object first.ppt
PDF
Java Programming.pdf
PDF
(eBook PDF) Data Structures and Other Objects Using Java 4th Edition
PDF
Java How To Program Fourth Edition Harvey M. Deitel
PPT
Object concepts
Download full ebook of Java Cookbook Ian F Darwin Darwin Ian F instant downlo...
[FREE PDF sample] Object Oriented Programming and Java Second Edition Danny P...
M.c.a. (sem iv)- java programming
Object Oriented Programming
Basic object oriented concepts (1)
java-language-programação.2-PDF Room.pdf
Object concepts
Learning Java 4th Edition Patrick Niemeyer Daniel Leuck
Polymorphism 9
Polymorphism 9
Objectoriented Programming And Java 2nd Ed Danny C C Poo Derek Beng Kee Kiong...
Chapter08
Effective Java
Java classes in karve nagar pune
chapter07 - well-behaved object buku object first.ppt
Java Programming.pdf
(eBook PDF) Data Structures and Other Objects Using Java 4th Edition
Java How To Program Fourth Edition Harvey M. Deitel
Object concepts
Ad

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Classroom Observation Tools for Teachers
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Insiders guide to clinical Medicine.pdf
PPTX
master seminar digital applications in india
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
VCE English Exam - Section C Student Revision Booklet
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Cell Types and Its function , kingdom of life
Anesthesia in Laparoscopic Surgery in India
human mycosis Human fungal infections are called human mycosis..pptx
O7-L3 Supply Chain Operations - ICLT Program
Pharma ospi slides which help in ospi learning
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Classroom Observation Tools for Teachers
Module 4: Burden of Disease Tutorial Slides S2 2025
Microbial diseases, their pathogenesis and prophylaxis
Renaissance Architecture: A Journey from Faith to Humanism
Microbial disease of the cardiovascular and lymphatic systems
Insiders guide to clinical Medicine.pdf
master seminar digital applications in india
STATICS OF THE RIGID BODIES Hibbelers.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
VCE English Exam - Section C Student Revision Booklet
Ad

Objects First With Java A Practical Introduction Using Bluej 1st Edition David J Barnes

  • 1. Objects First With Java A Practical Introduction Using Bluej 1st Edition David J Barnes download https://ebookbell.com/product/objects-first-with-java-a- practical-introduction-using-bluej-1st-edition-david-j- barnes-973080 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Objects First With Java A Practical Introduction Using Bluej 5th David J Barnes https://ebookbell.com/product/objects-first-with-java-a-practical- introduction-using-bluej-5th-david-j-barnes-51623770 Objects First With Java A Practical Introduction Using Bluej 4 Ed Barnes https://ebookbell.com/product/objects-first-with-java-a-practical- introduction-using-bluej-4-ed-barnes-22004612 Objects First With Java A Practical Introduction Using Bluej 5th Edition David J Barnes https://ebookbell.com/product/objects-first-with-java-a-practical- introduction-using-bluej-5th-edition-david-j-barnes-4541212 Objects First With Java A Practical Introduction Using Bluej 6th David J Barnes Michael Klling https://ebookbell.com/product/objects-first-with-java-a-practical- introduction-using-bluej-6th-david-j-barnes-michael-klling-10670742
  • 3. Objects First With Java A Practical Introduction Using Bluej 6th Edition David Barnes https://ebookbell.com/product/objects-first-with-java-a-practical- introduction-using-bluej-6th-edition-david-barnes-12118812 Objects First With Java A Practical Introduction Using Bluej David J Barnes https://ebookbell.com/product/objects-first-with-java-a-practical- introduction-using-bluej-david-j-barnes-4333392 Lets Hope Theyre Friendly The Kaikoura Ufos First Verified Film Encounter With Unidentified Flying Objects Quentin Fogarty https://ebookbell.com/product/lets-hope-theyre-friendly-the-kaikoura- ufos-first-verified-film-encounter-with-unidentified-flying-objects- quentin-fogarty-36046516 Objectrole Modeling Fundamentals A Practical Guide To Data Modeling With Orm First Terry Halpin https://ebookbell.com/product/objectrole-modeling-fundamentals-a- practical-guide-to-data-modeling-with-orm-first-terry-halpin-5526556 A First Course In Computational Physics And Objectoriented Programming With C Hardback With Cdrom David Yevick https://ebookbell.com/product/a-first-course-in-computational-physics- and-objectoriented-programming-with-c-hardback-with-cdrom-david- yevick-47506166
  • 5. 1 David Barnes Michael Kölling Objects First with Java A Practical Introduction using BlueJ FOR EVALUATION ONLY NOT FOR DISTRIBUTION Copyright © Barnes, Kölling, 2002 Pearson Education / Prentice Hall ISBN 0-13-044929-6
  • 6. 2 Contents LIST OF PROJECTS DISCUSSED IN DETAIL IN THIS BOOK 11 PREFACE TO THE INSTRUCTOR 14 PART I: Foundations of object orientation CHAPTER 1 OBJECTS AND CLASSES 23 1.1 Objects and classes 23 1.2 Creating objects 24 1.3 Calling methods 25 1.4 Parameters 26 1.5 Data types 27 1.6 Multiple instances 28 1.7 State 28 1.8 What is in an object? 29 1.9 Object interaction 31 1.10 Source code 32 1.11 Another example 33 1.12 Return values 33 1.13 Objects as parameters 34 1.14 Summary 36 Terms introduced in this chapter 36 Concept summary 36 CHAPTER 2 UNDERSTANDING CLASS DEFINITIONS 38 2.1 Ticket machines 38 2.1.1 Exploring the behavior of a naïve ticket machine 39 2.2 Examining a class definition 39 2.3 Fields, constructors, and methods 42 2.3.2 Fields 43 2.3.3 Constructors 44 2.4 Passing data via parameters 46 2.5 Assignment 47 2.6 Accessor methods 48 2.7 Mutator methods 50 2.8 Printing from methods 52 2.9 Summary of the naïve ticket machine 54
  • 7. 3 2.10 Reflecting on the design of the ticket machine 55 2.11 Making choices: the conditional statement 56 2.12 A further conditional-statement example 59 2.13 Local variables 60 2.14 Fields, parameters, and local variables 61 2.15 Summary of the better ticket machine 62 2.16 Reviewing a familiar example 62 2.17 Summary 65 Terms introduced in this chapter 66 Concept summary 66 CHAPTER 3 OBJECT INTERACTION 70 3.1 The clock example 70 3.2 Abstraction and modularization 71 3.3 Abstraction in software 72 3.4 Modularization in the clock example 72 3.5 Implementing the clock display 73 3.6 Class diagrams versus object diagrams 74 3.7 Primitive types and object types 75 3.8 The ClockDisplay source code 76 3.8.1 Class NumberDisplay 77 3.8.2 String concatenation 78 3.8.3 The modulo operator 80 3.8.4 Class ClockDisplay 80 3.9 Objects creating objects 83 3.10 Multiple constructors 84 3.11 Method calls 85 3.11.1 Internal method calls 85 3.11.2 External method calls 85 3.11.3 Summary of the clock display 87 3.12 Another example of object interaction 87 3.12.1 The mail system example 88 3.12.2 The this keyword 89 3.13 Using a debugger 91 3.13.2 Setting breakpoints 91 3.13.3 Single stepping 93 3.13.4 Stepping into methods 94 3.14 Method calling revisited 95 3.15 Summary 96 Terms introduced in this chapter 96 Concept summary 97 CHAPTER 4 GROUPING OBJECTS 98 4.1 Grouping objects in flexible-size collections 98 4.2 A personal notebook 99 4.3 A first look at library classes 99 4.3.1 An example of using a library 99 4.4 Object structures with collections 101
  • 8. 4 4.5 Numbering within collections 103 4.6 Removing an item from a collection 103 4.7 Processing a whole collection 104 4.7.1 The while loop 105 4.7.2 Iterating over a collection 107 4.7.3 Index access versus iterators 108 4.8 Summary of the notebook example 108 4.9 Another example – an auction system 109 4.9.1 The Lot class 109 4.9.2 The Auction class 110 4.9.3 Casting 112 4.10 Fixed-size collections 113 4.10.1 A log-file analyzer 114 4.10.2 Declaring array variables 116 4.10.3 Creating array objects 117 4.10.4 Using array objects 118 4.10.5 Analyzing the log file 119 4.10.6 The for loop 119 4.11 Summary 123 Terms introduced in this chapter 123 Concept summary 123 CHAPTER 5 MORE SOPHISTICATED BEHAVIOR 125 5.1 Documentation for library classes 126 5.2 The TechSupport System 127 5.2.1 Exploring the TechSupport System 127 5.2.2 Reading the code 131 5.3 Reading class documentation 132 5.3.2 Interfaces versus implementation 133 5.3.3 Using library-class methods 134 5.3.4 Checking string equality 136 5.4 Adding Random behavior 136 5.4.1 The Random class 137 5.4.2 Random numbers with limited range 138 5.4.3 Generating random responses 139 5.5 Packages and import 141 5.6 Using maps for associations 142 5.6.2 The concept of a map 143 5.6.3 Using a HashMap 143 5.6.4 Using a map for the TechSupport system 144 5.7 Using sets 146 5.8 Tokenizing Strings 147 5.9 Finishing the TechSupport system 148 5.10 Writing class documentation 150 5.10.1 Using javadoc in BlueJ 151 5.10.2 Elements of class documentation 151 5.11 Public versus private 153 5.11.1 Information hiding 154 5.11.2 Private methods and public fields 154 5.12 Learning about classes from their interfaces 155 5.13 Class variables and constants 158
  • 9. 5 5.13.2 The static keyword 158 5.13.3 Constants 160 5.14 Summary 160 Terms introduced in this chapter 160 Concept summary 161 CHAPTER 6 WELL-BEHAVED OBJECTS 163 6.1 Introduction 163 6.2 Testing and debugging 164 6.3 Unit testing within BlueJ 164 6.3.1 Using inspectors 168 6.3.2 Positive versus negative testing 170 6.4 Test automation 170 6.4.1 Regression testing 170 6.4.2 Automated checking of test results 173 6.5 Modularization and interfaces 174 6.6 A debugging scenario 176 6.7 Commenting and style 176 6.8 Manual walkthroughs 177 6.8.1 A high-level walkthrough 178 6.8.2 Checking state with a walkthrough 180 6.8.3 Verbal walkthroughs 182 6.9 Print statements 183 6.9.2 Turning debugging information on or off 185 6.10 Debuggers 186 6.11 Putting the techniques into practice 187 Terms introduced in this chapter 187 Concept summary 187 CHAPTER 7 DESIGNING CLASSES 188 7.1 Introduction 188 7.2 The world-of-zuul game example 190 7.3 Introduction to coupling and cohesion 192 7.4 Code duplication 193 7.5 Making extensions 196 7.5.1 The task 196 7.5.2 Finding the relevant source code 196 7.6 Coupling 198 7.6.1 Using encapsulation to reduce coupling 198 7.7 Responsibility-driven design 202 7.7.1 Responsibilities and coupling 202 7.8 Localizing change 205 7.9 Implicit coupling 205 7.10 Thinking ahead 208 7.11 Cohesion 209 7.11.1 Cohesion of methods 209 7.11.2 Cohesion of classes 210 7.11.3 Cohesion for readability 211
  • 10. 6 7.11.4 Cohesion for reuse 212 7.12 Refactoring 213 7.12.1 Refactoring and testing 213 7.12.2 An example of refactoring 214 7.13 Design guidelines 217 7.14 Executing without BlueJ 218 7.14.1 Class methods 218 7.14.2 The main method 219 7.14.3 Limitations of class methods 220 7.15 Summary 220 Terms introduced in this chapter 220 Concept summary 220 PART II: Application structures CHAPTER 8 IMPROVING STRUCTURE WITH INHERITANCE 223 8.1 The DoME example 223 8.1.1 DoME classes and objects 224 8.1.2 DoME source code 226 8.1.3 Discussion of the DoME application 231 8.2 Using inheritance 232 8.3 Inheritance hierarchies 234 8.4 Inheritance in Java 235 8.4.1 Inheritance and access-rights 236 8.4.2 Inheritance and initialization 236 8.5 DoME: Adding other item types 238 8.6 Advantages of inheritance (so far) 240 8.7 Subtyping 240 8.7.1 Subclasses and subtypes 242 8.7.2 Subtyping and assignment 242 8.7.3 Subtyping and parameter passing 243 8.7.4 Polymorphic variables 244 8.8 The Object class 245 8.9 Polymorphic collections 246 8.9.1 Element types 246 8.9.2 Casting revisited 247 8.9.3 Wrapper classes 248 8.10 The collection hierarchy 249 8.11 Summary 249 Terms introduced in this chapter 250 Concept summary 250 CHAPTER 9 MORE ABOUT INHERITANCE 252 9.1 The problem: DoME’s print method 252 9.2 Static type and dynamic type 253
  • 11. 7 9.2.2 Calling print from Database 255 9.3 Overriding 257 9.4 Dynamic method lookup 258 9.5 Super call in methods 261 9.6 Method polymorphism 262 9.7 Object methods: toString 262 9.8 Protected access 265 9.9 Another example of inheritance with overriding 267 9.10 Summary 270 Terms introduced in this chapter 270 Concept summary 270 CHAPTER 10 FURTHER ABSTRACTION TECHNIQUES 271 10.1 Simulations 271 10.2 The foxes-and-rabbits simulation 272 10.2.1 The foxes-and-rabbits project 273 10.2.2 The Rabbit class 275 10.2.3 The Fox class 278 10.2.4 The Simulator class – setup 280 10.2.5 The Simulator class – a simulation step 283 10.2.6 Taking steps to improve the simulation 284 10.3 Abstract classes 285 10.3.2 The Animal superclass 285 10.3.3 Abstract methods 286 10.3.4 Abstract classes 288 10.4 More abstract methods 290 10.5 Multiple inheritance 292 10.5.1 An Actor class 292 10.5.2 Flexibility through abstraction 293 10.5.3 Selective drawing 294 10.5.4 Drawable actors: multiple inheritance 295 10.6 Interfaces 295 10.6.1 An Actor interface 295 10.6.2 Multiple inheritance of interfaces 297 10.6.3 Interfaces as types 297 10.6.4 Interfaces as specifications 298 10.6.5 A further example of interfaces 299 10.6.6 Abstract class or interface? 301 10.7 Summary of inheritance 301 10.8 Summary 301 Terms introduced in this chapter 302 Concept summary 302 CHAPTER 11 HANDLING ERRORS 303 11.1 The address-book project 304 11.2 Defensive programming 307 11.2.1 Client-server interaction 307 11.2.2 Argument checking 309 11.3 Server error reporting 310
  • 12. 8 11.3.2 Notifying the user 311 11.3.3 Notifying the client object 311 11.4 Exception-throwing principles 314 11.4.1 Throwing an exception 314 11.4.2 Exception classes 315 11.4.3 The effect of an exception 317 11.4.4 Unchecked exceptions 317 11.4.5 Preventing object creation 319 11.5 Exception handling 320 11.5.1 Checked exceptions: the throws clause 320 11.5.2 Catching exceptions: the try block 320 11.5.3 Throwing and catching multiple exceptions 322 11.5.4 Propagating an exception 323 11.5.5 The finally clause 323 11.6 Defining new exception classes 324 11.7 Error recovery and avoidance 326 11.7.1 Error recovery 326 11.7.2 Error avoidance 327 11.8 Case study: Text input-output 329 11.8.1 Readers, writers, and streams 330 11.8.2 The address-book-io project 330 11.8.3 Text output with FileWriter 332 11.8.4 Text input with FileReader 333 11.8.5 Object serialization 334 11.9 Summary 335 Terms introduced in this chapter 335 Concept summary 335 CHAPTER 12 DESIGNING APPLICATIONS 336 12.1 Analysis and design 336 12.1.1 The verb/noun method 337 12.1.2 The cinema booking example 337 12.1.3 Discovering classes 337 12.1.4 Using CRC cards 338 12.1.5 Scenarios 339 12.2 Class design 343 12.2.1 Designing class interfaces 344 12.2.2 User interface design 345 12.3 Documentation 345 12.4 Cooperation 346 12.5 Prototyping 346 12.6 Software growth 347 12.6.1 Waterfall model 347 12.6.2 Iterative development 348 12.7 Using design patterns 349 12.7.1 Structure of a pattern 350 12.7.2 Decorator 350 12.7.3 Singleton 351 12.7.4 Factory method 352 12.7.5 Observer 352 12.7.6 Pattern summary 354
  • 13. 9 12.8 Summary 355 Terms introduced in this chapter 355 Concept summary 355 CHAPTER 13 A CASE STUDY 357 13.1 The case study 357 13.1.1 The problem description 357 13.2 Analysis and design 358 13.2.1 Discovering classes 358 13.2.2 Using CRC cards 359 13.2.3 Scenarios 360 13.3 Class design 362 13.3.1 Designing class interfaces 362 13.3.2 Collaborators 362 13.3.3 The outline implementation 363 13.3.4 Testing 367 13.3.5 Some remaining issues 367 13.4 Iterative development 367 13.4.1 Development steps 367 13.4.2 A first stage 369 13.4.3 Testing the first stage 372 13.4.4 A later stage of development 373 13.4.5 Further ideas for development 375 13.4.6 Reuse 375 13.5 Another example 376 13.6 Taking things further 376 APPENDIX A WORKING WITH A BLUEJ PROJECT 377 A.1 Installing BlueJ 377 A.2 Opening a project 377 APPENDIX B JAVA DATA TYPES 378 B.1 Primitive types 378 B.2 Object types 379 APPENDIX C JAVA CONTROL STRUCTURES 380 C.1 Selection statements 380 C.2 Loops 382 13.7 Exceptions 383 APPENDIX D OPERATORS 384 D.1 Arithmetic expressions 384
  • 14. 10 APPENDIX E RUNNING JAVA WITHOUT BLUEJ 385 E.1 Executing without BlueJ 385 E.2 Creating executable Jar files 387 E.3 Developing without BlueJ 387 APPENDIX F CONFIGURING BLUEJ 388
  • 15. 11 List of projects discussed in detail in this book shapes chapter 1 Simple drawing with some geometrical shapes; illustrates creation of objects, method calling, and parameters. picture chapter 1 An example using shape objects to draw a picture; introduces source code, Java syntax, and compilation. lab-classes chapter 1, chapter 2, chapter 8 A simple example with classes of students; illustrates objects, fields, and methods. Used again in chapter 8 to add inheritance. ticket-machine chapter 2 A simulation of a ticket vending machine for train tickets; introduces more about fields, constructors, accessor and mutator methods, parameters, and some simple statements. book chapter 2 Storing details of a book. Reinforcing the constructs used in the ticket-machine example. clock-display chapter 3 An implementation of a display for a digital clock; illustrates the concepts of abstraction, modularization and object interaction. mail system chapter 3 A simple simulation of an email system. Used to demonstrate object creation and interaction. notebook chapter 4 An implementation of a (simple) electronic note book; used to introduce collections and loops. auction chapter 4 An auction system. More about collections and loops, this time with iterators. weblog-analyzer chapter 4 A program to analyze web access log files; introduces arrays and for loops.
  • 16. 12 tech-support chapter 5 An implementation of an Eliza-like dialog program used to provide "technical support" to customers; introduces use of library classes in general and some specific classes in particular; reading and writing of documentation. balls chapter 5 A graphical animation of bouncing balls; demonstrates interface/implementation separation and simple graphics. diary chapter 6 The early stages of an implementation of a diary storing appointments; used to discuss testing and debugging strategies. calculator chapter 6 An implementation of a desk calculator. This example reinforces concepts introduced earlier, and is used to discuss testing and debugging. bricks chapter 6 A simple debugging exercise; models filling palettes with bricks for simple computations. world-of-zuul chapter 7, chapter 9 A text based, interactive adventure game. Highly extendable, makes a great open-ended student project. Used here to discuss good class design, coupling, and cohesion. Used again in chapter 9 as an example for use of inheritance. dome chapter 8, chapter 9 A database of CDs and videos. This project is discussed and then extended in great detail to introduce the foundations of inheritance and polymorphism. foxes-and-rabbits chapter 10 A classic predator-prey simulation; reinforces inheritance concepts and adds abstract classes and interfaces. address-book chapter 11 An implementation of an address book with an optional GUI interface. Lookup is flexible: entries can be searched by partial definition of name or phone number. This project makes extensive use of exceptions. cinema-booking-system chapter 12 A system to manage advance seat bookings in a cinema. This example is used in a discussion of class discovery and application design. No code is provided as the example represents developing an application from a blank sheet of paper.
  • 17. 13 taxi chapter 13 The taxi example is a combination of a booking system, management system, and simulation. It is used as a case study to bring together many of the concepts and techniques discussed throughout the book.
  • 18. 14 Preface to the instructor This book is an introduction to object-oriented programming for beginners. The main focus of the book is general object-oriented and programming concepts from a software engineering perspective. While the first chapters are written for students with no programming experience, later chapters are suitable for more advanced or professional programmers as well. In particular, programmers with experience in a non-object-oriented language who wish to migrate their skills into object orientation should also be able to benefit from the book. We use two tools throughout the book to enable the concepts introduced to be put into practice: These tools are the Java programming language and the Java development environment BlueJ. Java Java was chosen because of a combination of two aspects: the language design and its popularity. The Java programming language itself provides a very clean implementation of most of the important object-oriented concepts, and serves well as an introductory teaching language. Its popularity ensures an immense pool of support resources. In any subject area, having a variety of sources of information available is very helpful, for teachers and students alike. For Java in particular, countless books, tutorials, exercises, compilers, environments, and quizzes already exist, in many different kinds and styles. Many of them are online and many are available free of charge. The large amount and good quality of support material makes Java an excellent choice as an introduction to object-oriented programming. With so much Java material already available, is there still room for more to be said about it? We think there is, and the second tool we use is one of the reasons ... BlueJ The second tool, BlueJ, deserves more comment. This book is unique in its completely integrated use of the BlueJ environment. BlueJ is a Java development environment that was designed at Monash University, Australia, explicitly as an environment for teaching introductory object-oriented programming. It is better suited to introductory teaching than other environments for a variety of reasons: • The user interface is much simpler. Beginning students can typically use the BlueJ environment in a competent manner after 20 minutes of introduction. From then on, instruction can concentrate on the important concepts at hand –
  • 19. 15 object orientation and Java – and no time needs to be wasted talking about environments, file systems, class paths, DOS commands or DLL conflicts. • The environment supports important teaching tools not available in other environments. One of them is visualization of class structure. BlueJ automatically displays a UML-like diagram representing the classes and relationships in a project. Visualizing these important concepts is a great help to both teachers and students. It is hard to grasp the concept of an object when all you ever see on the screen is lines of code! The diagram notation is a simple subset of UML, again tailored to the needs of beginning students. This makes it easy to understand, but also allows migration to full UML in later courses. • One of the most important strengths of the BlueJ environment is the user’s ability to create directly objects of any class, and then to interact with their methods. This creates the opportunity for direct experimentation with objects, for little overhead in the environment. Students can almost ‘feel’ what it means to create an object, call a method, pass a parameter or receive a return value. They can try out a method immediately after it has been written, without the need to write test drivers. This facility is an invaluable aid in understanding the underlying concepts and language details. BlueJ is a full Java environment. It is not a cut down, simplified version of Java for teaching. It runs on top of Sun Microsystems' Java Development Kit, and makes use of the standard compiler and virtual machine. This ensures that it always conforms to the official and most up-to-date Java specification. The authors of this book have several years of teaching experience with the BlueJ environment (and many more years without it before that). We both have experienced how the use of BlueJ has increased the involvement, understanding and activity of students in our courses. One of the authors is also a developer of the BlueJ system. Real objects first One of the reasons for choosing BlueJ was that it allows an approach where teachers truly deal with the important concepts first. “Objects first” has been a battle cry for many textbook authors and teachers for some time. Unfortunately, the Java language does not make this noble goal very easy. Numerous hurdles of syntax and detail have to be overcome before the first experience with a living object arises. The minimal Java program to create and call an object typically includes: • writing a class; • writing a main method, including concepts such as static methods, parameters, and arrays in the signature; • a statement to create the object (‘new’); • an assignment to a variable; • the variable declaration, including variable type; • a method call, using dot notation; • possibly a parameter list.
  • 20. 16 As a result, textbooks typically either • have to work their way through this forbidding list, and only reach objects somewhere around chapter 4; or • use a “Hello, world”-style program with a single static main method as the first example, thus not creating any objects at all. With BlueJ, this is not a problem. A student can create an object and call its methods as the very first activity! Because users can create and interact with objects directly, concepts such as classes, objects, methods and parameters can easily be discussed in a concrete manner before looking at the first line of Java syntax. Instead of explaining more about this here, we suggest that the curious reader dip into Chapter 1 – things will quickly become clear then. An iterative approach Another important aspect of this book is that it follows an iterative style. In the computing education community, a well-known educational design pattern exists that states that important concepts should be taught early and often.1 It is very tempting for textbook authors to try and say everything about a topic at the point where it is introduced. For example, it is common, when introducing types, to give a full list of built-in data types, or to discuss all available kinds of loops when introducing the concept of a loop. These two approaches conflict: we cannot concentrate on discussing important concepts first, and at the same time provide complete coverage of all topics encountered. Our experience with textbooks is that much of the detail is initially distracting, and has the effect of drowning the important points, thus making them harder to grasp. In this book, we touch on all of the important topics several times, both within the same chapter and across different chapters. Concepts are usually introduced at a level of detail necessary for understanding and applying the task at hand. They are revisited later in a different context, and understanding deepens as the reader continues through the chapters. This approach also helps to deal with the frequent occurrence of mutual dependencies between concepts. Some teachers may not be familiar with an iterative approach. Looking at the first few chapters, teachers used to a more sequential introduction will be surprised about the number of concepts touched on this early. It may seem like a steep learning curve. It is important to understand that this is not the end of the story. Students are not expected to understand everything about these concepts immediately. Instead, these fundamental concepts will be revisited again and again throughout the book, allowing students to get a deeper and deeper understanding over time. Since their knowledge level changes as they work their way forward, revisiting important topics later allows them to gain a deeper understanding overall. 1 The ‘Early Bird’ pattern, in J. Bergin: ‘Fourteen Pedagogical Patterns for Teaching Computer Science’, Proceedings of the Fifth European Conference on Pattern Languages of Programs (EuroPLop 2000), Irsee, Germany, July 2000.
  • 21. 17 We have tried this approach with students many times. It seems that students have fewer problems dealing with it than some long time teachers. And remember: a steep learning curve is not a problem as long as you ensure that your students can climb it! No complete language coverage Related to our iterative approach is the decision not to try to provide complete coverage of the Java language within the book. The main focus of this book is to convey object-oriented programming principles in general, not Java language details in particular. Students studying with this book may be working as software professionals for the next 30 or 40 years of their life – it is a fairly safe bet that the majority of their work will not be in Java. Every serious textbook must of course attempt to prepare them for something more fundamental than the language flavor of the day. On the other hand, many Java details are important for actually doing the practical work. In this book, we cover Java constructs in as much detail as is necessary to illustrate the concepts at hand and implement the practical work. Some constructs specific to Java have been deliberately left out of the discussion. We are aware that some instructors will choose to cover some topics that we do not discuss in detail. That is expected and necessary. However, instead of trying to cover every possible topic ourselves (and thus blowing the size of this book out to 1500 pages), we deal with it using hooks. Hooks are pointers, often in the form of questions that raise the topic and give references to an appendix or outside material. These hooks ensure that a relevant topic is brought up at an appropriate time, and leaves it up to the reader or the teacher to decide to what level of detail that topic should be covered. Thus, hooks serve as a reminder of the existence of the topic and a placeholder indicating a point in the sequence where discussion can be inserted. Individual teachers can decide to use the book as it is, following our suggested sequence, or to branch out into sidetracks suggested by the hooks in the text. Each chapter also includes several questions suggesting discussion material related to the topic, but not discussed in this book. We fully expect teachers to discuss some of these questions in class, or students to research the answers as homework exercises. Project-driven approach The introduction of material in the book is project driven. The book discusses numerous programming projects and provides many exercises. Instead of introducing a new construct and then providing an exercise to apply this construct to solve a task, we first provide a goal and a problem. Analyzing the problem at hand determines what kinds of solutions we need. As a consequence, language constructs are introduced as they are needed to solve the problems before us. Almost all chapters provide at least two discussion examples. These are projects that are discussed in detail to illustrate the important concepts of each chapter. Using two very different examples supports the iterative approach: each concept is revisited in a different context after it is introduced.
  • 22. 18 In designing this book, we have tried to use a large number and wide variety of different example projects. This will hopefully serve to capture the reader's interest, but it also helps to illustrate the variety of different contexts in which the concepts can be applied. Finding good example projects is hard. We hope that our projects serve to give teachers good starting points and many ideas for a wide variety of interesting assignments. The implementation for all our projects is written very carefully, so that many peripheral issues may be studied by reading the projects’ source code. We are strong believers in the benefit of learning by reading and imitating good examples. For this to work, however, one must make sure that the examples students read are well written and worth imitating. We have tried to do this. All projects are designed as open-ended problems. While one or more versions of each problem are discussed in detail in the book, the projects are designed so that further extensions and improvements can be done as student projects. Complete source code for all projects is included. A list of projects discussed in this book is provided on page 11. Concept sequence rather than language constructs One other aspect that distinguishes this book from many others is that it is structured along fundamental software development tasks and not necessarily according to the particular Java language constructs. One indicator of this is the chapter headings. In this book, you will not find many of the traditional chapters titles, such as ‘Primitive data types’ or ‘Control structures’. Structuring by fundamental development tasks allows us to give a much more general introduction that is not driven by intricacies of the particular programming language utilized. We also believe that it is easier for students to follow the motivation of the introduction, and that it makes it much more interesting. As a result of this approach, it is less straightforward to use the book as a reference book. Introductory textbooks and reference books have different, partly competing, goals. To a certain extent, a book can try to be both, but compromises have to be made at certain points. Our book is clearly designed as a textbook, and wherever a conflict occurred, the textbook style took precedence over its use as a reference book. We have, however, provided support for use as a reference book by listing the Java constructs introduced in each chapter in the table of contents and the chapter introduction. We also provide a separate Java language construct index at the back of the book. Chapter sequence Chapter 1 deals with the most fundamental concepts of object-orientation: objects, classes and methods. It gives a solid, hands-on introduction to these concepts without going into the details of Java syntax. It also gives a first look at some source code. We do this by using an example of graphical shapes which can be interactively drawn, and a second example of a simple laboratory class enrolment system.
  • 23. 19 Chapter 2 opens up class definitions and investigates how Java source code is written to create behavior of objects. We discuss how to define fields and implement methods. Here, we also introduce the first types of statements. The main example is an implementation of a ticket machine. We also look back to the laboratory class example from chapter 1 to investigate that a bit further. Chapter 3 then enlarges the picture to discuss interaction of multiple objects. We see how objects can collaborate by invoking each other’s methods to perform a common task. We also discuss how one object can create other objects. A digital alarm clock display is discussed that uses two number display objects to show hours and minutes. As a second major example, we examine a simulation of an email system in which messages can be sent between mail clients. In Chapter 4, we continue by building more extensive structures of objects. Most importantly, we start using collections of objects. We implement an electronic notebook and an auction system to introduce collections. At the same time, we discuss iterations over collection and have a first look at loops. The first collection being used is an ArrayList. In the second half of the chapter we introduce arrays as a special form of a collection, and the for loop as another form of a loop. We discuss an implementation of a web log analyzer as an example for array use. Chapter 5 deals with libraries and interfaces. We introduce the Java standard library and discuss some important library classes. More importantly, we explain how to read and understand the library documentation. The importance of writing documentation in software development projects is discussed, and we end by practicing how to write suitable documentation for our own classes. Random, Set and Map are examples of classes that we encounter in this chapter. We implement an Eliza-like dialogue system and a graphical simulation of a bouncing ball to apply these classes. Chapter 6, titled Well-behaved objects, deals with a whole group of issues connected to producing correct, understandable, and maintainable classes. It covers issues ranging from writing clear, understandable code – including style and commenting – to testing and debugging. Test strategies are introduced and a number of debugging methods are discussed in detail. We use an example of a diary for appointment scheduling and an implementation of an electronic calculator to discuss these topics. In Chapter 7, we discuss more formally the issues of dividing a problem domain into classes for implementation. We introduce issues of designing classes well, including concepts such as responsibility-driven design, coupling, cohesion, and refactoring. An interactive, text-based, adventure game (World of Zuul) is used for this discussion. We go through several iterations of improving the internal class structure of the game and extending its functionality, and end with a long list of proposals for extensions that may be done as student projects. Chapters 8 and 9 introduce inheritance and polymorphism with many of the related detailed issues. We discuss a simple database of CDs and videos to illustrate the concepts. Issues of code inheritance, subtyping, polymorphic method calls and overriding are discussed in detail.
  • 24. 20 In Chapter 10 we implement a predator/prey simulation. This serves to discuss additional abstraction mechanisms based on inheritance, namely interfaces and abstract classes. Chapter 11 then picks up the difficult issue of how to deal with errors. Several possible problems and solutions are discussed, and Java’s exception handling mechanism is discussed in detail. We extend and improve an address book application to illustrate the concepts. Chapter 12 steps back to discuss in more detail the next level of abstraction: how to structure a vaguely described problem into classes and methods. In previous chapters we have assumed that large parts of the application structure already exist, and we have made improvements. Now it is time to discuss how we can get started from a clean slate. This involves detailed discussion of what the classes should be that implement our application, how they interact, and how responsibilities should be distributed. We use class-responsibilities-collaborators (CRC) cards to approach this problem, while designing a cinema booking system. In Chapter 13, we try to bring everything together and integrate many topics from the previous chapters of the book. It is a complete case study, starting with the application design, through design of the class interfaces, down to discussing many important functional and non-functional characteristics and implementation details. Topics discussed in earlier chapters (such as reliability, data structures, class design, testing, extendibility, etc.) are applied again in a new context. Discussion group The authors maintain an active email discussion group for the purpose of facilitating exchange of ideas and mutual support for and by readers of this book and other BlueJ users. Postings to this list are archived and publicly accessible. Using this list, teachers can receive support and ideas from other teachers and the authors of this book. The mail address for this list is bluej-discuss@bluej.org. Interested people can join the list or browse the archives at http://lists.bluej.org/mailman/listinfo/bluej-discuss Additional material This book includes all projects used as discussion examples and exercises on a CD. The CD also includes the Java development environment (JDK) and BlueJ for various operating systems. There is a support web site for this book at http://www.bluej.org/objects-first On this web site, updates to the examples can be found, and additional material is provided. For instance, the style guide used for all examples in this book is available on the web site in electronic form, so that instructors can modify it to meet their own requirements.
  • 25. 21 The web site also includes a password protected, teacher-only section that provides additional material, such as solutions to exercises. A set of slides to teach a course with this book is also provided.
  • 26. 22 Part I: Foundations of object orientation
  • 27. 23 Chapter 1 Objects and classes Main concepts discussed in this chapter: • objects • classes • methods • parameters This chapter is the start of our journey into the world of object-oriented programming. Here we introduce the most important concepts you will learn about: objects and classes. At the end of the chapter, you should have an understanding of what objects and classes are, what they are used for, and how to interact with them. This chapter forms the basis of all other explorations in the book. 1.1 Objects and classes [concept box: objects] If you write a computer program in an object-oriented language, you are creating, in your computer, a model of some part of the world. The parts that the model is built up from are the objects that appear in the problem domain. These objects must be represented in the computer model being created. Objects may be categorized and a class describes, in an abstract way, all objects of a particular kind. We can make these abstract notions clearer by looking at an example. Assume you want to model a traffic simulation. One kind of entity you then have to deal with is cars. What is a car in our context: is it a class or an object? A few questions may help us to make a decision. What color is a car? How fast can it go? Where is it right now? [concept box: classes] You will notice that we cannot answer these questions until we talk about one specific car. The reason is that the word “car” in this context refers to the class car – we are talking about cars in general, not about one particular car. If I say, “My old car that is parked at home in my garage,” we can answer the questions above. That car is red, it doesn’t go very fast, and it is in my garage. Now I am talking about an object – about one particular example of a car. We usually refer to a particular object as an instance. We will use the term “instance” quite regularly from now on. Instance is roughly synonymous with object – we refer to objects as instances when we want to emphasize that they are of a particular class (such as, “this object is an instance of class car”).
  • 28. 24 Before we continue this rather theoretical discussion, let us look at an example. 1.2 Creating objects Start BlueJ and open the example named shapes.2 You should see a window similar to that shown in Figure 1. Figure 1: The shapes project in BlueJ In this window, a diagram should become visible. Every one of the colored rectangles in the diagram represents a class in our project. In this project we have classes named Circle, Square, Triangle and Canvas. Right-click on the Circle class and choose new Circle() from the popup menu. The system asks you for a “name of the instance” – click Ok, the default name supplied is good enough for now. You will see a red rectangle towards the bottom of the screen labeled “circle_1” (Figure 2). 2 We regularly expect you to undertake some activities and exercises while reading this book. At this point we assume that you already know how to start BlueJ and open the example projects. If not, read [Appendix A] first.
  • 29. 25 Figure 2: An object on the object bench You have just created your first object! “Circle”, the rectangular icon in Figure 1, represents the class Circle, “circle_1” is an object created from this class. The area at the bottom of the screen where the object is shown is called the object bench. Convention: We start names of classes with capital letters (such as Circle) and names of objects with lowercase letters (such as circle_1). This helps to distinguish what we are talking about. Exercise: 1-1 Create another circle. Then create a square. 1.3 Calling methods Right-click on one of the circle objects (not the class!) and you will see a popup menu with several operations. Choose makeVisible from the menu – this will draw a representation of this circle in a separate window (Figure 3). Figure 3: A drawing of a circle You will notice several other operations in the circle’s menu. Try invoking moveRight and moveDown a few times to move the circle closer to the center of the screen. You may also like to try makeInvisible and makeVisible to hide and show the circle.
  • 30. 26 Exercise: 1-2 What happens if you call moveDown twice? Or three times? What happens if you call makeInvisible twice? [concept box: methods] The entries in the circle’s menu represent operations that you can use to manipulate the circle. These are called methods in Java. Using common terminology, we say that these methods are called or invoked. We will use this proper terminology from now on. We might ask you to “invoke the moveRight method of circle_1”. 1.4 Parameters [concept box: parameters] Now invoke the moveHorizontal method. You will see a dialog appear that prompts you for some input (Figure 4). Type in 50 and click Ok. You will see the circle move 50 pixels to the right.3 Figure 4: A method call dialog The moveHorizontal method that was just called is written in such a way that it requires some more information to execute. In this case, the information required is the distance – how far the circle should be moved. Thus, the moveHorizontal method is more flexible than the moveRight or moveLeft methods. The latter always move the circle a fixed distance, whereas moveHorizontal lets you specify how far you want to move the circle. Exercise: 1-3 Try invoking the moveVertical, slowMoveVertical and changeSize methods before you read on. Find out how you can use moveHorizon- tal to move the circle 70 pixels to the left. The additional values that some methods require are called parameters. A method indicates what kinds of parameters it requires. When calling, for example, the moveHorizontal method as shown in Figure 4, the dialog displays the line void moveHorizontal(int distance) 3 A pixel is a single dot on your screen. Your whole screen it made up of a grid of single pixels.
  • 31. 27 near the top. This is called the signature of the method. [concept box: signature] The signature provides some information about the method in question. The part between the parenthesis (int distance) is the information about the required parameter. For each parameter, it defines a type and a name. The signature above states that the method requires one parameter of type int named distance. The name gives a hint about the meaning of the data expected. 1.5 Data types A type specifies what kind of data can be passed to a parameter. [concept box: types] The type “int” signifies whole numbers (also called “integer” numbers, therefore the abbreviation “int”). In the example above, the signature of the moveHorizontal method states that, before the method can execute, we need to supply a whole number specifying the distance to move. The data entry field shown in Figure 4 then lets you enter that number. In the examples so far, the only data type we have seen is int. The parameters of the move methods and the changeSize method are all of that type. Closer inspection of the object’s popup menu shows that the method entries in the menu include the parameter types. If a method has no parameter, the method name is followed by an empty set of parentheses. If it has a parameter, the type of that parameter is displayed. In the list of methods for a circle, you will see one method with a different parameter type: the changeColor method has a parameter of type String. The String type indicates that a section of text (for example a word or a sentence) is expected. Strings are always enclosed within double quotes. For example, to enter the word red as a string, type "red" The method call dialog also includes a section of text called a comment above the method signature. Comments are included to provide information to the (human) reader and are described in [Chapter 2]. The comment of the changeColor method describes what color names the system knows about. Exercise: 1-4 Invoke the changeColor method on one of your circle objects and enter the String “red”. This should change the color of the circle. Try other colors. 1-5 This is a very simple example, and not many colors are supported. See what happens when you specify a color that is not known. 1-6 Invoke the changeColor method, and write the color into the parameter field without the quotes. What happens?
  • 32. 28 Pitfall: A common error for beginners is to forget the double quotes when typing in a data value of type String. If you type green instead of “green”, you will get an error message saying something like “Error: undefined variable” (or something similar). Java supports several other data types including, for example, decimal numbers and characters. We will not discuss all of them right now, but rather come back to this issue later. If you want to find out about them now, look at [Appendix B]. 1.6 Multiple instances Exercise: 1-7 Create several circle objects on the object bench. You can do so by selecting new Circle() from the popup menu of the Circle class. Make them visible, then move them around on the screen using the “move” methods. Make one big and yellow, make another one small and green. Try the other shapes too: create a few triangles and squares. Change their positions, sizes and colors. [concept box: multiple instances] Once you have a class, you can create as many objects (or instances) of that class as you like. From the class Circle, you can create many circles. From Square, you can create many squares. Every one of those objects has its own position, color and size. You change an attribute of an object (such as its size) by calling a method on that object. This will affect this particular object, but not others. You may also notice an additional detail about parameters. Have a look at the changeSize method of the triangle. Its signature is void changeSize(int newHeight, int newWidth) Here is an example of a method with more than one parameter. This method has two, and a comma separates them in the signature. Methods can, in fact, have any number of parameters. 1.7 State [concept box: state] The set of values of all attributes defining an object (such as x- position, y-position, color, diameter and visibility status for a circle) is also referred to as the object’s state. This is another example of common terminology that we will use from now on. In BlueJ, the state of an object can be inspected by selecting the Inspect function from the object’s popup menu. When an object is inspected, a window similar to that shown in Figure 5 is displayed. This window is called the object inspector. Exercise:
  • 33. 29 1-8 Make sure you have several objects on the object bench and then inspect each of them in turn. Try changing the state of an object (for example by calling the moveLeft method) while the object inspector is open. You should see the values in the object inspector change. Some methods, when called, change the state of an object. For example, moveLeft changes the xPosition attribute. Java refers to these object attributes as fields. Figure 5: An object inspection dialog 1.8 What is in an object? On inspecting different objects you will notice that objects of the same class all have the same fields. That is, the number, type and names of the fields are the same, while the actual value of a particular field in each object may be different. In contrast, objects of a different class may have different fields. A circle, for example, has a field “diameter”, while a triangle has fields for “width” and “height”. The reason is that the number, types, and names of fields are defined in a class, not in an object. So the class Circle defines that each circle object will have five fields, named diameter, xPosition, yPosition, color and isVisible. It also defines the types for these fields. That is, it specifies that the first three are of type int, while the color is of type String and the isVisible flag is of type boolean. (Boolean is a type that can represent two values: true and false. We will discuss it in more detail later.) When an object of class Circle is created, the object will automatically have these fields. The values of these fields are stored in the object. That ensures that each circle has a color, for instance, and each can have a different color (Figure 6).
  • 34. 30 Figure 6: A class and its objects with fields and values The story is similar for methods. Methods are defined in the class of the object. As a result, all objects of a given class have the same methods. However, the methods are invoked on objects. This makes it clear which object to change when, for example, a moveRight method is invoked. Exercise: 1-9 Use the shapes from the shapes project to create an image of a house and a sun, similar to that shown in Figure 7. While you are doing this, write down what you have to do to achieve this. Could it be done in different ways?
  • 35. 31 Figure 7: An image created from a set of shape objects 1.9 Object interaction For the next section, we will work with a different example project. Close the shapes project if you still have it open, and open the project called picture. Exercises: 1-10 Open the picture project. Create an instance of class Picture and invoke its draw method. Also, try out the setBlackAndWhite and setColor methods. 1-11 How do you think the Picture class draws the picture? Four of the classes in the project are identical to the classes in the shapes project. But we now have an additional class: Picture. This class is programmed to do exactly what we have done by hand in exercise 1-9. In reality, if we want a sequence of tasks done in Java, we would not normally do it by hand as in exercise 1-9. Instead, we create a class that does it for us. This is the Picture class. The Picture class is written in a way that, when you create an instance, that instance creates two square objects (one for the wall, one for the window), a triangle and a circle, moves them around, changes their color and size, until it looks like the picture we see in Figure 7. [concept box: method-calling] The important point here is: objects can create other objects and they can call each other’s methods. In a normal Java program you may well have hundreds or thousands of objects. The user of a program just starts the program (which typically creates a first object), and all other objects are created – directly or indirectly – by that object.
  • 36. 32 The big question now is: how do you write the class for such an object? 1.10 Source code [concept box: source code] Each class has some source code associated with it. The source code is text that defines the details of the class. In BlueJ, the source code of a class can be viewed by selecting the Open Editor function from the class’s popup menu, or by double-clicking the class icon. Exercise: 1-12 Look at the popup menu of class Picture again. You will see an option labeled Open Editor. Select it. This will open a text editor displaying the source code of the class. The source code is text written in the Java programming language. It defines what fields and methods a class has, and precisely what happens when a method is invoked. In the next chapter we will discuss exactly what the source code of a class contains and how it is structured. A large part of learning the art of programming is learning how to write these class definitions. To do this, we will learn to use the Java language (although there are many other programming languages that could be used to write code). When you make a change to the source code and close the editor,4 the icon for that class appears striped in the diagram. The stripes indicate that the source has been changed. The class now needs to be compiled by clicking the Compile button. (You may like to read the “About compilation” sidebar for more information about what is happening when you compile a class.) Once a class has been compiled, objects can be created again and you can try out your change. Exercises: 1-13 In the source code of class Picture, find the part that actually draws the picture. Change it so that the sun will be blue rather than yellow. 1-14 Add a second sun to the picture. To do this, pay attention to the field definitions close to the top of the class. You will find this code: 4 In BlueJ, there is no need to save the text in the editor explicitly before closing. If you close the editor, the source code will automatically be saved. About compilation When people write computer programs, they typically use a “higher level” programming language, such as Java. A problem with that is that a computer cannot execute Java source code directly. Java was designed to be reasonably easy to read for humans, not for computers. Computers, internally, work with a binary representation of a machine code, which looks quite different from Java. The problem for us is: it looks so complex that we do not want to write it directly. We prefer to write Java. What can we do about this? The solution is a program called the compiler. The compiler translates the Java code into machine code. We can write Java, run the compiler – which generates the machine code – and the computer can then read the machine code. As a result, every time we change the source code we must first run the compiler before we can use the class again to create an object. Otherwise the machine code version that the computer needs does not exist.
  • 37. 33 private Square wall; private Square window; private Triangle roof; private Circle sun; You need to add a line here for the second sun, For example: private Circle sun2; Then write the appropriate code for creating the second sun. 1-15 Challenge exercise: (This means that this exercise might not be solved quickly. We do not expect everyone to be able to solve this at the moment. If you do – great. If you don’t, then don’t worry. Things will become clearer as you read on. Come back to this exercise later.) Add a sunset to the single-sun version of Picture. That is: make the sun go down slowly. Remember: The circle has a method slowMoveVertical that you can use to do this. 1-16 Challenge exercise: If you added your sunset to the end of the draw method (so that the sun goes down automatically when the picture is drawn), change this now. We now want the sunset in a separate method, so that we can call draw and see the picture with the sun up, and then call sunset (a separate method!) to make the sun go down. 1.11 Another example In this chapter, we have already discussed a large number of new concepts. To help in understanding these concepts, we will now revisit them in a different context. For this, we use a different example. Close the picture project if you still have it open, and open the lab-classes project. This project is a simplified part of a student database designed to keep track of students in laboratory classes and to print class lists. Exercise: 1-17 Create an object of class Student. You will notice that this time you are not only prompted for a name of the instance, but also for some other parameters. Fill them in before clicking Ok. (Remember that parameters of type String must be written in double-quotes.) 1.12 Return values As before, you can create multiple objects. And again, as before, the objects have methods which you can call from their popup menu. Exercise:
  • 38. 34 1-18 Create some student objects. Call the getName method on each object. Explain what is happening. When calling the getName method of the Student class, we notice something new: methods may return a result value. [concept box: results] In fact, the signature of each method tells us whether or not it returns a result, and what the type of the result is. The signature of getName (as shown in the object’s popup menu) is defined as: String getName() The word String before the method name specifies the return type. In this case it states that calling this method will return a result of type String. The signature of changeName states: void changeName(String) The word void indicates that this method does not return any result. Methods with return values enable us to get information from an object via a method call. This means that we can use methods either to change an object’s state or to find out about its state. 1.13 Objects as parameters Exercises: 1-19 Create an object of class LabClass. As the signature indicates, you need to specify the maximum number of students in that class (an integer). 1-20 Call the numberOfStudents method of that class. What does it do? 1-21 Look at the signature of the enrolStudent method. You will notice that the type of the expected parameter is Student. Make sure you have two or three students and a LabClass object on the object bench, then call the enrolStudent method of the LabClass object. With the input cursor in the dialog entry field, click on one of the student objects – this enters the name of the student object into the parameter field of the enrolStudent method (Figure 8). Click Ok, and you have added the student to the LabClass. Add one or more other students as well. 1-22 Call the printList method of the LabClass object. You will see a list of all the students in that class printed to the BlueJ terminal window (Figure 9).
  • 39. 35 Figure 8: Adding a student to a tutorial Figure 9: Output of the LabClass project’s class listing As the exercises show, objects can be passed as parameters to methods of other objects. In the case where a method expects an object as a parameter, the expected object’s class name is specified as the parameter type in the method signature. Explore this project a bit more. Try to identify the concepts discussed in the shapes example in this context. Exercises: 1-23 Create three students with the following details: Snow White, student ID: 100234, credits: 24 Lisa Simpson, student ID: 122044, credits: 56 Charlie Brown, student ID: 12003P, credits: 6 Then enter all three into a lab and print a list to the screen. 1-24 Use the inspector on a LabClass object to discover what fields it has. 1-25 Set the instructor, room, and time for a lab and print the list to the terminal window to check that these new details appear.
  • 40. 36 1.14 Summary In this chapter, we have explored the basics of classes and objects. We have discussed the fact that objects are specified by classes. Classes represent the general concept of a thing, while objects represent concrete instances of a class. We can have many objects of any class. Objects have methods which we use to communicate with them. We can use a method to make a change to the object or to get information from the object. Methods can have parameters, and parameters have types. Methods have return types, which specify what type of data they return. If the return type is void, they do not return anything. Objects store data in fields (which also have types). All the data values of an object together are referred to as the object’s state. Objects are created from class definitions that have been written in a particular programming language. Much of programming in Java is about learning to write class definitions. A large Java program will have many classes, each with many methods which call each other in many different ways. To learn to develop Java programs, we need to learn how to write class definitions, including fields and methods, and how to put these classes together well. The rest of this book deals with these issues. Terms introduced in this chapter object, class, instance, method, signature, parameter, type, state, source code, return value, compiler. Concept summary • Java objects model objects from a problem domain. [objects] • Objects are created from classes. The class describes the kind of object; the objects represent individual instantiations of the class. [classes] • We can communicate with objects by invoking methods on them. Objects usually do something if we invoke a method. [methods] • Methods can have parameters to provide additional information for a task. [parameters] • The header of a method is called its signature. It provides information needed to invoke that method. [signatures] • Parameters have types. The type defines what kinds of values a parameter can take. [types] • Many similar objects can be created from a single class. [multiple instances] • Objects have state. The state is represented by storing values in fields. [state] • Objects can communicate by calling each other’s methods. [method-calling] • The source code of a class determines the structure and the behavior (the fields and methods) of each of the objects in that class. [source code] • Methods may return information about an object via a return value. [results] Exercise:
  • 41. 37 1-26 In this chapter, we have mentioned the data types int and String. Java has more predefined data types. Find out what they are and what they are used for. To do this, you can check [Appendix B], look it up in another Java book or in an online Java language manual. One such manual is at http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
  • 42. 38 Chapter 2 Understanding class definitions Main concepts discussed in this chapter: • fields • constructors • methods (accessor, mutator) • parameters • assignment and conditional statement Java constructs discussed in this chapter: field, constructor, comment, parameter, assignment (=), block, return statement, void, compound assignment operators (+=, -=), if In this chapter, we take our first proper look at the source code of a class. We will discuss the basic elements of class definitions: fields, constructors, and methods. Methods contain statements and initially we look at methods containing only simple arithmetic and printing statements. Later we introduce conditional statements that allow choices between different actions to be made within methods. We will start by examining a new project in a fair amount of detail. This project represents a naïve implementation of an automated ticket machine. As we start by introducing the most basic features of classes, we will quickly find that this implementation is deficient in a number of ways. So we will then proceed to describe a more sophisticated version of the ticket machine that represents a significant improvement. Finally, in order to reinforce the concepts introduced in this chapter, we take a look at the internals of the lab-classes example encountered in [Chapter 1]. 2.1 Ticket machines Train stations often provide ticket machines that print a ticket when a customer inserts the correct money for their fare. In this chapter, we will define a class that models something like these ticket machines. As we will be looking inside our first Java example classes, we will keep our simulation fairly simple to start with. That will give us the opportunity to ask some questions about how these models differ from the real world versions, and how we might change our classes to make the objects they create more like the real thing. Our ticket machines work by customers ‘inserting’ money into them, and then requesting a ticket to be printed. A machine keeps a running total of the amount of money it has collected throughout its operation. In real life, it is often the case that a ticket machine offers a selection of different types of ticket from which customers choose the one they want. Our simplified machines only print tickets of a single price.
  • 43. 39 It turns out to be significantly more complicated to program a class to be able to issue tickets of different values than it does to have a single price. On the other hand, with object-oriented programming it is very easy to create multiple instances of the class, each with its own price setting, to fulfill a need for different types of ticket. 2.1.1 Exploring the behavior of a naïve ticket machine Open the naive-ticket-machine project in BlueJ. This project contains only one class – TicketMachine – that you will be able to explore in a similar way to the examples we discussed in [Chapter 1]. When you create a TicketMachine instance, you will be asked to supply a number that corresponds to the price of tickets that will be issued by that particular machine. The price is taken to be a number of cents, so a positive whole number such as 500 would be appropriate as a value to work with. Exercises: 2-1 Create a TicketMachine object on the object bench and take a look at its methods. You should see the following: getBalance, getPrice, insertMoney, and printTicket. Try out the getPrice method. You should see a return value containing the price of the tickets that was set when this object was created. Use the insertMoney method to simulate inserting an amount of money into the machine and then use getBalance to check that the machine has a record of the amount inserted. You can insert several separate amounts of money into the machine, just like you might insert multiple coins or notes into a real machine. Try inserting the exact amount required for a ticket. As this is a simple machine, a ticket will not be issued automatically, so once you have inserted enough money, call the printTicket method. A facsimile ticket should be printed in the BlueJ terminal window. 2-2 What value is returned if you check the machine’s balance after it has printed a ticket? 2-3 Experiment with inserting different amounts of money before printing tickets. Do you notice anything strange about the machine’s behavior? What happens if you insert too much money into the machine – do you receive any refund? What happens if you do not insert enough and then try to print a ticket? 2-4 Try to obtain a good understanding of a ticket machine’s behavior by interacting with it on the object bench before we start looking at how the TicketMachine class is implemented in the next section. 2-5 Create another ticket machine for tickets of a different price. Buy a ticket from that machine. Does the printed ticket look different? 2.2 Examining a class definition Examination of the behavior of TicketMachine objects within BlueJ reveals that they only really behave in the way we might expect them to if we insert exactly the correct
  • 44. 40 amount of money to match the price of a ticket. As we explore the internal details of the class in this section, we will begin to see why this is so. Take a look at the source code of the TicketMachine class by double-clicking its icon in the class diagram. It should look something like Figure 10. Figure 10: The BlueJ editor window The complete text of the class is shown in Figure 11. By looking at the text of the class definition piece by piece we can flesh out some of the object-oriented concepts that we talked about in [Chapter 1]. /** * TicketMachine models a naive ticket machine that issues * flat-fare tickets. * The price of a ticket is specified via the constructor. * It is a naive machine in the sense that it trusts its users * to insert enough money before trying to print a ticket. * It also assumes that users enter sensible amounts. * * @author David J. Barnes and Michael Kölling * @version 2002.02.06 */ public class TicketMachine { // The price of a ticket from this machine. private int price; // The amount of money entered by a customer so far. private int balance; // The total amount of money collected by this machine.
  • 45. 41 private int total; /** * Create a machine that issues tickets of the given price. * Note that the price must be greater than zero, and there * are no checks to ensure this. */ public TicketMachine(int ticketCost) { price = ticketCost; balance = 0; total = 0; } /** * Return the price of a ticket. */ public int getPrice() { return price; } /** * Return the amount of money already inserted for the * next ticket. */ public int getBalance() { return balance; } /** * Receive an amount of money in cents from a customer. */ public void insertMoney(int amount) { balance += amount; } /** * Print a ticket. * Update the total collected and * reduce the balance to zero. */ public void printTicket() { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); // Update the total collected with the balance. total += balance; // Clear the balance. balance = 0; } } Figure 11: The TicketMachine class
  • 46. 42 2.3 Fields, constructors, and methods The source of most classes can be broken down into two main parts: a small outer wrapping that simply names the class, and a much larger inner part that does all the work. In this case, the outer wrapping appears as follows: public class TicketMachine { Inner part of the class omitted. } The outer wrappings of different classes all look pretty much the same; their main purpose is to provide a name for the class. Exercise: 2-6 Write out what you think the outer layers of the Student and LabClass classes might look like – do not worry about the inner part. The inner part of the class is where we define the fields, constructors, and methods that give the objects of that class their own particular characteristics and behavior. We can summarize the essential features of those three components of a class as follows: • The fields store data for each object to use. • The constructors allow each object to be set up properly when it is first created. • The methods implement the behavior of the objects. In Java, there are very few rules about the order in which you choose to define the fields, constructors, and methods within a class. In the TicketMachine class, we have chosen to list the fields first, the constructors second, and finally the methods (Figure 12). This is the order that we will follow in all of our examples. Other authors choose to adopt different styles, and this is mostly a question of preference. Our style is not necessarily better than all others. However, it is important to choose one style and then to use it consistently because then your classes will be easier to read and understand. public class ClassName { Fields Constructors Methods } Figure 12: Our ordering of fields, constructors and methods Exercises: 2-7 From your earlier experimentation with the ticket machine objects within BlueJ, you can probably remember the names of some of the methods – printTicket, for instance. Look at the class definition in
  • 47. 43 Figure 11 and use this knowledge, along with the additional information about ordering we have given you, to try to make a list of the names of the fields, constructors and methods in the TicketMachine class. Hint: There is only one constructor in the class. 2-8 Do you notice any features of the constructor that make it significantly different from the other methods of the class? 2.3.2 Fields [concept box: fields] The TicketMachine class has three fields: price, balance, and total. Fields are also known as instance variables. We have defined these right at the start of the class definition (Figure 13). All of the fields are associated with monetary items that a ticket machine object has to deal with: • The price field stores the fixed price of a ticket. • The balance field stores the amount of money inserted into the machine by a user prior to asking for a ticket to be printed. • The total field stores a record of the total amount of money inserted into the machine by all users since the machine object was constructed. public class TicketMachine { private int price; private int balance; private int total; Constructor and methods omitted. } Figure 13: The fields of the TicketMachine class Fields are small amounts of space inside an object which can be used to store values. Every object, once created, will have some space for every field declared in its class. Figure 14 shows a diagrammatic representation of a ticket machine object with its three fields. The fields have not yet been assigned any values – once they have, we can write each value into the box representing the field. The notation is similar to that used in BlueJ to show objects on the object bench, except that we show a bit more detail here. In BlueJ, for space reasons, the fields are not displayed on the object icon. We can, however, see them by opening an inspector window.
  • 48. 44 Figure 14: An object of class TicketMachine Each field has its own declaration in the source code. On the line above each, in the full class definition, we have added a single line of text – a comment – for the benefit of human readers of the class definition: // The price of a ticket from this machine. private int price; [concept box: comments] A single-line comment is introduced by the two characters, ‘//’, which are written with no spaces between them. More detailed comments, often spanning several lines, are usually written in the form of multi-line comment. These start with the character pair, ‘/*’ and end with the pair ‘*/’. There is a good example preceding the header of the class in Figure 11. The definitions of the three fields are quite similar. • All definitions indicate that they are private fields of the object – we will have more to say about what this means in [Chapter 5], but for the time being we will simply say that we always define fields to be private. • All three fields are of type int. This indicates that each can store a single whole number value, which is reasonable given that we wish them to store numbers that represent amounts of money in cents. Because fields can store values which can vary over time, they are also known as variables. The value stored in a field can be changed if we wish to. For instance, as more money is inserted into a ticket machine we will want to change the value stored in the balance field. In the following sections, we will also meet other kinds of variables in addition to fields. The price, balance, and total fields are all the data items that a ticket machine object needs to fulfill its role of receiving money from a customer, printing tickets, and keeping a running total of all the money that has been put into it. In the following sections, we will see how the constructor and methods use those fields to implement the behavior of naïve ticket machines. 2.3.3 Constructors [concept box: constructors] The constructors of a class have a special role to fulfill – it is their responsibility to put each object of that class into a fit state to be used once it has been created. This is also called initialization. The constructor initializes the
  • 49. 45 object to a reasonable state. Figure 15 shows the constructor of the TicketMachine class. One of the distinguishing features of constructors is that they have the same name as the class in which they are defined – TicketMachine in this case. public class TicketMachine { Fields omitted. /** * Create a machine that issues tickets of the given price. * Note that the price must be greater than zero, and there * are no checks to ensure this. */ public TicketMachine(int ticketCost) { price = ticketCost; balance = 0; total = 0; } Methods omitted. } Figure 15: The constructor of the TicketMachine class The fields of the object are initialized in the constructor. Some fields, such as balance and total can be set to sensible initial values by assigning a constant number, zero in this case. With others, such as the ticket price, it is not that simple since we do not know the price that tickets from a particular machine will have until that machine is constructed – recall that we might wish to create multiple machine objects to sell tickets with different prices, so no one initial price will always be right. You will recall from experimenting with creating TicketMachine objects within BlueJ that you had to supply the cost of the tickets whenever you created a new ticket machine. An important point to note here is that the price of a ticket is initially determined outside of the ticket machine, and then has to be passed into a ticket machine object. Within BlueJ, you decide the value and enter it into a dialogue box. One task of the constructor is to receive that value and store it into the price field of the newly created ticket machine so that the machine can remember what that value was without you having to keep reminding it. We can see from this that one of the most important roles of a field is to remember information, so that it is available to an object throughout that object’s lifetime. Figure 16 shows a ticket machine object after the constructor has executed. Values have now been assigned to the fields. From this diagram, we can tell that the ticket machine was created by passing in 500 as the value for the ticket cost. In the next section, we discuss how values are received by an object from outside.
  • 50. 46 Figure 16: A TicketMachine object after initialization (created for 500 cent tickets) Note: In Java, all fields are automatically initialized to a default value if they are not explicitly initialized. For integer fields, this default value is 0. So, strictly speaking, we could have done without setting balance and total to 0, relying on the default value to give us the same result. However, we prefer to write the explicit assignments anyway. There is no disadvantage to it, and it serves well to document what is actually happening. We do not rely on a reader of the class knowing what the default value is, and we document that we really want this value to be zero, and have not just forgotten to initialize it. 2.4 Passing data via parameters The way in which both constructors and methods receive values is via their parameters. You may recall that we briefly encountered parameters in [Chapter 1]. Parameters are defined in the header of the constructor or method: public TicketMachine(int ticketCost) This constructor has a single parameter, ticketCost, which is of type int – the same type as the price field it will be used to set. Figure 17 illustrates how values are passed via parameters. In this case, a BlueJ user enters a value into the dialogue box when creating a new ticket machine (shown on the left), and that value is then copied into the ticketCost parameter of the new machine’s constructor. This is illustrated with the arrow labeled (A). The additional box in the ticket machine object in Figure 17, labeled “TicketMachine (constructor)” is additional space for the object that is created only when the constructor executes. We will call it the constructor space of the object (or method space when we talk about methods instead of constructors, since the situation there is the same). The constructor space is used to provide space to store the values for the constructor’s parameters (and other variables that we will come across later).
  • 51. 47 Figure 17: Parameter passing (A) and assignment (B) We distinguish between parameter names inside a constructor or method, and parameter values outside by referring to the names as formal parameters and the values as actual parameters. So ticketCost is a formal parameter, and a user- supplied value, such as 500, is an actual parameter. Because they are able to store values, formal parameters are another sort of variable. In our diagrams, all variables are represented by white boxes. [concept box: scope] A formal parameter is only available to an object within the body of a constructor or method that declares it. We say that the scope of a parameter is restricted to the body of the constructor or method in which it is declared. In contrast, the scope of a field is the whole of the class definition – it can be accessed from anywhere in the same class. [concept box: lifetime] A concept related to variable scope is variable lifetime. The lifetime of a parameter is limited to a single call of a constructor or method. Once that call has completed its task, the formal parameters disappear and the values they held are lost. In other words, when the constructor has finished executing, the whole constructor space (see Figure 17) is removed, along with the parameter variables held within it. In contrast, the lifetime of a field is the same as the lifetime of the object to which it belongs. It follows that if we want to remember the cost of tickets held in the ticket- Cost parameter, we must store the value somewhere more persistent – that is, in the price field. 2.5 Assignment In the previous section, we noted the need to store the short-lived value of a parameter into somewhere more permanent – a field. In order to do this, the body of the constructor contains the following assignment statement: price = ticketCost; Assignment statements are recognized by the presence of an assignment operator, such as ‘=’ in the example above. Assignment statements work by taking the value of
  • 52. 48 what appears on the right-hand side of the operator and copying that value into a variable on the left-hand side. This is illustrated in Figure 17 by the arrow labeled (B). [concept box: assignment] The right-hand side is called an expression: expressions are things that compute values. In this case, the expression just consists of a single variable but we will see some examples of more complicated expressions containing arithmetic operations later in this chapter. One rule about assignment statements is that the type of the expression must match the type of the variable to which it is assigned. So far we have met three different types: int, String, and (very briefly) boolean. This rule means that we are not allowed to store an integer-type expression into a string-type variable, for instance. This same rule also applies between formal parameters and actual parameters; the type of an actual-parameter expression must match the type of the formal-parameter variable. For now, we can say that the types of both must be the same, although we will see in later chapters that this is not the whole truth. 2.6 Accessor methods The TicketMachine class has four methods: getPrice, getBalance, insertMoney, and printTicket. We will start our look at the source code of methods by considering getPrice (Figure 18). public class TicketMachine { Fields omitted. Constructor omitted. /** * Return the price of a ticket. */ public int getPrice() { return price; } Remaining methods omitted. } Figure 18: The getPrice method [concept box: methods] Methods have two parts: a header and a body. Here is the method header for getPrice: /** * Return the price of a ticket. */ public int getPrice() The first three lines are a comment describing what the method does. The fourth line is also known as the method signature. It is important to distinguish between method signatures and field declarations, because they can look quite similar. We can tell that getPrice is a method and not a field because it is followed by a pair of parentheses: '(' and ')'. Note, too, that there is no semicolon at the end of the signature.
  • 53. 49 The method body is the remainder of the method after the header. It is always enclosed by a matching pair of curly brackets: '{' and '}'. Method bodies contain the declarations and statements that define what happens inside an object when that method is called. In our example above the method body contains a single statement, but we will see examples very soon where the method body consists of many lines of both declarations and statements. Any set of declarations and statements between a pair of matching curly brackets is known as a block. So the body of the TicketMachine class and the bodies of all the methods within the class are blocks. There are at least two significant differences between the signatures of the TicketMachine constructor and the getPrice method: public TicketMachine(int ticketCost) public int getPrice() • The method has a return type of int but the constructor has no return type. A return type is written just before the method name. • The constructor has a single formal parameter, ticketCost, but the method has none – just a pair of empty parentheses. It is an absolute rule in Java that a constructor may not have a return type. On the other hand, both constructors and methods may have any number of formal parameters, including none. Within the body of getPrice there is a single statement: return price; This is a return statement. It is responsible for returning an integer value to match the int return type in the method’s signature. Where a method contains a return statement, it is always the final statement of that method, because no further statements in the method will be executed once the return statement is executed. The int return type of getPrice is a form of promise that the body of the method will do something that ultimately results in an integer value being calculated and returned as the method’s result. You might like to think of a method call as being a form of question to an object, and the return value from the method being the object’s answer to that question. In this case, when the getPrice method is called on a ticket machine, the question is, “What do tickets cost?” A ticket machine does not need to perform any calculations to be able to answer that, because it keeps the answer in its price field. So the method answers by just returning the value of that variable. As we gradually develop more complex classes, we will inevitably encounter more complex questions that require more work to supply their answers. [concept box: accessor methods] We often describe methods such as the two get methods of TicketMachine (getPrice and getBalance) as accessor methods (or just accessors). This is because they return information to the caller about the state of an object – they provide access to that state. An accessor usually contains a return
  • 54. 50 statement in order to pass back that information as a particular value, but this is not exclusively the case. A method that prints information about an object’s state may also be classified as an accessor. Exercises: 2-9 Compare the getBalance method with the getPrice method. What are the differences between them? 2-10 If a call to getPrice can be characterized as, “What do tickets cost?” how would you characterize a call to getBalance? 2-11 If the name of getBalance is changed to getAmount, does the return statement in the body of the method need to be changed, too? Try it out within BlueJ. 2-12 Define an accessor method, getTotal, that returns the value of the total field. 2-13 Try removing the return statement from the body of getPrice. What error message do you see now when you try compiling the class? 2-14 Compare the method signatures of getPrice and printTicket in Figure 11. Apart from their names, what is the main difference between them? 2-15 Do the insertMoney and printTicket methods have return statements? Why do you think this might be? Do you notice anything about their headers that might suggest why they do not require return statements? 2.7 Mutator methods The get methods of a ticket machine perform similar tasks – returning the value of one of their object’s fields. The remaining methods – insertMoney and printTicket – have a much more significant role; primarily because they change the value of one or more fields of a ticket machine object each time they are called. We call methods that change the state of their object, mutator methods (or just mutators.) [concept box: mutator methods] In the same way as we think of accessors as requests for information (questions), we can think of mutators as requests for an object to change its state. One distinguishing effect of a mutator is that an object will often exhibit slightly different behavior before and after it is called. We can illustrate this with the following exercise. Exercise: 2-16 Create a ticket machine with a ticket price of your choosing. Before doing anything else, call the getBalance method on it. Now call the
  • 55. Exploring the Variety of Random Documents with Different Content
  • 56. It was Harry Tynan—a tall, handsome lad with dark hair inclined to curl, and big brown eyes; the type of boy who from childhood is petted and spoilt by mothers and aunts. Unless such an one possesses an exceptionally strong character the result is fatal, and Tynan showed a weak mouth and chin. “The Padre’s” owner caught the whisper. “More fool you, you young idiot!” Markham genially observed, as the silly youngster turned away with a muttered curse. Miss Woodburn’s congratulations were even more welcome than the praises of his comrades. “I’m proud of my future brother,” she said. “You rode just splendidly. Oh, it was exciting! I gave up all hope at the last water- jump.... And then when you began to overhaul him down the incline! Didn’t the shouting affect your nerves?” Ted shook his head. “I don’t remember hearing anything. For all I knew there might not have been a single person within miles except me and Spencer—I mean Spencer and I—Spencer and myself, I should say.” “I could hardly hold myself in,” went on Ethel. “I was dancing up and down—screaming, I’m afraid.” “You were indeed, madame,” interposed Jim. “You were making a most discreditable exhibition.” “Ted,” exclaimed the girl, “will you marry me? I’m tired of your brother.” “That I will!” replied Ted. “To-morrow if you like. I never could imagine what you could see in that chap, you know.” “Very well, I’ll abandon him to his fate. He was actually cheering on that Guide fellow during the last hundred yards.” “The brute!”
  • 57. “Isn’t he?” “Who—the Guide fellow?” With this embarrassing query Lieutenant Spencer joined the party. Ethel blushed crimson, and for once in her life was at a loss for a remark. Jim chuckled away to himself at his sweetheart’s discomfiture in most brutal fashion. “That’s right, Spencer,” said he. “Come and back me up, I’m in a minority here.” Miss Woodburn recovered from her confusion. She had already been introduced by Jim to “that Guide fellow”. “I really beg your pardon, Lieutenant Spencer. We were indulging in a little inter-regimental chaff and abuse. Captain Russell had dared to applaud you rather than his brother at the final burst. And you don’t understand how fond we all are of ‘The Padre’. He’s the regimental horse.” “Please don’t apologize,” Miss Woodburn. “I quite understand and sympathize with you. Indeed, I’m glad you’re scorching him, for he needs it. And so he was cheering me in preference to your favourite? He must have most execrable taste.” “Thank you, Spencer!” Jim hurriedly and joyfully broke in. “Thanks!... Be grateful, Ethel. Don’t you see how very complimentary to you that remark is?” For a few moments Miss Woodburn struggled with her amusement, but laughter mastered her, and she could not speak before Spencer had partially recovered his senses and recognized what a left-handed compliment he had paid her. The Guides lieutenant was far more confused and nervous now than at any time during the steeple-chase. With crimson face he offered reparation.
  • 58. “It’s my turn to apologize now, Miss Woodburn. I think you’ll forgive me, though. It’s my misfortune that I’m not very intelligent.” “I couldn’t dream of doing so, Lieutenant Spencer,” Ethel asserted, still laughing. “You paid me out nicely, and I’m sure you did it wilfully; it was far too smart to be unintentional.” “’Pon my honour, I didn’t. I’m not half sharp enough to say anything of that kind except by accident. One can’t be perfect, you know, and we must take into account that Russell did show poor taste in applauding the inferior horse and rider—especially going against your opinion, though we must acknowledge his perfect taste in at least one respect.” “I must forgive you after that, Mr. Spencer, though it was rather crude,” said the girl, shaking her head. “And I say, Spencer,” Jim interposed, “don’t talk about ‘inferior rider’. We all know, and Ted knows, that you are a far better horseman than he.” “Of course I do,” the ensign heartily agreed. “Too much praise isn’t good for a youngster,” the elder brother sagaciously opined. Spencer placed a hand on Ted’s shoulder. “All the same, young ’un, you won the Aurungpore Cup, and you deserved to win.” The party of four came to a halt opposite Colonel Woodburn’s bungalow. “What time shall we start back for Murdan to-morrow?” asked the lieutenant. “We must leave early,” Jim replied. “Will eight o’clock suit?”
  • 59. “Very good,” Spencer assented; “the young ’un and I will leave you here.” “But you must not think of leaving us yet, Mr. Spencer. Won’t you come in? My father would be delighted to know you.” “Couldn’t dream of it, Miss Woodburn, delighted though I should be to make the colonel’s acquaintance. It will be some time before Russell gets leave again, and your last evening shall be sacred. Good-bye, Miss Woodburn! I’m very glad to have met you. And may I congratulate you both? I’ve known Russell well for some years, and I can congratulate you, and—forgive me for saying it—I’ve known you for a couple of days, and I do most sincerely congratulate him.” Ethel pressed the “horrid Guide man’s” hand, and when he and Ted had departed, observed: “Whilst congratulations are passing round, Jim, I congratulate you on your friend.” Ted shared a small, one-story residence just outside the town with his chum Ensign Paterson. His bedroom was only just large enough to allow sleeping-room for Jim, but hearing that Captain Russell’s comrade of the Guides was coming to Aurungpore, Paterson had placed his equally limited accommodation at Spencer’s disposal. Arrived at home, Ted doffed the pigskin and discussed horses and riding with his guest until the time came for them to sally forth once more. A dinner was to be given by the officers of the 193rd in honour of the triumph of their regiment. For the third time in succession they had won the Aurungpore Cup, and Ted was the hero of the hour. He enjoyed the rôle until, his health having been drunk with acclamation, he was called upon for a speech. Such an ordeal had never been contemplated, and he had to be dragged to his feet, a victim of nervous funk. As he faced his quizzing comrades his mind was a blank; he stammered a few incoherent sentences intended for thanks, and abruptly sat down again, feeling convinced that he had qualified for a place in any
  • 60. home for the feeble-minded. Yet the older officers liked him better for this lack of self-confidence than had he shown no sign of confusion. In reply to the toast, “Our Guests”, Lieutenant Spencer made a neat and witty speech that set everyone at his ease. The ordeal over, Spencer, Paterson, and Ted returned to the little bungalow, and settled down to await Jim’s arrival. Lieutenant Spencer filled his pipe and lay back in the one chair that the apartment boasted, Paterson sat straddle-legged across a camp- stool, and Ted squatted on a box with his back to the wall and his legs dangling. The room was lighted by a candle stuck in a bottle, for were they not in the “Gorgeous East” where luxury and splendour reign supreme? “So you fellows of the 193rd are proud of your regiment!” the Guides’ officer observed. “It’s a first-class corps,” Ted replied. “They fought like good ’uns throughout both Sikh wars. You see, we’ve Bhurtpore as well as Sobraon, Moodkee, and Gujerat on the colours; and the colonel says he’d lead ’em anywhere—they’d follow their officers to the death. Markham’s the favourite with the men, though they’re very fond of the ‘old man’ and Major Munro.” “Yours is a queer corps, is it not, Lieutenant Spencer?” Paterson asked. Spencer chuckled. “It is! But I’m proud of being in the Guides.” “They say,” continued the Scotch boy, “that you have all the frontier races in the corps—Afridis, Afghans, and other Pathan tribes, Sikhs and Gurkhas—and that some of them have been robbers and outlaws, and murderers even. Is that true?” Spencer chuckled still more.
  • 61. “Quite true. We have all sorts—men with the best of characters, men with the worst, and men with no characters at all. We’ve outlaws and dacoits, thieves and murderers—though they don’t call themselves murderers; they resemble the border raiders of Scotland of some hundreds of years ago. But every man who joins the Guides has to be strong, healthy, active, brave as a lion, able to track like a Red Indian, climb mountains, and think for himself. Lumsden gets hold of the most daring men on the border, such as Dilawur Khan and Futteh Khan and Bahram Khan, and makes Guides of them. They don’t get coddled; and I guess we shall have more work to do in the future than any regiment in India. We’ve men of all races and creeds and men of no race or creed—mostly big truculent Pathans, and nearly a hundred jolly little Gurkhas sent us by the King of Nepal at Sir Henry Lawrence’s request. Oh, it’s a grand corps! and we can get as many men as we like—scores apply for every vacancy. Why, there are dozens of fellows learning the drill at their own expense, both cavalry and infantry, waiting for an opportunity to join us. There’s no other regiment in India or England can say the same.” “Well, I’d rather serve in the 193rd B.N.I.,” Ted declared. “I shouldn’t care to trust your Guides very far. Why, many of your Sikhs must have fought against us eight years ago; and as for the Afridis and Yusufzais, they’re always raiding British territory and killing our men, whilst the sepoys of the 193rd have fought under British colours for half a century.” “That’s right, young ’un; stick up for your regiment.” “Jim was going to tell me,” Ted remarked, “something about that Pathan officer who was speaking to you this morning. Who is he?” “Bahram Khan, do you mean?” “Yes, that’s the man. We noticed the natives shrinking from him when he looked at them. Why was that?” The lieutenant lay back in his chair and smiled.
  • 62. “His is a queer story and typical of the Guides,” he replied. “A few years ago he was a well-known outlaw and brigand chief, who raided and burnt villages and robbed right and left. We could never catch him, so Lumsden, our colonel, offered to make him an officer if he’d join the Guides, and he consented and brought his brigands with him.” Paterson regarded the speaker curiously. “Is that a fact?” he asked. “It is an absolute fact.” “We’d keep that sort of ruffian out of the 193rd, wouldn’t we, Paterson?” Ted asserted. “Aren’t you afraid that you’ll wake up some morning with all your throats cut?” “Not in the least. I’d rather be with the Guides than any corps. With all respect to your sepoys of the 193rd, they’ve neither the stamina nor the resource of our fellows.” “H’m! you’re welcome to them. Eh, Paterson?” “I agree with you, Ted. Have you ever seen Colonel Nicholson, Lieutenant Spencer?” “Jan Nikkulseyn? Rather. I sha’n’t forget the first time I met him. It was south of Peshawur, close to the border, where a gang of Afghan labourers were making a road, protected by a half-company of sepoys under an English subaltern, for it was in a wild district. It was just after the rains, and a bullock-cart had stuck fast in the deep mud; and the bullocks, not having the grit of a horse, wouldn’t make any efforts. I happened to be riding past with a couple of troopers. A big fellow standing by in civilian dress had taken his coat off and put his shoulder to the wheel, but they couldn’t move it. This civilian, whom I took to be the man in charge of the work, then asked the lieutenant and the sepoys to lend a hand. But the sepoys coolly informed him that they had enlisted to fight, not to do menial work, and the officer said:
  • 63. “‘It’s no business of mine. I’m here to protect the road-makers, not to do their work.’ “I dismounted, and so did one of my two men. The other, Hafiz Khan, bent down and whispered: “‘I go to get help, Lieutenant Sahib’; and before I could stop him he was galloping away. Well, we two turned the scale—though the big civilian was worth us both—and at last we got the cart out and trotted away. A mile or two farther on we saw Hafiz Khan waiting for us, and when I slanged him for not staying to help us, he replied: “‘But he once threatened to hang me, Lieutenant Sahib, and Jan Nikkulseyn never breaks his word’. “‘Who?’ I asked, quite taken aback. “‘Jan Nikkulseyn. I am not afraid of a little pushing and pulling, but of Jan Nikkulseyn are we all afraid.’ “The civilian was Colonel Nicholson. Hafiz Khan had been engaged in two or three raids before he had enlisted, and, bold as they are, there’s not a Pathan along the border dare look Nicholson between the eyes.” “And what became of the lieutenant?” asked Ted. “He applied for an important appointment at Peshawur a month later. He found out his mistake then, and felt sorry he’d ever been born.” A clatter of hoofs interrupted their talk, and Ted ran to the outer door to admit his brother. Captain Russell was quiet and grave, for his happy days had come to an end, and to-morrow the dull routine of regimental work would begin again. He was evidently little inclined for conversation, and before long the four officers passed off into the adjoining bedrooms.
  • 64. Captain Russell was well liked by about one-half of his acquaintances, and disliked by a good proportion of the remainder. His friends knew him for a brave, good-hearted, conscientious man, and his detractors termed him a prig. The fault was in his manner, at times heavy, awkward, and solemn, largely the result of shyness, for with intimate friends he could be lively and full of fun. Serious thoughts occupied his mind as he undressed. Ought not he, the elder brother and man of experience, to give the youngster a few words of advice, before leaving him, on some subjects more serious than steeple-chasing? But how to begin? Jim Russell knew his own failings, and dreaded lest Ted should sneer at him as a prig; and he envied his chum, Spencer, who, he felt sure, could have given the lad sound advice and warning without the least suspicion of preaching. However, Jim was conscientious, and he resolved to take the risk. The ensign’s evident esprit de corps and delight in his regiment furnished an admirable opening, and sitting on the low bed half- undressed, the elder brother spoke like a father to the younger concerning his duty to the regiment. Then, as the captain was an enthusiastic admirer of the great brothers Henry and John Lawrence, and of their band of devoted followers, the first topic naturally led to a eulogy of the Punjab leaders; and Jim explained to the ensign how Henry Lawrence had begun, and how John Lawrence was now carrying on the work of showing to the wild Sikhs, Jats, and Mohammedans of the Punjab the highest ideal of British justice and uprightness. Ted listened attentively, but said nothing. He too was already filled with admiration for those Christian soldiers and statesmen who were soon to save India. “Not that I want you to be an objectionable young prig,” the captain went on; “there’s a big difference between that and the genuine article. You know what I mean?”
  • 65. The ensign nodded, and Jim continued: “I like your chum—Paterson; he seems a very decent lad. And I noticed on one occasion that he showed he was not ashamed of his religion. Why should we so-called Christians be so afraid of acting up to what we profess to believe? Look at the Lawrences and Herbert Edwardes, three of the greatest men in India! They are true Christians, and where could you find finer soldiers and braver men? It’s a poor soldier who’s ashamed of his colours.” Ted nodded assent, and, feeling that he had done his duty, Jim bade him good-night and blew out the candle. An early breakfast next morning, and our ensign and his two visitors were in the saddle by seven o’clock. Ten minutes later Ethel Woodburn cantered up, attended by a sais, and Spencer and Ted ambled along, keeping well ahead of the lovers. “I suppose that’s the fort over there?” Spencer asked, and pointed to an ugly square building of dark sandstone that dominated the town. “Yes, it’s an arsenal too. There’d be a big smash in Aurungpore if it was to blow up,” said Ted, who little thought of the influence that forbidding fortress would exert upon his career. “It has half-ruined the town already by its ugliness,” Spencer mused. “That mosque on the left is a little gem, and that dome is perfect, but the arsenal spoils them as completely as a factory chimney spoils a view at home. The Moslems beat us at architecture.” “I think I must be turning back now,” Ted presently observed, “I have plenty to do before parade.” They came to a halt and awaited the arrival of the others. The lovers parted, Ted shook hands with Jim and Spencer, and nodded in response to his brother’s parting injunction to take care of Ethel. Miss Woodburn stayed, waving her handkerchief, until a bend of the
  • 66. road hid her betrothed from view. Joining Ted, she touched her bay lightly with the whip, and they trotted home without exchanging a word.
  • 67. CHAPTER IV The Fanatics In spite of our hero’s recent disgust he had quickly become reconciled to the sweet girl who was to be his brother’s wife. There was no resisting her charms. He found her as full of fun and as fond of adventure as any boy could wish, and he soon grew very anxious to win her good opinion, even attempting to show off occasionally for her benefit. Ethel had become no less attached to the honest, healthy-minded, plucky lad, and wrote warningly to Jim that she had fallen desperately in love with his jolly young brother. A few weeks had elapsed since Captain Russell’s departure, when something happened to attach them still more closely. One beautiful winter day Ethel asked the ensign if he would care to stroll through the native bazar with her, and the lad willingly complied. Not being of a very curious disposition, he had hitherto neglected this quarter of the town, and had spent most of his leisure time riding and shooting in the country beyond. But on this occasion the girl was able to make the visit much more interesting than he had anticipated. She knew the people and more than one of the many dialects fairly well, and she pointed out to her companion the men of various nationalities and religions who swarmed in the narrow streets. He noticed with amazement the difference between the strong fighting men of the North-west—the sturdy Jat and stalwart Pathan—and the fat, mild, shrinking Babu from Bengal, or the slender and weaker Hindu from the South. This part of the town was quite distinct from the quarter in which the Europeans lived, and was much more picturesque, if also more
  • 68. dirty. In the narrow streets all the goods of the small shops were exposed to the passer-by. Workmen could be seen plying their trade, undisturbed by the inquisitive glances of the lookers-on. And what clumsy tools they had! It would have been impossible for such delicate, exquisite work to have been turned out therewith, had not the artisans put their whole soul into the labour: for to do his work thoroughly and beautifully is a religious duty with the Hindu. Passing the stalls of the money-changers, fruit-sellers, and dealers in native sweetmeats, their attention was attracted by certain curios in one of the queer shops, and our ensign looked about for something worth sending home. He fixed upon a queer silver bangle, set with turquoises. The setting was uncommon, but the stones were only poor. The turbaned, white-robed shopkeeper rose and came forward at once, salaaming profoundly, and putting on one side the hubble-bubble he was smoking. After a lengthy argument, in which Ted failed to understand the man’s rapid utterance, and his own Hindustani was beyond comprehension, Miss Woodburn came to the rescue, fixed the price, and concluded the business. Attracted by the sahib’s curious rendering of their native tongue, a number of the many idlers around had drawn near. At a corner of the narrow street, not fifty paces distant, voices had been meanwhile raised in earnest and violent harangue. Having learned even during his short sojourn in the land how furious an altercation may arise over a matter of a couple of annas, Ted had not paid much attention to the noise; but now the speakers rose and came towards them. Foremost was a tall, half-naked man, with long and flowing beard—a mass of dirt and evil smells; for with these strange people cleanliness is not on speaking terms with godliness, and the most holy men are the most filthy. His eyes were inflamed, and his looks and gestures wild. Ethel, from her longer experience, saw that the mullah had rendered himself mad with bhang, and that two of his companions were in a similar condition. Pointing to the Feringhis, the mullah’s voice rose to a wild shriek.
  • 69. “What do these offspring of the evil one here? O followers of the Prophet, how long will ye allow yourselves to be denied by these kafirs. The time is even now at hand when Allah shall no longer permit this: then shall his wrath fall upon them, and they shall be swept from the face of the earth. The hundred years of the white man’s raj[1] are fulfilled, and the curse shall be lifted from us!” [1] dominion. The fanatic’s voice rose to a wild shriek as he concluded the harangue. Ted could not follow the speech: he could only gather from the tone and gestures that he and his companion were the objects of abuse, and he guessed from the half-angry, half-cringing manner of the tradesman that something serious was being said. Ethel, however, understood every word, and was alarmed. They tried to leave the bazar, but found their progress barred. “Out of the way, there!” the ensign commanded, but no one moved. “Kill the kafir pigs!—there is no one to see!” called out a voice from the rear. “No, no!” objected others hastily. “What harm have they done? And will not the vengeance of the Whites be upon us all? Make way there for the sahib-log!” But another of the bhang-drugged fanatics, who had been swaying to and fro in his delirium, screamed: “Aye! Why not kill now?” and he roughly seized the white-faced girl. With a savage exclamation the English boy sprang forward and struck the speaker behind the ear with all his force. Not for nothing had Edward Russell been trained in gymnastics, in boxing and fencing—the fellow dropped like a log. But before Ted could turn or
  • 70. draw his sword the mullah had plucked a knife from beneath his scanty garment and plunged it in the lad’s side. “Die, unbeliever!” he cried. As the ensign pressed his hands to his side and dropped to the earth with a feeble moan, the screaming and jabbering of the by- standers ceased as if by magic. Even the mullah and his disciples drew back appalled at what they had done, while the more timid of the crowd fled to their homes in dread of the consequences and the sure wrath of the sahibs, fearing lest vengeance should fall on innocent and guilty alike for this murder of a white man. The merchants before whose shops the act had been committed wrung their hands in despair, shrieking imprecations down upon the heads of the fanatics, who stood gazing at their handiwork. The mullah’s hesitation lasted but a second. He turned towards the trembling girl, and called to his abettors: “Finish off the lad while I slay the woman!” Ethel Woodburn was a soldier’s daughter: she had more than once looked danger in the face bravely and calmly. Had she been alone she might have hesitated, or had her companion been in a condition to protect her she might have relied on him. But, seeing the boy of whom she was so fond stretched at her feet, cruelly wounded and helpless, and at the mercy of these madmen, her instinct prompted her to do the right thing without a moment’s hesitation, and she blessed the father who had taught her to carry and use a pistol. The little weapon was hardly more than a toy, but it checked the assassins sufficiently to enable her to bend down swiftly and snatch Ted’s sword from its scabbard. The murderer was but a pace away when she pulled the trigger and stepped back. He fell, writhing, the bullet in his chest. The second received the point of the sword under his arm-pit as he raised his hand to strike. The third assailant, dazed by the blow from Ted’s fist, had now risen, and was hesitating as to
  • 71. his next step, when a couple of native police, attracted by the report and noise, ran up, and, being Sikhs, they had no hesitation in securing the uninjured Mohammedan, and they also prevented the crowd from carrying off the wounded Wahabis.[1] [1] The most fanatical and implacable Moslem sect. Never losing her presence of mind, Ethel bound the unconscious lad’s wound to stop the bleeding, and ordered the by-standers to carry him to his quarters, where the regimental surgeon attended to the injury. The bangle had disappeared. A few weeks later, when the injured persons had recovered, the three would-be assassins were tried on the charge of attempted murder, and were sentenced to long terms of imprisonment. Some time elapsed before Ted was able to get about as usual. Had it not been for the bandage so promptly applied by Ethel he must have bled to death, so she had saved his life in two different ways. During his slow and painful recovery he was nursed untiringly by his new sister; and though she made light of her heroic deed, the girl’s courage and presence of mind were the chief themes of conversation with the officers who frequently visited his bed-side, and the ensign’s lucky brother became more envied than ever. Ethel invariably checked his expressions of gratitude, and would not allow him to talk about the incident. “Bosh, Ted!” she would say; “I was in such a state of abject fear that I didn’t know what I was doing. I only shot the man because my hand trembled so that the trigger went off, and he happened to be in front.” “Certainly, Ethel, I quite understand. I’ll just read you a letter I had this morning from Jim. You’d p’r’aps like to hear his opinion?” “Oh, that boy’s demented! I had a note also from him this morning. He’s quite wild.”
  • 72. “Good chap Jim,—knows a thing or two!” said Ted, nodding his head sagely.
  • 73. CHAPTER V The Cad of the Regiment “This is the place where I was knifed, Paterson,” said Ted, “and there’s the old boy I had been bargaining with. Watch him eyeing me; he looks rather scared, don’t he?” The wound was now quite healed, and impelled doubtless by a magnetic attraction, akin perhaps to that said to be exercised on murderers by the scenes of their crimes, our ensign had induced his chum Paterson to stroll with him through the bazar one evening after duty was over for the day. While Ted had been down with his wound Alec Paterson had opened out in a remarkable manner and thrown down the last barriers of reserve. Ensign Paterson had only recently admitted Ted into close friendship. He was a Scottish lad, hailing from Lanarkshire, and no better choice of a friend could have been made. Physically he was tall and well-formed, intellectually he was ahead of most of his brother ensigns, and in moral character strong, upright, and healthy. He was very reserved, difficult to know, chary of his intimacy, and slow of speech. Tynan termed him a “saint”, and cordially disliked him; and in return Paterson disproved the accusation of saintliness by being obnoxiously polite and somewhat ponderously playful in his dealings with the regimental bête noir. “He does look scared,” Alec replied. “He must think you were killed, and that your ghost has come to jump down his throat or ride on his back, or whatever it is that their evil spirits do. You had better speak and reassure him.”
  • 74. As Ted approached the stall, the hand of the sleek Hindu shot forth across the boards on which his wares were displayed and snatched something from the front row. Not, however, before our hero had recognized the identical bangle that he had bought and paid for on the occasion of his previous visit. His face flushed. “That is mine,” he asserted. “I bought and paid for it.” Understanding that the bangle had been seen, and that denial was useless, the shopkeeper salaamed and unabashed replied: “Nay, sahib, the one you bought you took away, and I have never set eyes on it since.” “But you told me it was unique—that there was not another like it in the country.” “I am the sahib’s slave, and I spoke truth. There was not another like it in the Punjab. But since the Heaven-born’s visit a Kazilbash merchant from Kabul, with whom I deal in turquoises, has sold me this. It is indeed similar to the one I sold the sahib, but the turquoises are larger and better. Welcome is the sight of the Heaven- born in the eyes of his servant, who has suffered great anxiety.” “What’s the row, Ted?” Paterson asked. And matters being explained, he at once enquired of the Hindu why he had been so anxious to prevent the bangle being seen if he had come by it honestly. But the “Aryan brown” was more than their match in guile. “In truth I remembered how the former one had brought ill-luck to the young sahib, and I feared lest he might take a fancy to this one also. And I know that the sahibs are reckless in such matters, not believing in omens. Rather would I lose business than bring misfortune upon the head of the young sahib.” Alec Paterson laughed. “I’m afraid it’s no go, Russell,” he whispered. “The rascal is too deep for us, and we cannot prove that it really is the same article.”
  • 75. “But it’s robbery pure and simple!” Ted indignantly declared. “I know it’s the same that I lost during the scuffle.” The shopkeeper regarded them gravely and sadly, as though he felt deeply the doubts they had cast upon his honesty. He produced one article after another, tempting them in vain to buy. At length, guessing that the boy had set his heart upon the bangle, he offered him the pretty toy for thirty rupees, assuring him that he had given twice that sum to the Kazilbash. “I’ll give you fifteen,” said Ted, “and not an anna more.” The Hindu shook his head. “I am poor man,” said he, “else would I gladly beg the sahib to accept it as a present.” “Very well,” Ted firmly rejoined. “Come along, Alec.” They turned to go, but the Hindu hastily recalled them. “Nay,” said he, “I had forgotten that the sahib had to suffer the loss of the first one. For twenty rupees will I sell it, or, in truth, give it away, rather than that the Heaven-born should be disappointed.” “Fifteen,” was all Ted’s answer; and once more the bangle changed hands, and the ensign left the shop. On the way to cantonments they overtook Harry Tynan, the object of their mutual dislike, and were about to pass with a nod as devoid of cordiality as decency would permit, when Tynan spoke, or rather sneered: “Why, Russell, I thought you always took a girl to protect you whenever you went into the bazar!” “Did you really now?” asked Ted banteringly. “Wasn’t it an effort?” “What do you mean? Was what an effort?” “To think—so unusual, you know, for you.”
  • 76. “Oh how clever you are! But how aren’t you keeping an eye on Brother Jim’s future wife, according to instructions? I saw her this evening flirting as usual with the Commissioner Sahib. You are not doing your duty. Captain Russell ’ud be angry if he knew.” “Come along, Russell; what’s the use of talking to that cad?” whispered Paterson. “Contemptible toad!” But his friend’s ire had been aroused by the last remark. He halted and faced Tynan. “What d’you mean?” he demanded. Tynan slowly drew a huge cheerot from his lips and attempted to blow rings of smoke before replying. “You know well enough. Stunnin’ little flirt is Ethel—deuced stunnin’! Shouldn’t be surprised if she threw Brother Jim over!” “What do you mean?” repeated Ted with still greater heat. “Don’t be an ass, Ted. Leave the cad alone,” Paterson again whispered. Tynan was Russell’s senior by nearly a couple of years, and he stood a clear three inches taller. Ted’s anger amused him. “Why—don’t you know?” he innocently enquired. “You see, our little Ethel had been setting her cap at Sir Arthur Fletcher for months before she saw your brother. But Arthur knows what’s what, and the little darling has had to put up with a mere captain of the Guides. But she still hankers after the commissioner, and sighs for the handle to her name.” “Ye leein’ hyæna!” Paterson burst out, his native dialect rising to the surface in his excitement. “Keep a ceevil tongue in your heid, or I’ll knock ye down!” “No, you don’t, Paterson,” broke in Ted. “That’s my business. You cad, to lie like that about a girl you’re not fit to speak to! Take that!”
  • 77. Our ensign struck his comrade across the face—a resounding smack with the open palm. The fight was very short. Though tall enough, Tynan was weedy and unfit. For several years he had considered himself a man of the world, and one of the chief aims—if not the chief—of his life had been to convince his associates that he was well qualified for that dignified position, and the attainment of this object had, of course, necessitated abundant smoking and drinking. Wonderful to relate, no one had so far seemed greatly impressed! Five minutes after the first blow, with bleeding nose and damaged eye, the contemptible fellow was sullenly admitting that he had had enough. “Think it over the nicht,” Paterson suggested. “If ye hev not I’ll just gie ye seemilar satisfaction. And I’d hev ye obsairve it wad be safer to cam’ oot wi’ no mair lees o’ that sort. Cam’ awa’, Russell!” “Wait a moment, I’ve not done yet,” said Ted. “Let me inform you now, you cad, what I would not waste my breath in telling you before—that Miss Woodburn had refused Sir Arthur Fletcher before she became engaged to my brother, and that he has congratulated my brother, and is a loyal, honourable gentleman, of whose friendship Miss Woodburn is proud; and don’t let me hear you speaking of her again as you did just now.” The chums left the miserable being—neither man nor boy—to follow as he chose. “What garred ye say that last, Russell?” asked the Scottish lad, who was still labouring under strong excitement, as soon as they had passed out of hearing. “What? About Fletcher?” “Yea You’d no right to drag his refusal into the affair!” Paterson dropped the tell-tale accent as he spoke more slowly. “That’s between him and Miss Woodburn, and he wouldn’t thank you if he
  • 78. knew, nor would she. It was perhaps very satisfying to you, but they don’t need to be defended from a fellow like our friend yonder.” “I’m very sorry—I’m a fool! I was so angry I didn’t stop to think. Bah! he leaves a bad taste in the mouth, that fellow!” “We should have passed him without taking any notice,” Paterson went on. “But it served him right!” For the future Tynan gave his conqueror a wide berth, and Ted ignored his existence as far as their respective duties, would permit. Returning from the officers’ mess that evening, Ted was accosted by Pir Baksh, the Mohammedan captain. “I saw you fight with Ensign Tynan,” said he. “He is the kind of officer to ruin a regiment. Once he dared to call me a soor (pig) before my men, and I thank you, sahib, for teaching him a lesson.”
  • 79. CHAPTER VI The Outbreak of the Mutiny On the night of Monday, May 11, some weeks after Ted’s recovery, Ethel’s twenty-first birthday was celebrated, Colonel Woodburn entertaining the officers and British residents of Aurungpore. The season was too warm for more than occasional dancing, and conversation was the order of the night—conversation serious and frivolous, harmless flirtations between the younger members, and solemn interchange of views concerning the rumoured dissatisfaction prevailing amongst the native troops, a subject pooh-poohed by some and laughed at by others, but gravely regarded by a few—when an orderly entered and handed a missive to the colonel. As he opened it and read he gave a start, and his face paled for one brief second, but soon resumed its ordinary aspect as he slowly folded the paper and placed it in his pocket. A few moments later he crossed over to Major Munro, who at once left the room after speaking to the adjutant and another officer. These two also took their departure before long, and one by one the remainder of the officers were spoken to and retired to their mess- room, where they were shortly joined by Colonel Woodburn. “I have terrible news,” he informed them, “but we must try to avoid alarming either the ladies or the sepoys. The 3rd Native Cavalry and the 11th and 20th Native Infantry have broken into mutiny at Meerut, killed some of their officers, and, so the message runs, are sacking the town and murdering right and left.” “At Meerut!” gasped Major Munro. “How at Meerut of all places? They couldn’t—it’s simply impossible!”
  • 80. “It must be true,” declared the colonel, “though it certainly does seem impossible. One would think they would have broken out at Cawnpore, or Benares, or Allahabad, or here, or anywhere rather than Meerut. But this report must be exaggerated! How could they sack the town and murder in the face of those English regiments and the Artillery? It’s incomprehensible!” Now even Ensign Russell, a mere griffin, knew that Meerut—a large station more than fifty miles north-east of Delhi—was considered a model cantonment, and contained the strongest British force in all India. Could a revolt seem more hopeless than at this station, where the three native corps were more than counterbalanced by a regiment of British dragoons, the 60th Rifles, and two batteries of the finest artillery in the world—a force sufficient to repress any rising within ten minutes—whereas throughout the seven hundred and fifty miles of territory along the Ganges, in the districts containing the large towns of Agra, Allahabad, Benares, Cawnpore, Lucknow, and Patna, there were only three weak British corps to oppose nearly a score of sepoy regiments and many thousands of armed rebels? “There’s no saying how it will spread,” continued the colonel. “We must take all precautions, though I believe our men are perfectly trustworthy. There must be some mistake, and I’ve no doubt that we shall hear to-morrow that the rebels have been cut to pieces. I’m afraid the silly fellows will be slaughtered by hundreds.” But the news of the morning and of the succeeding days was no less hard to understand. Eighty-five men of the 3rd Native Cavalry (a corps composed of Hindus and Mohammedans) had refused to use the cartridges served out, alleging that the fat of pigs and of cows had been employed in the manufacture. As most readers will know, the pig is regarded as unclean by all Moslems, and the cow is holy to Hindus, so that to touch the fat of these animals would imperil their salvation and shut them out of Paradise. The mullahs and fakirs had been poisoning the minds of
  • 81. 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