Learn Objectoriented Java The Hard Way Graham Mitchell instant download
Learn Objectoriented Java The Hard Way Graham Mitchell instant download
Mitchell download
https://ebookbell.com/product/learn-objectoriented-java-the-hard-
way-graham-mitchell-48927976
https://ebookbell.com/product/the-java-workshop-learn-objectoriented-
programming-and-kickstart-your-career-in-software-development-david-
cuartielles-46712648
https://ebookbell.com/product/java-programming-for-beginners-improve-
your-software-engineering-skills-by-learning-to-code-using-an-
objectoriented-program-learn-about-the-virtual-machine-javascript-and-
machine-code-2022-vergil-silva-46408466
https://ebookbell.com/product/interactive-objectoriented-programming-
in-java-learn-and-test-your-programming-skills-2nd-edition-2nd-
edition-vaskaran-sarcar-50195476
https://ebookbell.com/product/interactive-object-oriented-programming-
in-java-learn-and-test-your-skills-1st-edition-vaskaran-sarcar-
auth-5696030
Interactive Objectoriented Programming In Java Learn And Test Your
Programming Skills Vaskaran Sarcar
https://ebookbell.com/product/interactive-objectoriented-programming-
in-java-learn-and-test-your-programming-skills-vaskaran-
sarcar-232010682
https://ebookbell.com/product/a-software-engineer-learns-java-and-
object-orientated-programming-cameron-43039484
https://ebookbell.com/product/a-software-engineer-learns-java-and-
object-orientated-programming-1st-dane-cameron-6769022
https://ebookbell.com/product/a-software-engineer-learns-java-and-
object-orientated-programming-dane-cameron-43187710
https://ebookbell.com/product/a-software-engineer-learns-java-and-
object-orientated-programming-cameron-22783254
Learn Object-Oriented Java the Hard Way
Graham Mitchell
This book is for sale at http://leanpub.com/javahard2
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
…and more!
In the final chapter you’ll write a graphical version of a popular checker-dropping game and be able
to package that up to send to others.
All the examples in this book will work in version 1.8 of Java or any newer version. If you omit the
last few chapters on JavaFX, most of the code will work in Java version 1.6 or later.
No basics
If you don’t already know how to create variables and write if statements, loops and functions
in Java, then you should learn that before trying to work through this book.
No Android
Android apps are pretty complex, and if you’re a beginner, an app is way beyond your ability.
Nothing in this book will hurt your chances of making an app, though, and the kinder, gentler
pace may keep you going when other books would frustrate you into quitting.
No specific version
I will not cover anything about the differences between Java SE 7 and Java SE 8, for example.
If you care about the difference, then this book is not for you.
Except for the last few graphics chapters, I will also not cover anything that was only recently
added to Java. This book is for learning the basics of object-oriented programming and nothing
has changed about the basics of Java in many years.
No Javascript
“Javascript” is the name of a programming language and “Java” is also the name of a
programming language. These two languages have nothing to do with each other. They are
completely unrelated.
¹https://learnjavathehardway.org/book/ex01.html
Introduction: Object-Oriented Java v
I hope to write more books after this one. My third book will cover making a simple Android app,
assuming you have finished working through the first two books.
License
Some chapters of this book are made available free to read online but you are not allowed to make
copies for others without permission.
The materials provided for download may not be copied, scanned, or duplicated, or posted to a
publicly accessible website, in whole or in part.
Educators who purchase this book and/or tutorial videos are given permission to utilize the
curriculum solely for self-study or for one-to-one, face-to-face tutoring of a single student. Large-
group teaching of this curriculum requires a site license.
Unless otherwise stated, all content is copyright 2015-2016 Graham Mitchell.
Exercise 0: The Setup
This exercise has no code but do not skip it. It will help you to get a decent text editor installed
and to install the Java Development Kit (JDK). If you do not do both of these things, you will not be
able to do any of the other exercises in the book. You should follow these instructions as exactly as
possible.
This exercise requires you to do things in a terminal window (also called a “shell”, “console”
or “command prompt”. If you have no experience with a terminal, then you might need to
go learn that first.
I’ll tell you all the commands to type, but if you’re interested in more detail you might
want to check out the first chapter of “Conquering the Command Line” by Mark Bates. His
book is designed for users of a “real” command line that you get on a Linux or Mac OS X
machine, but the commands will be similar if you are using PowerShell on Windows.
Read Mark’s book at conqueringthecommandline.com².
You are going to need to do three things no matter what kind of system you have:
(The JDK commands are automatically added to the PATH on Apple computers and on Linux
computers.)
I have instructions below for Windows, then for the Mac OS, and finally for Linux. Skip down to
the operating system you prefer.
²http://conqueringthecommandline.com/book/basics
Exercise 0: The Setup 2
Windows
javac -version
You will probably get an error in red text that says something like “The term ‘javac’ is not recognized
as the name of a cmdlet….”
This just means that the JDK isn’t installed and added to the PATH, which is what we expect at this
point.
If you are using a very old version of Windows, PowerShell might not be installed. You
can do all of the exercises in this book using “Command Prompt” (cmd.exe) instead, but
the navigation commands will be different and adding the JDK to the PATH will also be
different.
I recommend trying to get PowerShell installed if you can.
³http://notepad-plus-plus.org/
Exercise 0: The Setup 3
<<(code/set-environ-var-8u102.txt)
Then type or paste the folder location from above. If you installed the x86 (32-bit) version of JDK
version 8u102, it should be
C:\Program Files (x86)\Java\jdk1.8.0_102\bin
(Still don’t press ENTER.)
Then add ", "User") at the end. Finally, press ENTER.
If you get an error then you typed something incorrectly. You can press the up arrow to get it back
and the left and right arrows to find and fix your mistake, then press ENTER again.
Once the SetEnvironmentVariable command completes without giving you an error, close the
PowerShell window by typing exit at the prompt. If you don’t close the PowerShell window
the change you just made won’t take effect.
javac -version
java -version
In the following text, I will use the word “folder” and the word “directory” interchangably.
They mean the same thing. The word “directory” is much older, but ever since the 1980s
graphical operating systems have used a picture of a folder to represent a directory, so that
word is now used, too.
ls
Type ls then press ENTER. (That’s an “L” as in “list”.) This command will list the contents of the
current folder/directory.
cd Documents
The cd command means “change directory” and it will move you into the “Documents” folder so
that future commands will take effect there.
Notice that your prompt will change to show that you are now inside a new folder. For example,
when I first open PowerShell on my Windows 7 machine, my prompt is
PS C:\Users\Mitchell>
Then once I change into the “Documents” directory the prompt changes to
PS C:\Users\Mitchell\Documents>
You should type ls again once you get in there to see the contents of your Documents directory.
If you are using an older version of Windows, the folder might be called “My Documents”
instead of “Documents”. If so, you will need to put quotes around the folder name for the
cd command to work, since the name of the folder contains a space:
cd "My Documents"
mkdir javahard2
Exercise 0: The Setup 6
mkdir means “make directory” and will create a new folder in the current location. Typing ls
afterward should show you that the new directory is now there. You can call the folder something
different than “javahard2” if you want to. You will only need to create this folder once per computer.
cd javahard2
Change into the javahard2 folder. Afterward, type ls and it should list nothing. (The directory is
empty, after all.)
cd ..
This is how you use the cd command to back out one level. After you type it you will be back in
just the “Documents” directory, and your prompt should have changed to reflect that.
Issue the command to get back into the “javahard2” folder again.
Now, use the mouse to open the text editor you installed earlier. Type a sentence or something and
then save the file as test.txt. Save it into the “javahard2” folder you just created.
Go back to the terminal window and issue the ls command to see the file you just created.
If you’re feeling fancy, you won’t have to use the mouse to switch back to the terminal;
you can just press Alt + Tab on Windows or Linux or press Command + Tab on a Mac
to switch applications.
Press and hold the Alt key. Keep it pressed. Then press and release the Tab key a single
time. While still holding the Alt key, press Tab several more times until your terminal
window is selected, then let go of the Alt key to make the switch.
If you just quickly press Alt+Tab and let go of both keys right away, it usually takes
you back to the previous application. I do this a lot. When I’m in the text editor I press
Alt+Tab to get back to the terminal, then when I’m done in the terminal I press Alt+Tab
again to get back to my text editor. It’s very fast once you get used to it.
You should skip down to the bottom of this chapter and read the “Warnings for Beginners”, but
otherwise you’re done with the setup and you are ready to begin Exercise 01 on Windows! Nice job.
Exercise 0: The Setup 7
Mac OS X
I don’t own an Apple computer, so I don’t currently have a way to test these directions for
myself. I have tried to explain things, but there might be some small errors.
If you use these directions, I would appreciate any emails about things that worked or
didn’t work on your computer.
javac -version
You should probably get an error that tells you that “javac” is an unknown command. (Feel free to
email me a screenshot of the error message so I can update this paragraph.)
This just means that the JDK isn’t installed, which is what we expect at this point.
If you are using a very old version of Mac OS X, the javac command might not give you
an error! It might just print a version number on the screen!
As long as it is version 1.5 or higher, you can do all of the exercises in this book.
2. Click the big “Java” button on the left near the top to download the Java Platform (JDK) 8u102.
Clicking this will take you to a different page titled “Java SE Development Kit 8 Downloads.”
3. On this page you will have to accept the license agreement and then choose the “Mac OS
X x64” version in the middle of the list. Download the file for version 8u102 or any newer
version.
You do not need to download the “Demos and Samples”.
4. Once downloaded, run jdk-8u102-macosx-x64.dmg to install it.
5. Just keep clicking “Next” until everything is done. Unless you really know what you’re doing
it’s probably best to just let the installer do what it wants.
javac -version
java -version
However, if both commands worked and you didn’t get any errors and the version numbers did
match, then congratulations! Getting all that to work is pretty hard and you probably have what it
takes to finish the rest of the book!
Don’t move on to the next exercise yet, though! We should get used to navigating using the
command-line, since that’s how you will be running the programs you write in this book.
In the following text, I will use the word “folder” and the word “directory” interchangably.
They mean the same thing. The word “directory” is much older, but ever since the 1980s
graphical operating systems have used a picture of a folder to represent a directory, so that
word is now used, too.
ls
Type ls then press ENTER. (That’s an “L” as in “list”.) This command will list the contents of the
current folder/directory.
cd Documents
The cd command means “change directory” and it will move you into the “Documents” folder so
that future commands will take effect there.
Notice that your prompt will change to show that you are now inside a new folder. For example,
when I first open Terminal, my prompt is
localhost:∼ mitchell$
Then once I change into the “Documents” directory the prompt changes to
localhost:Documents mitchell$
You should type ls again once you get in there to see the contents of your Documents directory.
Now we are ready to create the folder.
mkdir javahard2
Exercise 0: The Setup 10
mkdir means “make directory” and will create a new folder in the current location. Typing ls
afterward should show you that the new directory is now there. You can call the folder something
different than “javahard2” if you want to. You will only need to create this folder once per computer.
cd javahard2
Change into the javahard2 folder. Afterward, type ls and it should list nothing. (The directory is
empty, after all.)
cd ..
This is how you use the cd command to back out one level. After you type it you will be back in
just the “Documents” directory, and your prompt should have changed to reflect that.
Issue the command to get back into the “javahard2” folder again.
Now, use the mouse to open the text editor you installed earlier. Type a sentence or something and
then save the file as test.txt. Save it into the “javahard2” folder you just created.
Go back to the terminal window and issue the ls command to see the file you just created.
If you’re feeling fancy, you won’t have to use the mouse to switch back to the terminal;
you can just press Command + Tab on a Mac or press Alt + Tab on Windows or Linux
to switch applications.
Press and hold the Command key. Keep it pressed. Then press and release the Tab key
a single time. While still holding the Command key, press Tab several more times until
your terminal window is selected, then let go of the Command key to make the switch.
If you just quickly press Command+Tab and let go of both keys right away, it usually
takes you back to the previous application. I do this a lot. When I’m in the text editor
I press Command+Tab to get back to the terminal, then when I’m done in the terminal
I press Command+Tab again to get back to my text editor. It’s very fast once you get
used to it.
You should skip down to the bottom of this chapter and read the “Warnings for Beginners”, but
otherwise you’re done with the setup and you are ready to begin Exercise 01 on Mac OS X! Nice job.
Exercise 0: The Setup 11
Linux
There are a lot of different versions of Linux out there, so I am going to give instructions for the
latest version of Ubuntu. If you are running something else, you probably know what you are doing
well enough to figure out how to modify the directions for your setup.
javac -version
You should get an error message that says “The program ‘javac’ can be found in the following
packages” followed by a list of packages.
This just means that the JDK isn’t installed, which is what we expect at this point.
That’s pretty much it. Everything in this book works fine using OpenJDK. (In fact, I use Linux for
most of my day-to-day work and the exercises in this book were actually written and tested using
OpenJDK!)
If, however, you’re determined to have to install something like Windows and Mac users have to,
you can download it from Oracle’s Java SE downloads page⁷.
You’re on your own for installing it, though. Seriously. Just use the version provided by your package
manager.
This is because Eclipse doesn’t work right without this JAR file. But we aren’t going to be using
Eclipse, and this message annoys me, so you need to add a line to the end of a hidden file called
.profile. (The filename starts with a dot/period, which is why it’s hidden.)
unset JAVA_TOOL_OPTIONS
Save the file and close it. You might want to click “Open” again and remove the checkmark next to
“Show Hidden Files”.
⁷http://www.oracle.com/technetwork/java/javase/downloads/index.html
Exercise 0: The Setup 13
javac -version
java -version
In the following text, I will use the word “folder” and the word “directory” interchangably.
They mean the same thing. The word “directory” is much older, but ever since the 1980s
graphical operating systems have used a picture of a folder to represent a directory, so that
word is now used, too.
Exercise 0: The Setup 14
ls
Type ls then press ENTER. (That’s an “L” as in “list”.) This command will list the contents of the
current folder/directory.
cd Documents
The cd command means “change directory” and it will move you into the “Documents” folder so
that future commands will take effect there.
Notice that your prompt will change to show that you are now inside a new folder. For example,
when I first open Terminal, my prompt is
mitchell@localhost:∼$
Then once I change into the “Documents” directory the prompt changes to
mitchell@localhost:∼/Documents$
You should type ls again once you get in there to see the contents of your Documents directory.
Now we are ready to create the folder.
mkdir javahard2
mkdir means “make directory” and will create a new folder in the current location. Typing ls
afterward should show you that the new directory is now there. You can call the folder something
different than “javahard2” if you want to. You will only need to create this folder once per computer.
cd javahard2
Change into the javahard2 folder. Afterward, type ls and it should list nothing. (The directory is
empty, after all.)
cd ..
This is how you use the cd command to back out one level. After you type it you will be back in
just the “Documents” directory, and your prompt should have changed to reflect that.
Exercise 0: The Setup 15
Issue the command to get back into the “javahard2” folder again.
Now, use the mouse to open the text editor you installed earlier. Type a sentence or something and
then save the file as test.txt. Save it into the “javahard2” folder you just created.
Go back to the terminal window and issue the ls command to see the file you just created.
If you’re feeling fancy, you won’t have to use the mouse to switch back to the terminal;
you can just press Alt + Tab on Windows or Linux or press Command + Tab on a Mac
to switch applications.
Press and hold the Alt key. Keep it pressed. Then press and release the Tab key a single
time. While still holding the Alt key, press Tab several more times until your terminal
window is selected, then let go of the Alt key to make the switch.
If you just quickly press Alt+Tab and let go of both keys right away, it usually takes
you back to the previous application. I do this a lot. When I’m in the text editor I press
Alt+Tab to get back to the terminal, then when I’m done in the terminal I press Alt+Tab
again to get back to my text editor. It’s very fast once you get used to it.
You should read the “Warnings for Beginners” below, but otherwise you’re done with the setup and
you are ready to begin Exercise 01 on Linux! Nice job.
• Write exercises using your text editor (gedit on Linux, TextWrangler on OSX, or Notepad++
on Windows).
Exercise 0: The Setup 16
1. It makes you do things that you don’t need to worry about right now.
2. It does things for you that you need to learn how to do for yourself first.
So follow my instructions and use a decent text editor and a terminal window. Once
you have learned how to code you can use other tools if you want, but not now.
WorkingWithObjects.java
1 import java.io.File;
2 import java.util.ArrayList;
3 import java.util.Random;
4 import java.util.Scanner;
5
6 public class WorkingWithObjects {
7 public static void main( String[] args ) throws Exception {
8 File f = new File("datafiles/phonetic-alphabet.txt");
9
10 if ( f.exists() == false ) {
11 System.out.println( f.getName() + " not found in this folder. :(");
12 System.exit(1);
13 }
14
Exercise 1: Working With Objects 18
Once you’ve got the code typed in I’m going to assume that you saved the file WorkingWithOb-
jects.java into a folder called javahard2. If you saved it into a different folder, substitute the
name below.
Open up a terminal window and change into the javahard2 folder:
cd javahard2
ls
(If you’re stuck on a much older version of Windows that doesn’t have Powershell, then you will
have to type dir. Everybody else gets to type ls, though.)
Hopefully you’ll see an output listing that includes:
WorkingWithObjects.java
Exercise 1: Working With Objects 19
That means you’re in the right place. Then you’ll compile the file using the Java compiler, which is
called javac:
javac WorkingWithObjects.java
If this command gives an error about javac itself, then you skipped Exercise 0! Go back and make
sure the JDK is installed and in the PATH, then come back!
Assuming you have good attention to detail and did everything that I told you, this command will
take a second to run, and then the terminal will just display the prompt again without showing
anything else.
However, if you made a mistake, you will see some error. If you have any error messages, fix them,
then save your code, go back to the terminal and compile again.
If you make a change to the code in your text editor, you must save the file before attempting
to re-compile it. If you don’t save the changes, you will still be compiling the old version
of the code that was saved previously, even if the code in your text editor is correct.
Eventually you should get it right and it will compile with no errors and no message of any kind.
Do a directory listing and you should see the bytecode file has appeared in the folder next to your
code:
javac WorkingWithObjects.java
ls
WorkingWithObjects.class
WorkingWithObjects.java
Now that we have successfully created a bytecode file we can run it (or “execute” it) by running it
through the Java Virtual Machine (JVM) program called java:
java WorkingWithObjects
Exercise 1: Working With Objects 20
Okay, now that that is working, let’s talk about some of the patterns we see in this exercise.
Line 1 imports a “library”. java.io.File contains the definition for a object/class called File. Once
we have imported it, we can create File objects in our code and call methods defined inside those
objects.
The next three lines import three more libraries, each defining an object. Some programming
languages call these imported things “modules” instead of libraries. Same thing.
On line 8 we instantiate a File object and name it f. The File object is passed a String parameter
containing the name of a file to connect itself to.
You should have been provided a folder called datafiles with several files in it, including a text
file named phonetic-alphabet.txt. Make sure this folder is inside the folder where your Java file
is located. Copy or move the folder there if it isn’t already.
On line 9, we now have a File object named f that is somehow connected to the text file on our
computers.
On line 15 we created a second object. This is an ArrayList of Strings named words, and instantiating
it didn’t use any parameters.
On line 16, we create a third object. This one is a Scanner object, and it uses the File object from
before as its parameter.
Finally, on line 26 we instantiate our fourth object: a Random object. Notice the pattern. If you want
to instantiate an object called “Bob”, you’d write code like this:
Or maybe:
String s = "Robert";
Bob b = new Bob(s);
Exercise 1: Working With Objects 21
That’s pretty much how Java creates objects. The keyword new is always involved, and the name of
the class (twice) and some parens.
Now let’s look at method calls. A method is a chunk of code inside an object that accomplishes a
single purpose, and “calling” a method means asking the object to execute the code in that method
for you.
On line 10, we call a “method” named exists() that is contained inside the File object f. This
method will return a Boolean value (either true or false) depending on whether or not that file
exists. The code that figures out how to do that is contained inside the library java.io.File that
we imported. Make sense?
Line 11 features another method in the File class: getName(). It returns a String containing the
name of the file associated with the object. If you skip down to line 18 you can also see a method
named getPath() being called.
Line 19 calls the hasNext() method, which is in the Scanner class (our Scanner object is named
alpha. It returns true if there’s text in the file we haven’t read yet.
The next() method reads a single String from the file and then on line 21 we call the add() method
of ArrayLists to add that String to the list.
On line 23 we call the close() method, which closes the Scanner object so that we can’t read from
its file anymore.
Line 27 calls the setSeed() method of the Random class, and line 31 calls the nextInt() method of
the same class. Line 31 also calls the size() method of ArrayLists, and line 32 calls get() to retrieve
a single String out of the list.
Finally line 33 calls a method named toLowerCase(), which is part of the String class. Could you
have figured that out if I hadn’t told you? I hope so, because “toLowerCase()” looks like a method
call, and the variable s is a String.
Okay, so that’s enough for this exercise. The specific details of how this program works aren’t
important, but at this point you should have a good sense of how you do the following in Java:
Study Drills
After most of the exercises, I will list some additional tasks you should try after typing up
the code and getting it to compile and run. Some study drills will be fairly simple and some
will be more challenging, but you should always give them a shot.
1. Computers are pretty bad at being “random”. They can only generate a random
sequence of values, but that sequence is typically based on a “seed”. If you use the
same seed, the sequence of random numbers will be the same. (This is useful for
debugging.) Change the seed on line 27 to something else (maybe 23213 or whatever).
Then run the program again and confirm that although the output is different from
before, it doesn’t change when you run the program many times.
Add a comment explaining what seed you picked and what the output was.
Exercise 2: Creating Your Own Single
Objects
In the last chapter, we imported a few objects from Java’s “standard library”: the collection of classes
and methods that are pre-built by the creators of the language.
In this chapter, we will create objects of our own, and each one will contain a single method.
Type up the following code and get it to compile. Save it in your ‘javahard2’ folder with a name of
OldMacDonald.java.
OldMacDonald.java
1 class Cow {
2 public void moo() {
3 System.out.println("Cow says moo.");
4 }
5 }
6
7 class Pig {
8 public void oink() {
9 System.out.println("Pig says oink.");
10 }
11 }
12
13 class Duck {
14 public void quack() {
15 System.out.println("Duck says quack.");
16 }
17 }
18
19 public class OldMacDonald {
20 public static void main( String[] args ) {
21
22 Cow maudine = new Cow();
23 Cow pauline = new Cow();
24 maudine.moo();
25 pauline.moo();
26
27 Pig snowball = new Pig();
Exercise 2: Creating Your Own Single Objects 24
28 snowball.oink();
29 snowball.oink();
30
31 Duck ferdinand = new Duck();
32 ferdinand.quack();
33 }
34 }
java OldMacDonald
Lines 1-5 define an object called Cow. The definition of the Cow class includes the definition of a
method called moo(). Note that on line 2 it says “public void moo()”, not “public static void moo()”.
Except for main(), you won’t be using the keyword static very much anymore.
Lines 7 through 11 define a class named Pig, containing an oink() method. And lines 13 through
17 define a class named Duck, which contains a quack() method.
Lines 19 to 34 define the class that matches the name of the Java file. Notice that in this file, the class
OldMacDonald has the keyword public in front, but none of the other classes do. In Java, each file
may only have one public class in it, and the name of that public class has to match the name of the
file.
This class contains the main() method in it, which is where the Java Virtual Machine begins when
executing a file. The OldMacDonald class is listed after the other classes in the file, but it would work
the same if the classes were in a different order.
When we run this program, execution begins on the first line of the main() method. Any other code
in the file will only execute if it gets called from inside main().
Lines 22 and 23 instantiate two Cow objects. Lines 24 and 25 call the moo() method on behalf of each
object. This causes execution to jump up to line 3, run the println() statement inside the method,
and return back down below.
Exercise 2: Creating Your Own Single Objects 25
On line 27 we create an instance of a Pig object and then call its oink() method twice. And on line
31 we instantiate a Duck object and call its only method on the next line.
Then on line 33 we hit the close curly brace of the main() method, which typically means the end
of the program.
Do you see? Defining your own objects isn’t so hard, and calling their methods is pretty easy, too,
once you’ve instantiated an object.
Study Drills
1. Try moving the entire definition of the Duck class below the OldMacDonald class.
Does the code still compile and work? Answer in a comment.
2. Inside the main() method, instantiate another object and call its method. (It doesn’t
matter which of the three objects; just pick one.)
Exercise 3: Defining Objects in
Separate Files
In the previous exercise, we defined three objects (actually four if you count the one that had main()
in it), but they were all implemented in the same file. This is not typically how things are done.
Usually Java puts the implementation for each class into its own file, and then there’s another file
that just holds the main() method that instantiates the objects and makes them do their thing. This
class is often called the “driver” class, so usually I’ll put the word “Driver” in the name of the file.
Type up the following code, and put each class into its own file, named as shown. Save them all in
the same folder.
OldMacCow.java
After you’ve typed in and saved OldMacCow.java, you should probably try to compile it to make
sure you haven’t made any mistakes before you move on.
OldMacDuck.java
Did you accidentally try to run this file or the first one? Neither one contains a main() method, and
so executing it by itself won’t work.
Exercise 3: Defining Objects in Separate Files 27
OldMacDriver.java
Ah, there’s the main() method. Once done you can compile these a few ways.
javac OldMacCow.java
javac OldMacDuck.java
javac OldMacDriver.java
You can compile them one at a time. That works just fine.
Although you have probably only used the Java compiler on one file at a time, it will happily compile
as many files as you give it, in order from left to right.
If there’s an error, though, you’ll have to pay attention to the filename in the error message. For
example:
This error message is on line 2 in the file OldMacCow.java, whereas the next mistake is on line 6 or
earlier in the file OldMacDuck.java for this error message:
javac OldMac*.java
If the filenames you’re trying to compile are similar, you can compile them all at once with something
like this. The star/asterisk gets expanded by your terminal into all filenames in the current folder
that begin with OldMac and which end in .java. (This includes the file OldMacDonald.java from the
previous exercise. Which is fine, compiling doesn’t “combine” the files in any way, it just converts
each file one at a time into its own bytecode (.class) file.)
javac OldMacDriver.java
So, what magic is going on here? Only one file name? Well, what happens is that javac starts
compiling OldMacDriver.java. On line 3 we refer to an object called OldMacCow. There’s no object
called that defined in this file. And there are no import statements to import a class called that, either.
So the Java compiler goes hunting. It knows it needs an object called OldMacCow, which would be
implemented in a bytecode file named OldMacCow.class. If this file exists in the current folder, then it
pulls the definitions from this bytecode file automatically! (This is a big deal for C++ programmers.)
And if there’s no bytecode file in the current folder, it then looks for a source code file called
OldMacCow.java that it can compile to create that bytecode file. If such a file is in the current folder,
it’ll just automatically compile it for you.
It does this for any objects referenced in the file you’re compiling. If it can resolve all the
dependencies itself, it’ll do so. If not, it’ll throw a compiler error about the undefined symbol it
couldn’t find.
So, to sum up, from here until the end of the book you should probably compile each file as you
finish it to make sure there aren’t any mistakes. But if you’re lazy or just confident, it is usually
okay to just compile the one file containing the main(), and let the compiler find the rest of the files
for you.
java OldMacDriver
Exercise 3: Defining Objects in Separate Files 29
You’ll notice that the process of actually instantiating the objects or calling their methods isn’t any
different. (See lines 3 through 9 in the driver file.) You just make an instance of an object, then call
its method, just like before.
Hopefully this process of doing one program that is broken up into multiple files makes sense.
Because that’s what we will be doing from here on out in the rest of the book!
(I’m not trying to be difficult; that’s just how object-oriented programming works. Code is broken
up into classes/objects each in their own file and those objects are combined to make a working
program. I’ll talk more about the reasons behind this in the chapters to come.)
Study Drills
1. Edit the message in the moo() method inside OldMacCow. Save the file with the
changes but do not compile it! Then edit the message in the quack() method inside
OldMacDuck(). Save the file but don’t compile it either. Then confirm that the
single command javac OldMacDriver.java will compile all three files. Answer in
a comment in the driver file how things worked out.
Exercise 4: Fields in an Object
So far we have only looked at methods inside of objects. But most objects have variables inside them,
too, called “fields” (or sometimes “instance variables”).
This program will illustrate accessing fields in an object.
Type up this code and save it in its own file, named as indicated.
TVActor.java
1 public class TVActor {
2 String name;
3 String role;
4 }
Then type up this one and save it in the same folder as the first file.
TVActorDriver.java
1 public class TVActorDriver {
2 public static void main( String[] args ) {
3 TVActor a = new TVActor();
4 a.name = "Thomas Middleditch";
5 a.role = "Richard Hendricks";
6
7 TVActor b = new TVActor();
8 b.name = "Martin Starr";
9 b.role = "Bertram Gilfoyle";
10
11 TVActor c = new TVActor();
12 c.name = "Kumail Nanjiani";
13 c.role = "Dinesh Chugtai";
14
15 System.out.println( a.name + " played " + a.role );
16 System.out.println( b.name + " played " + b.role );
17 System.out.println( c.name + " played " + c.role );
18 }
19 }
Remember that you only need to compile the one file containing the main() method, though it is a
good idea to test compiling each file as you finish it to make sure it’s correct before moving on.
Exercise 4: Fields in an Object 31
javac TVActorDriver.java
java TVActorDriver
So the class TVActor contains two instance variables, and they are both Strings. The first variable is
called name and the second is called role.
They are called “instance” variables because each instance (copy) of the object gets its own copies
of the variables.
That is, just after line 11 is over, there are three instances of the TVActor class created. public class
TVActor makes a pattern or recipe or blueprint of sorts, and then line 3 actually sews together the
clothing or cooks the recipe or builds the structure when it instantiates the object.
And so the instance named a has a copy of the name variable and a copy of the role variable. We
can put values into a’s copies of these variables as shown on lines 4 and 5, though we’ll see later in
the book that this is considered bad style.
Line 7 creates a second instance of the class, with its own copies of the instance variables.
And line 11 creates a third instance of the class, which also has its own copies of the variables. So
by line 14, there are at least nine objects floating around in memory: three TVActor objects and six
String objects (two per TVActor).
Study Drills
1. Add a third instance variable to the TVActor class, either a String, an int, or a double.
Name it something suitable, then add code to the driver class to put values for each
instance of the TVActor object.
Also add code to print out the new field.
Exercise 5: Programming Paradigms
Before I get too far into the weeds of object-oriented programming (OOP), it might be useful to
see the difference between OOP-style code and doing the same program in other programming
paradigms.
I created a short program that does four things:
First, here’s the program using as much of a simple, monolithic style as Java will allow. You don’t
have to type this program in unless you really want to.
StringFunMonolith.java
1 import java.util.Scanner;
2
3 public class StringFunMonolith {
4 public static void main( String[] args ) {
5 Scanner keyboard = new Scanner(System.in);
6
7 // input it
8 System.out.print("Enter a message: ");
9 String msg = keyboard.nextLine();
10
11 // reverse it
12 String rev = "";
13 for ( int i=msg.length()-1; i>=0; i-- )
14 rev += msg.substring(i,i+1);
15
16 // camel-case it
17 String lower = rev.toLowerCase();
18 String[] words = lower.split(" ");
19 String result = "";
20 for ( String w : words )
21 result += w.substring(0,1).toUpperCase() + w.substring(1);
Exercise 5: Programming Paradigms 33
22
23 // display it
24 System.out.println(result);
25 }
26 }
Enter a message: ^C
So, lines 8-9 input the message, lines 12-14 reverse it, lines 17-21 camel-case it, and line 24 displays
it. Don’t worry too much if you don’t understand the details of the camel-case part.
Next, I have coded the same program in a “functional” style. Functional style uses only functions
with a few inputs and only one output each. The functions don’t share information with each other
except through their inputs and outputs.
Again, there’s no sense typing up this version unless you want the practice. (It does work, though.)
StringFunFunctional.java
1 import java.util.Scanner;
2
3 public class StringFunFunctional {
4 public static void main( String[] args ) {
5 Scanner keyboard = new Scanner(System.in);
6
7 // input it
8 System.out.print("Enter a message: ");
9 String msg = keyboard.nextLine();
10
11 // reverse it
12 msg = reverse(msg);
13
14 // camel-case it
15 msg = camelCase(msg);
16
17 // display it
18 System.out.println(msg);
19 }
20
Exercise 5: Programming Paradigms 34
Lines 1-9 are the same as the previous version, because it’s kind of hard to get input from the human
in Java any other way.
But you can see on line 12, the message (in the variable msg) is passed in to a function called reverse,
and the result is put back into msg, overwriting the previous value. This is a bit more understandable.
And lines 21-27 are the reverse() function itself. It’s the same code as lines 12-14 of the previous
assignment, but there’s a little extra setup to name the function and name the parameter and also an
extra line to “return” the final result. Notice, though, that we get to call the input s instead of having
to care that it’s really called msg elsewhere. It’s a bit nice to be able to call that variable whatever
we want without caring what happens in other parts of the program.
Line 15 is the camelCase function call, and lines 29 through 36 are the function definition. Notice
that on line 29 we were free to call the parameter s without caring about other parts of the program.
Is the variable in main() really called s?
Doesn’t matter.
Is some other function already using a variable called s?
Doesn’t matter.
What variable is the return value going into?
It doesn’t matter. We can call it result or rev or whatever suits us.
Another nice thing about a functional style of programming is that since each function receives an
input and returns an output, functions can be chained very compactly.
Here is the same functional version, but with the functions all nested inside each other.
Exercise 5: Programming Paradigms 35
StringFunFunctionalShort.java
1 import java.util.Scanner;
2
3 public class StringFunFunctionalShort {
4 public static void main( String[] args ) {
5 Scanner keyboard = new Scanner(System.in);
6
7 System.out.print("Enter a message: ");
8 System.out.println(camelCase(reverse(keyboard.nextLine())));
9 }
10
11 public static String reverse( String s ) {
12 String rev = "";
13 for ( int i=s.length()-1; i>=0; i-- )
14 rev += s.substring(i,i+1);
15
16 return rev;
17 }
18
19 public static String camelCase( String s ) {
20 String[] words = s.toLowerCase().split(" ");
21 String result = "";
22 for ( String w : words )
23 result += w.substring(0,1).toUpperCase() + w.substring(1);
24
25 return result;
26 }
27 }
You read line 8 from the inside out. The inner-most thing happens first: keyboard.nextLine()
is called. Once it’s done, it returns a String, which we pass immediately to reverse(), then
camelCase(), then println().
Some programs are more difficult in a functional style, but when it works it’s really nice and clean-
looking.
By the way, formulas in a spreadsheet program like Microsoft’s Excel, Apple’s Numbers
or LibreOffice’s Calc are programmed in a functional style. This is a tricky way to code,
as you know if you’ve ever struggled to get one right!
Graphics-processing shaders (like in OpenGL or Direct3D) are usually written in a
functional style, too, and that makes them well-suited for parallel processing.
Exercise 5: Programming Paradigms 36
Okay, finally let’s do this same little program in an object-oriented style. We’ll use two files as usual:
one containing our class/object, and one with the driver. These are the ones you should type in.
StringFunObject.java
1 public class StringFunObject {
2
3 String message;
4
5 public void setMessage( String s ) {
6 message = s;
7 }
8
9 public String getMessage() {
10 return message;
11 }
12
13 public void reverse() {
14 String rev = "";
15 for ( int i=message.length()-1; i>=0; i-- )
16 rev += message.substring(i,i+1);
17
18 message = rev;
19 }
20
21 public void camelCase() {
22 String[] words = message.toLowerCase().split(" ");
23 String result = "";
24 for ( String w : words )
25 result += w.substring(0,1).toUpperCase() + w.substring(1);
26
27 message = result;
28 }
29 }
There’s something new in this one. On line 3 there’s an instance variable / field, just like you learned
about in the previous exercise.
Notice that on line 6, there’s a method that stores a copy of the parameter s into a variable named
message. Where is this message declared? It’s the field. We’ll look more at this in later chapters, so
don’t worry too much about it for now.
Just remember for this code, any time that “message” is referenced, it’s the instance variable. All
the other variables are “local”, which means they only exist inside the method in which they are
defined.
Exercise 5: Programming Paradigms 37
So, here’s the code for the driver. Type this one in, too.
StringFunOODriver.java
1 import java.util.Scanner;
2
3 public class StringFunOODriver {
4 public static void main( String[] args ) {
5 Scanner keyboard = new Scanner(System.in);
6
7 // input it
8 System.out.print("Enter a message: ");
9 String msg = keyboard.nextLine();
10
11 StringFunObject sfo = new StringFunObject();
12 sfo.setMessage(msg);
13 sfo.reverse();
14 sfo.camelCase();
15
16 // display it
17 System.out.println( sfo.getMessage() );
18 }
19 }
Enter a message: ^C
(There’s the output again so you don’t have to scroll up for it.)
This is very typical object-oriented code. Line 11 declares and instantiates an object. Line 12 calls the
setMessage() method of that object, and passes the message into it as a parameter. Then the next
few changes happen inside the object: the message gets reversed, then the message gets camel-cased.
Finally on line 17 of the driver we call the getMessage() method of the object, and it returns to us
the modified String for printing.
Maybe you don’t like the object-oriented style. Maybe you think the monolithic version is better, or
maybe the functional version.
You know what? I agree with you. Object-oriented programming isn’t a very good fit for a tiny
program like this. OOP works best when the programs are large and complicated (like 10,000 lines
of code or more).
Exercise 5: Programming Paradigms 38
Whenever I write a program to help me automate something annoying, I almost never code it in an
object-oriented style if it’s going to be only 500 lines of code or less.
I write it in a monolithic style if it’s just going to be 10-50 lines long. I use functions when it’s 50-500
lines long, and I start out object-oriented if it’s going to be much bigger than that.
Unfortunately the rest of this book is going to be a little weird. I’m going to use the object-oriented
style even for tiny 20-line programs. It’ll be gross. You might not like it. You might think “This
program would be so much simpler if he would just….”
But I can’t teach you object-oriented programming using only nice huge 1,000 line perfect examples
where OOP makes sense. (Well, I could, but this book would be about 800 pages longer and I wouldn’t
have finished writing it yet!) Instead I have to teach you OOP using small silly example programs
where the OOP feels weird and forced but the programs are small enough to understand.
Once you’re done with this book, you’re free to code for the rest of your life in a non-object-oriented
way. But, if someone dumps a 20,000 (or two-million!) line program on you that uses OOP just to
have any hope of preventing bugs, then you’ll have the tools to make sense of it.
Deal?
Study Drills
1. Using the reverse() method as a guide, add a method to the object-oriented version
to remove half of the letters from the message. (It can be the first half, the last half,
every other letter or whatever scheme you like.) Then add a call for that method to
the driver.
Exercise 6: Accessing Fields in
Methods
In this exercise, we are going to look in closer detail at the concept of an object having fields
and methods that access those variables. This was introduced in the OOP-version of the previous
exercise.
Here is the source code for the object, which will take a phrase and a number and produce a String
with the specified number of copies of that message.
PhraseRepeater.java
This class has two fields / instance variables, a String named phrase and an int named repeats.
Remember that if we were to instantiate several versions of this object in a driver, each instance of
the object would have its own copies of both fields.
“Instance variables” are variables defined in a class but outside of any method. A “field”
is just a generic name for a member of a class. They mean pretty much the same thing,
so I will use them interchangably in this book.
Random documents with unrelated
content Scribd suggests to you:
It was quite a treat now to Todd, and put him in mind of old times,
to arrange his apparatus for giving this wretched man a tumble into
the vaults below. He went into the parlour and drew the bolt, when
away went the man and the chair, and the other chair that was on
the reverse side of the plank took the place of that which had gone.
"Ha! ha!" shouted Todd. "This is grand—this is most glorious! Ha!
ha! Who would have thought, now, that I should ever live to be at
my old work again in this house? It is capital! If that fall has not
broken his neck, it's a wonder. It used to kill five out of seven; that
was about the average—ha!"
Todd didn't fasten the bolt again, but went at once for the other
man. He was sitting up!
Todd staggered back for a moment, when he saw him in that
position looking at him. The man rubbed his eyes with his hands and
said in a weak voice—
"Good God! what is it all about?"
Todd placed the light on the floor within the parlour, so that it shed
sufficient rays into the shop to let him see every object in it; and
then, with a cry like that of some wild beast rushing upon his prey,
he dashed at the man.
The struggle that ensued was a frightful one. Despair, and a feeling
that he was fighting for his life, nerved the man, who had recovered
just in time to engage in such a contest, and they both fought their
way into the shop together. Todd made the greatest exertions to
overcome the man, but it was not until he got him by the throat,
and held him with a clutch of iron, that he could do so. Then he
flung him upon the chair, but the man, with a last effort, dragged
Todd after him, and down they both went together to the vault
below!
Todd And The Bow Street Officers—The Death Grapple.
CHAPTER CXLVII.
SIR RICHARD BLUNT AND CROTCHET COMMENCE
THEIR SEARCH FOR TODD.
When Sir Richard Blunt left Chelsea, he felt that he had given a
sufficient warning to all who could feel in any way personally
interested in the escape of Sweeney Todd from the punishment that
his numerous crimes merited.
He rode direct to the office of the Under Secretary of State for the
Home Department, and his name at once procured him an interview.
This was not the supercilious personage who once before, upon an
occasion of Sir Richard Blunt calling upon him regarding Sweeney
Todd, had exhibited so much indifference upon the subject, and Sir
Richard was received as he ought to be.
"I have waited upon you, sir," said the magistrate, "to say that I
have now made every arrangement that is possible for the purpose
of counteracting any mischief that the man, Todd, might strive to do;
and I think it very likely that I may not have the pleasure of seeing
or communicating with you for some time."
"Then you still think, Sir Richard, of going personally after the
notorious ruffian?"
"I do, sir. I feel that in some sort I am bound to rid society of that
man. I had so large a share in his former apprehension, and in his
conviction, that I feel his escape quite a personal matter; and I have
no hesitation in saying that I shall not feel at ease until I have again
placed him in the hands of the law."
"It is most desirable that he should be so placed, Sir Richard, and I
have only two things to say to you upon the subject. One is, that I
hope you will be careful of your own safety in the affair; and the
other is, that anything we can do or any facilities we can throw in
your way, you may most unhesitatingly command in the prosecution
of your most praiseworthy enterprise."
"I thank you, sir. I shall take one man with me. His name is
Crotchet; and I should wish that in your name I might tell him that,
in the event of our search for Todd being successful, he may count
upon an adequate reward."
"Certainly! He shall have the whole reward, Sir Richard; and as for
yourself, the ministry will not be unmindful of your service in a way
that I am sure will be more gratifying to you than an offer of
money."
"Sir, I thank you. The government has already, upon more than two
or three occasions, been sufficiently liberal to me as regards money
to place me in a good position, and I have now no further desires of
that sort. I will bid you good morning, sir, and at once start upon the
expedition in search of Sweeney Todd. If he be alive and above
ground in this country, I will have him."
"If anybody will, you will, Sir Richard."
The magistrate left the place, and repaired at once to his private
office, which was close at hand, in Craven Street. There our old
friend, Crotchet, was waiting for him.
"Well, Crotchet," said Sir Richard, "I have just seen the Secretary of
State, and if we catch Todd, you are to have all the money."
"All on it, sir? Oh, my eye! No, I doesn't want all on it, Sir Richard. I
isn't a pig."
"I never thought you were, Crotchet; but you may make up your
mind to the whole of the reward, as the government will provide for
me in another way; so you know now, at starting, what you have to
expect, and it will keep you in good heart during all the botheration
we may have in looking after this man."
"Why, so it will, sir, you see, so it will, and if I do catch him and get
all this tin as is offered as a reward for him, I shall retire from the
grabbing business, you see, sir."
"What will you do then, Crotchet?"
"Set up a public-house, sir, and call it 'The Crotchet's Arms,' to be
sure. That's the sort of ticket for me."
"Well, Crotchet, you will be quite at liberty to do what you like; and
now let us at once start on our errand. We will, from the door of
Newgate, see if we cannot trace the progress of this man, with his
new friend, that rascal, Lupin."
A tap sounded on the panel of the door of the room in which
Crotchet and Sir Richard were conversing.
"Come in," said the magistrate, and his clerk entered with a written
paper in his hand.
"Here, sir," he said, "is a report from a city officer, which will give a
clue to the route that Todd and Lupin have taken, sir."
"Ah, that is welcome. Let me see it. 'Two men broke into the house
of Alderman Stanhope; one a tall man with a large face—the other,
shorter.' Humph! Not a doubt of it. I will go and see about it. No
doubt it was Todd and his new friend Lupin. This is something of a
clue, at all events however slight, and may, after all, put us upon the
right track. Come on, Crotchet, we will do the best we can in this
matter. Have you your pistols in good order?"
"Yes, yer honour, and a pair of darbies in my pocket, that if once
they get on the wrists of old Todd, he will find it no such easy matter
to get them off again."
"That is right. I only want to get face to face with the ruffian, and
then I will engage that he shall not be much further trouble to
society or to individuals."
Sir Richard Blunt and Crotchet proceeded then at once to the house
in the City, into which Lupin and Todd, it will be recollected, had
made a violent entry, and from which they had been so gallantly
repulsed by the young lady. Then, from the description of the
assailants, not a shadow of a doubt remained upon the magistrate's
mind that they were the parties he sought; but there all clue seemed
to be lost.
He and Crotchet stood in the street looking about them rather
despairingly; and then they thought of going to the round-house
close to Finsbury; and when they got there, they found an officer,
who reported that two men answering the description of the
fugitives had been seen making their way westward; and he had
met a woman who had passed them, and who had heard the words
"money," and "Caen Wood."
This was, in good truth, most important intelligence, if it could be
relied upon; and that was the only kind of doubt that Sir Richard
had. He spoke to Crotchet about it.
"What do you think, Crotchet? Is it worth while to follow this
seeming clue to Highgate?"
"Yes, yer honour, it is. We can go there and back again while we are
considering about it here. It's clear enough as we shan't get any
other news in this part of the town; and so I advises that we go off
at once to Highgate, and calls at every public-house on the road."
"Every public-house?"
"Yes, yer honour. Todd won't do without his drops of something
strong to keep him a-going. These kind of feelings go down—down,
till they haven't the heart to say don't, when the hangman puts the
noose round their necks, if they haven't their drops. It's brandy, yer
worship, as keeps 'em a going."
"I do believe, Crotchet, that there is a great deal of truth in what
you say; and that it is only by use of stimulants that they keep up a
kind of artificial strength, as well as drowning reflection; and so they
go blundering on in the career of crime."
"You may depend upon it, sir. They'd cut their own throats in a
week, If it wasn't for the tipple, yer honour."
Acting then upon the practical advice of Crotchet, which in a great
measure accorded with his own convictions, Sir Richard Blunt
repaired to a livery-stable, and hired two good horses. He found no
difficulty in getting them, upon declaring who he was; and so, well
mounted, he and Crotchet went upon the very road that had been
so recently traversed by the two culprits, Todd and Lupin.
At the first public-house they came to they got no news; but at the
second they were told, that two men, answering the description they
gave of those they sought, had called and had some brandy.
The magistrate no longer doubted but that he was upon the right
track now. With such a feeling, he pushed on, making what inquiries
he could on the road; but until Highgate was reached they got no
further news, and then, by dint of diligent ferreting out, they found a
woman who had seen two men go down Swains Lane, and from the
description she gave of them, there could be no doubt but that they
were Todd and Lupin. Now as Swains Lane led direct to Caen Wood,
it was a great confirmation of the former intelligence; and Sir
Richard made up his mind to search the wood, as well as it could be
done by him and Crotchet.
They engaged a lad from Highgate to come with them, and to take
care of the horses, while they should go into the wood; but they did
not say one word to him regarding their object in going there, nor
could he possibly suspect it. Sir Richard and Crotchet both thought it
would be much more prudent to keep that to themselves, than to
put it in the power of a boy to gossip about it to every one who
might chance to pass that way, while he was minding the horses.
When the wood was reached, Sir Richard said to the lad—
"Now, my boy, we shall not be very long gone, but you will bear in
mind that if we are absent longer than you expected, you will be
paid in proportion; so don't be impatient, but walk the horses up and
down this bit of the lane; and think that you have got a very good
job."
"Thank you, sir," said the boy. "Across that there meadow is the
nearest way to the wood. I seed two fellows go that way, early this
morning, and one on 'em was the ugliest fellow I ever saw, and he
calls out to the other—'Come along Lupin, we shall be all right in the
wood now. Come along, Lupin—Ha! ha!'"
"You heard that?"
"Yes, sir, I did. You see, I was sloe-gathering in the hedge, and they
don't let you do it, cos they say you breaks down all the young
twigs, and spoils the hedge, and so you does; and so, sir, when I
heard footsteps a-coming, I hid myself right down among the long
grass, so that they did not see me."
Mr. Crotchet gave a long whistle.
"Very good," said Sir Richard; "we shall be back with you soon. You
take good care of the horses."
"I will, sir."
"What do you think of that, Crotchet?" said Sir Richard, as they
made their way into the very meadow across which Todd and Lupin
had run to get to Caen Wood.
"It's the finger o' Providence, yer worship."
"Well, I cannot deny, Crotchet, but that it may be so. At all events,
whether it be Providence or chance, one thing is quite certain, and
that is, that we are on the track of those whom we seek."
"Not a doubt o' that, sir. Into the wood here they have been, but
whether they have staid here or not, you see, sir, is quite another
affair. But it's worth looking well to; at all events yer worship, and I
shan't leave an old tree in this here place as we is coming to, that I
shan't walk right round and have a jolly good look at, somehow or
another."
"Nor I, Crotchet. They may know of some hiding-place in this wood,
for all we know to the contrary, and if they do, it strikes me we shall
ferret them out."
"In course we shall, sir; and here we is."
They had reached the wood by this time, and before plunging into
its recesses the magistrate looked carefully about him, and Crotchet
did the same.
"Do you think, your worship, there's a chance of such a fellow as
Todd staying long here?"
"Why do you think that?" said Sir Richard.
"Why, sir," said Crotchet, putting his head on one side, "this here is a
sort of place that makes a man think; and always when I am in a
quiet place like this, with the beautiful trees all about me, and the
little birds a singing, and the frogs a croaking, it makes me think of
things that I don't always think of, and of those as has passed away
like spirits, and as we may meet in t'other world nor this, sir."
"Indeed, Crotchet, I do not wonder that the silence and solitude of
nature should have that effect upon you."
"Exactly, sir. In course, it ain't for me to say whether in this ere
world there ought to be prigs, and sneaks, and cracksmen, and all
that sort of thing or not; but I will say, sir, as I'm not a little
surprised how anybody can do anything very wrong, sir, in the
country."
"Indeed, Crotchet?"
"Yes, sir; it has an effect on me. When I gets among the old trees
and sees the branches a waving about, and hear the wind a
moaning among 'em, it makes me think as there ain't a great deal in
this world as is worth the bothering about, you see, sir; and least of
all is it worthwhile doing anything that ain't the right thing."
"You are quite a philosopher, Crotchet, although you are not the first
nor the only one upon whom the beauties of nature have produced
an elevating effect. The reason I fear is that you are not familiar
with such places as these. You are town-bred, Crotchet, and you
pass your life among the streets of London; so such places as this
affect you with all the charm of novelty, while those who are born in
the country know nothing and care nothing for its sights and
sounds."
"That's about it, sir, I shouldn't wonder," said Crotchet; "but I feels
what I feels and thinks what I thinks."
They now had fairly penetrated into Caen Wood; and we may here
appropriately remark, that Caen Wood was much more of a real
wood then, than it is now, when it is rather an imitation of one than
one in reality. The smoke and the vegetation-killing vapours of
London have almost succeeded in begriming the green trees even at
that distance off; and in a few short years Caen Wood, we fear, will
be but a thing of tradition in the land.
So time works his changes!
Sir Richard Blunt, with long practised sagacity, began his hunt
through the wood. It could scarcely be said that he expected to find
Todd there, but he would be satisfied if he found some conclusive
evidence that he had been there, for that would show him that he
was upon the track of the villain, and that he was not travelling wide
from the course that Todd had taken. The idea that he might have at
once, on foot, made his way to some part of the coast, haunted Sir
Richard, notwithstanding all the seemingly conclusive evidence he
had to the contrary; and knowing well, as he did, how very little
reliance ought to be placed upon personal descriptions, he did buoy
himself up with many hopes consequent upon the presumed identity
of Todd with the person who had been seen by those who had
described him.
Taking a small piece of chalk from his pocket, the magistrate marked
a few of the trees in the different directions where they searched, so
that they might not, amid the labyrinths of the wood, give
themselves increased trouble; and in the course of half an hour they
had gone over a considerable portion of the wood.
They paused at an open spot, and Crotchet lifted from the ground a
thick stick that appeared to have been recently cut from a tree.
"This is late work," he said.
"Yes; and here are the marks of numerous footsteps. What is the
meaning of this strange appearance on the ground, as if something
had been dragged along it?"
Crotchet looked at the appearance that Sir Richard pointed out, and
then with a nod, he said—
"Let's follow this, Sir Richard. It strikes me that it leads to
something."
CHAPTER CXLVIII.
SHOWS HOW TODD HAD A VERY NARROW ESCAPE
INDEED.
The silence that ensued after that knock at his door, for he had
become to consider it as his again, was like the silence of the grave.
The only sound that Todd heard then, was the painful beating of his
own heart.
The guilty man was full of the most awful apprehensions.
"What is it?" he said. "Who is it?—who can it be? Surely, no one for
me. There is no one who saw me. No—no! It cannot be. It is some
accidental sound only. I—begin—to doubt if it were a knock at all.—
Oh, no, it was no knock."
Bang! came the knock again.
Todd actually started and uttered a cry of terror, and then he
crouched down and crept towards the door. He might, to be sure,
have made his escape from the premises, with some little trouble, by
the way he had got into them; but he was most anxious to find out
who it was that demanded admittance to the old shop in Fleet
Street, with all its bad associations and character of terror; so he
crept towards the door, and just as he reached it, the knock came
again.
If the whole of his future hopes—we allude to the future that might
be for him in this world only, for Todd had no hopes nor thoughts of
another—had depended upon his preserving silence and stillness, he
could not have done so, and he gave another start.
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.
ebookbell.com