Data Structures Abstraction and Design Using Java 2rd Edition by Elliot Koffman, Paul Wolfgang 9781119239147
Data Structures Abstraction and Design Using Java 2rd Edition by Elliot Koffman, Paul Wolfgang 9781119239147
https://ebookball.com/product/problem-solving-and-program-design-
in-c-3rd-edition-by-jeri-hanly-elliot-koffman-
isbn-0201754908-9780201754902-15530/
https://ebookball.com/product/data-structures-and-problem-solving-
using-java-4th-edition-by-mark-weiss-0321541405-9780321541406-17186/
Data Structures and Problem Solving Using Java 4th edition
by Mark Allen Weiss ISBN 0321541405 978-0321541406
https://ebookball.com/product/data-structures-and-problem-solving-
using-java-4th-edition-by-mark-allen-weiss-
isbn-0321541405-978-0321541406-16342/
ELLIOT B. KOFFMAN
Temple University
PAUL A. T. WOLFGANG
Temple University
This book was set in 10/12 pt SabonLTStd-Roman by SPiGlobal and printed and bound by Lightning Source Inc.
Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more than 200 years, helping people
around the world meet their needs and fulfill their aspirations. Our company is built on a foundation of principles that include responsibility
to the communities we serve and where we live and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address
the environmental, social, economic, and ethical challenges we face in our business. Among the issues we are addressing are carbon impact,
paper specifications and procurement, ethical conduct within our business and among our vendors, and community and charitable support.
For more information, please visit our website: www.wiley.com/go/citizenship.
Copyright © 2016, 2010 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit-
ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authori-
zation through payment of the appropriate per‐copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923
(Web site: www.copyright.com). Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley &
Sons, Inc., 111 River Street, Hoboken, NJ 07030‐5774, (201) 748‐6011, fax (201) 748‐6008, or online at: www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next
academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please
return the evaluation copy to Wiley. Return instructions and a free of charge return shipping label are available at: www.wiley.com/go/
returnlabel. If you have chosen to adopt this textbook for use in your course, please accept this book as your complimentary desk copy.
Outside of the United States, please contact your local sales representative.
QA76.9.D35K58 2016
005.7'3—dc23
2015036861
Printing identification and country of origin will either be included on this page and/or the end of the book. In addition, if the ISBN on this
page and the back cover do not match, the ISBN on the back cover should be considered the correct ISBN.
Intended Audience
This book was written for anyone with a curiosity or need to know about data structures,
those essential elements of good programs and reliable software. We hope that the text will
be useful to readers with either professional or educational interests.
It is intended as a textbook for the second programming course in a computing curriculum
involving the study of data structures, especially one that emphasizes Object‐Oriented Design
(OOD). The text could also be used in a more‐advanced course in algorithms and data struc-
tures. Besides coverage of the basic data structures and algorithms (lists, stacks, queues, trees,
recursion, sorting), there are chapters on sets and maps, balanced binary search trees, graphs,
and an online appendix on event‐oriented programming. Although we expect that most read-
ers will have completed a first programming course in Java, there is an extensive review
chapter (included as an appendix) for those who may have taken a first programming course
in a different language, or for those who need a refresher in Java.
Case Studies
We illustrate OOD principles in the design and implementation of new data structures and in
the solution of approximately 20 case studies. Case studies follow a five‐step process (prob-
lem specification, analysis, design, implementation, and testing). As is done in industry, we
sometimes perform these steps in an iterative fashion rather than in strict sequence. Several
case studies have extensive discussions of testing and include methods that automate the test-
ing process. Some case studies are revisited in later chapters, and solutions involving different
data structures are compared. We also provide additional case studies on the Web site for the
textbook (www.wiley.com/college/koffman), including one that illustrates a solution to the
same problem using several different data structures.
Prerequisites
Our expectation is that the reader will be familiar with the Java primitive data types including
int, boolean, char, and double; control structures including if, case, while, for, and try‐catch;
the String class; the one‐dimensional array; input/output using either JOptionPane dialog win-
dows or text streams (class Scanner or BufferedReader) and console input/output. For those
readers who lack some of the concepts or who need some review, we provide complete coverage
of these topics in Appendix A. Although labeled an Appendix, the review chapter provides full
coverage of the background topics and has all the pedagogical features (discussed below) of the
other chapters. We expect most readers will have some experience with Java programming, but
someone who knows another programming language should be able to undertake the book
after careful study of the review chapter. We do not require prior knowledge of inheritance,
wrapper classes, or ArrayLists as we cover them in the book (Chapters 1 and 2).
Pedagogy
The book contains the following pedagogical features to assist inexperienced programmers
in learning the material.
• Learning objectives at the beginning of each chapter tell readers what skills they should
develop.
• Introductions for each chapter help set the stage for what the chapter will cover and tie
the chapter contents to other material that they have learned.
• Case Studies emphasize problem solving and provide complete and detailed solutions to
real‐world problems using the data structures studied in the chapter.
• Chapter Summaries review the contents of the chapter.
• Boxed Features emphasize and call attention to material designed to help readers become
better programmers.
Pitfall boxes help readers identify common problems and how to avoid
them.
Design Concept boxes illuminate programming design decisions and
trade‐offs.
Programming Style boxes discuss program features that illustrate good
programming style and provide tips for writing clear and effective code.
Syntax boxes are a quick reference for the Java structures being
introduced.
• Self‐Check and Programming Exercises at the end of each section provide immediate
feedback and practice for readers as they work through the chapter.
• Quick‐Check, Review Exercises, and Programming Projects at the end of each chapter
review chapter concepts and give readers a variety of skill‐building activities, including
longer projects that integrate chapter concepts as they exercise the use of data structures.
Theoretical Rigor
In Chapter 2, we discuss algorithm efficiency and big‐O notation as a measure of algorithm
efficiency. We have tried to strike a balance between pure “hand waving” and extreme rigor
when determining the efficiency of algorithms. Rather than provide several paragraphs of
formulas, we have provided simplified derivations of algorithm efficiency using big‐O nota-
tion. We feel this will give readers an appreciation of the performance of various algorithms
and methods and the process one follows to determine algorithm efficiency without bogging
them down in unnecessary detail.
Acknowledgments
Many individuals helped us with the preparation of this book and improved it greatly. We are
grateful to all of them. These include students at Temple University who have used notes that
led to the preparation of this book in their coursework, and who class‐tested early drafts of the
book. We would like to thank Rolf Lakaemper and James Korsh, colleagues at Temple
University, who used earlier editions in their classes. We would also like to thank a former
Temple student, Michael Mayle, who provided preliminary solutions to many of the exercises.
We would also like to acknowledge support from the National Science Foundation (grant num-
ber DUE‐1225742) and Principal Investigator Peter J. Clarke, Florida International University
(FIU), to attend the Fifth Workshop on Integrating Software Testing into Programming Courses
(WISTPC 2014) at FIU. Some of the testing methodologies discussed at the workshop were
integrated into the chapter on Testing and Debugging.
We are especially grateful to our reviewers who provided invaluable comments that helped
us correct errors in each version and helped us set our revision goals for the next version. The
individuals who reviewed this book are listed below.
Reviewers
Sheikh Iqbal Ahamed, Marquette University
Justin Beck, Oklahoma State University
John Bowles, University of South Carolina
Mary Elaine Califf, Illinois State University
Tom Cortina, SUNY Stony Brook
Adrienne Decker, SUNY Buffalo
Chris Dovolis, University of Minnesota
Vladimir Drobot, San Jose State University
Kenny Fong, Southern Illinois University, Carbondale
Ralph Grayson, Oklahoma State University
Allan M. Hart, Minnesota State University, Mankato
James K. Huggins, Kettering University
Chris Ingram, University of Waterloo
Gregory Kesden, Carnegie Mellon University
Sarah Matzko, Clemson University
Lester McCann, University of Arizona
Although all the reviewers provided invaluable suggestions, we do want to give special thanks
to Chris Ingram who reviewed every version of the first edition of the manuscript, including
the preliminary pages for the book. His care, attention to detail, and dedication helped us
improve this book in many ways, and we are very grateful for his efforts.
Besides the principal reviewers, there were a number of faculty members who reviewed
sample pages of the first edition online and made valuable comments and criticisms of its
content. We would like to thank those individuals, listed below.
Finally, we want to acknowledge the participants in focus groups for the second programming
course organized by John Wiley & Sons at the Annual Meeting of the SIGCSE Symposium in
March 2004. They reviewed the preface, table of contents, and sample chapters and also
provided valuable input on the book and future directions of the course.
Focus Group
Claude Anderson, Rose-Hulman Institute of Technology
Jay M. Anderson, Franklin & Marshall University
John Avitabile, College of Saint Rose
Cathy Bishop‐Clark, Miami University—Middletown
Debra Burhans, Canisius College
Michael Clancy, University of California—Berkeley
Nina Cooper, University of Nevada Las Vegas
Kossi Edoh, Montclair State University
Robert Franks, Central College
Evan Golub, University of Maryland
Graciela Gonzalez, Sam Houston State University
Scott Grissom, Grand Valley State University
Jim Huggins, Kettering University
Lester McCann, University of Wisconsin—Parkside
Briana Morrison, Southern Polytechnic State University
Judy Mullins, University of Missouri—Kansas City
Roy Pargas, Clemson University
J.P. Pretti, University of Waterloo
Reza Sanati, Utah Valley State College
Barbara Smith, University of Dayton
Suzanne Smith, East Tennessee State University
Michael Stiber, University of Washington, Bothell
Jorge Vasconcelos, University of Mexico (UNAM)
Lee Wittenberg, Kean University
We would also like to acknowledge and thank the team at John Wiley & Sons who were
responsible for the management of this edition and ably assisted us with all phases of the
book development and production. They were Gladys Soto, Project Manager, Nichole Urban,
Project Specialist, and Rajeshkumar Nallusamy, Production Editor.
We would like to acknowledge the help and support of our colleague Frank Friedman who
also read an early draft of this textbook and offered suggestions for improvement. Frank and
Elliot began writing textbooks together many years ago and Frank has had substantial influ-
ence on the format and content of these books. Frank also influenced Paul to begin his teach-
ing career as an adjunct faculty member and then hired him as a full‐time faculty member
when he retired from industry. Paul is grateful for his continued support.
Finally, we would like to thank our wives who provided us with comfort and support through
this arduous process. We very much appreciate their understanding and their sacrifices that
enabled us to focus on this book, often during time we would normally be spending with
them. In particular, Elliot Koffman would like to thank
Caryn Koffman
and Paul Wolfgang would like to thank
Sharon Wolfgang
Contents
Preface iii
Connecting Nodes 78
A Single-Linked List Class 79
Inserting a Node in a List 79
Removing a Node 80
Completing the SingleLinkedList Class 81
The get and set Methods 82
The add Methods 82
Exercises for Section 2.5 83
2.6 Double‐Linked Lists and Circular Lists 84
The Node Class 85
Inserting into a Double‐Linked List 86
Removing from a Double‐Linked List 86
A Double‐Linked List Class 86
Circular Lists 87
Exercises for Section 2.6 88
2.7 The LinkedList Class and the Iterator, ListIterator, and Iterable Interfaces 89
The LinkedList Class 89
The Iterator 89
The Iterator Interface 90
The Enhanced for Loop 92
The ListIterator Interface 92
Comparison of Iterator and ListIterator 94
Conversion between a ListIterator and an Index 95
The Iterable Interface 95
Exercises for Section 2.7 95
2.8 Application of the LinkedList Class 96
Case Study: Maintaining an Ordered List 96
Testing Class OrderedList 101
Exercises for Section 2.8 103
2.9 Implementation of a Double‐Linked List Class 103
Implementing the KWLinkedList Methods 104
A Class that Implements the ListIterator Interface 104
The Constructor 105
The hasNext and next Methods 106
The hasPrevious and previous Methods 107
The add Method 107
Inner Classes: Static and Nonstatic 111
Exercises for Section 2.9 111
2.10 The Collections Framework Design 112
The Collection Interface 112
Common Features of Collections 113
The AbstractCollection, AbstractList, and
AbstractSequentialList Classes 113
The List and RandomAccess Interfaces (Advanced) 114
Exercises for Section 2.10 114
Java API Interfaces and Classes Introduced in this Chapter 116
User‐Defined Interfaces and Classes in this Chapter 116
Quick‐Check Exercises 116
Review Questions 117
Programming Projects 117
Answers to Quick-Check Exercises 119
Chaining 340
Performance of Hash Tables 340
Exercises for Section 7.3 342
7.4 Implementing the Hash Table 344
Interface KWHashMap 344
Class Entry 344
Class HashtableOpen 345
Class HashtableChain 350
Testing the Hash Table Implementations 353
Exercises for Section 7.4 354
7.5 Implementation Considerations for Maps and Sets 354
Methods hashCode and equals 354
Implementing HashSetOpen 355
Writing HashSetOpen as an Adapter Class 355
Implementing the Java Map and Set Interfaces 356
Interface Map.Entry and Class AbstractMap.SimpleEntry 356
Creating a Set View of a Map 357
Method entrySet and Classes EntrySet and SetIterator 357
Classes TreeMap and TreeSet 358
Exercises for Section 7.5 359
7.6 Additional Applications of Maps 359
Case Study: Implementing a Cell Phone Contact List 359
Case Study: Completing the Huffman Coding Problem 361
Encoding the Huffman Tree 365
Exercises for Section 7.6 366
7.7 Navigable Sets and Maps 366
Application of a NavigableMap 368
Exercises for Section 7.7 370
Java API Interfaces and Classes Introduced in This Chapter 372
User‐Defined Interfaces and Classes in This Chapter 372
Quick‐Check Exercises 372
Review Questions 372
Programming Projects 373
Answers to Quick-Check Exercises 374
Constructors 577
The No‐Parameter Constructor 577
Modifier and Accessor Methods 578
Use of this. in a Method 578
The Method toString 578
The Method equals 579
Declaring Local Variables in Class Person 580
An Application that Uses Class Person 580
Objects as Arguments 581
Classes as Components of Other Classes 582
Java Documentation Style for Classes and Methods 582
Exercises for Section A.7 585
A.8 Arrays 585
Data Field length 587
Method Arrays.copyOf 588
Method System.arrayCopy 588
Array Data Fields 589
Array Results and Arguments 590
Arrays of Arrays 590
Exercises for Section A.8 593
A.9 Enumeration Types 594
Using Enumeration Types 595
Assigning Values to Enumeration Types 596
Exercises for Section A.9 596
A.10 I/O Using Streams, Class Scanner, and Class JOptionPane 596
The Scanner 597
Using a Scanner to Read from a File 599
Exceptions 599
Tokenized Input 599
Extracting Tokens Using Scanner.findInLine 600
Using a BufferedReader to Read from an Input Stream 600
Output Streams 600
Passing Arguments to Method main 600
Closing Streams 601
Try with Resources 601
A Complete File‐Processing Application 601
Class InputStream and Character Codes (Optional) 603
The Default Character Coding (Optional) 603
UTF‐8 (Optional) 604
Specifying a Character Encoding (Optional) 605
Input/Output Using Class JOptionPane 605
Converting Numeric Strings to Numbers 606
GUI Menus Using Method showOptionDialog 607
Exercises for Section A.10 607
A.11 Catching Exceptions 608
Catching and Handling Exceptions 608
Exercises for Section A.11 614
A.12 Throwing Exceptions 614
The throws Clause 615
Glossary 635
Index 643
1
Object‐Oriented Programming
and Class Hierarchies
Chapter Objectives
◆ To learn about interfaces and their role in Java
◆ To understand inheritance and how it facilitates code reuse
◆ To understand how Java determines which method to execute when there are multiple
methods with the same name in a class hierarchy
◆ To become familiar with the Exception hierarchy and the difference between checked and
unchecked exceptions
◆ To learn how to define and use abstract classes as base classes in a hierarchy
◆ To learn the role of abstract data types and how to specify them using interfaces
◆ To study class Object and its methods and to learn how to override them
◆ To become familiar with a class hierarchy for shapes
◆ To understand how to create packages and to learn more about visibility
Interfaces
A Java interface is a way to specify or describe an ADT to an applications programmer. An
interface is like a contract that tells the applications programmer precisely what methods are
available and describes the operations they perform. It also tells the applications programmer
what arguments, if any, must be passed to each method and what result the method will
return. Of course, in order to make use of these methods, someone else must have written a
class that implements the interface by providing the code for these methods.
The interface tells the coder precisely what methods must be written, but it does not provide
a detailed algorithm or prescription for how to write them. The coder must “program to the
interface,” which means he or she must develop the methods described in the interface with-
out variation. If each coder does this job well, that ensures that other programmers can use
the completed class exactly as it is written, without needing to know the details of how it was
coded.
There may be more than one way to implement the methods; hence, several classes may
implement the interface, but each must satisfy the contract. One class may be more efficient
than the others at performing certain kinds of operations (e.g., retrieving information from a
database), so that class will be used if retrieval operations are more likely in a particular
application. The important point is that the particular implementation that is used will not
affect other classes that interact with it because every implementation satisfies the contract.
Besides providing the complete definition (implementation) of all methods declared in the
interface, each implementer of an interface may declare data fields and define other methods
not in the interface, including constructors. An interface cannot contain constructors because
it cannot be instantiated—that is, one cannot create objects, or instances, of it. However, it
can be represented by instances of classes that implement it.
E X A M P L E 1. 1 An automated teller machine (ATM) enables a user to perform certain banking operations
from a remote location. It must support the following operations.
1. Verify a user’s Personal Identification Number (PIN).
2. Allow the user to choose a particular account.
3. Withdraw a specified amount of money.
4. Display the result of an operation.
5. Display an account balance.
A class that implements an ATM must provide a method for each operation. We can write
this requirement as the interface ATM and save it in file ATM.java, shown in Listing 1.1. The
keyword interface on the header line indicates that an interface is being declared. If you are
unfamiliar with the documentation style shown in this listing, read about Java documenta-
tion at the end of Section A.7 in Appendix A.
LISTING 1.1
Interface ATM.java
/** The interface for an ATM. */
public interface ATM {
String selectAccount();
The interface definition shows the heading only for several methods. Because only the head-
ings are shown, they are considered abstract methods. Each actual method with its body must
be defined in a class that implements the interface. Therefore, a class that implements this
interface must provide a void method called verifyPIN with an argument of type String.
There are also two display methods with different signatures. The first is used to display the
result of a withdrawal, and the second is used to display the result of a PIN verification. The
keywords public abstract are optional (and usually omitted) in an interface because all
interface methods are public abstract by default.
EXAMPLE:
public interface Payable {
public abstract double calcSalary();
public abstract boolean salaried();
public static final double DEDUCTIONS = 25.5;
}
MEANING:
Interface interfaceName is defined. The interface body provides headings for abstract
methods and constant declarations. Each abstract method must be defined in a class
that implements the interface. Constants defined in the interface (e.g., DEDUCTIONS) are
accessible in classes that implement the interface or in the same way as static fields
and methods in classes (see Section A.4).
NOTES:
The keywords public and abstract are implicit in each abstract method declaration,
and the keywords public static final are implicit in each constant declaration. We
show them in the example here, but we will omit them from now on.
Java 8 also allows for static and default methods in interfaces. They are used to add
features to existing classes and interfaces while minimizing the impact on existing
programs. We will discuss default and static methods when describing where they are
used in the API.
Each class heading ends with the clause implements ATM. When compiling these classes, the
Java compiler will verify that they define the required methods in the way specified by the
interface. If a class implements more than one interface, list them all after implements, with
commas as separators.
Figure 1.2 is a UML (Unified Modeling Language) diagram that shows the ATM interface
and these two implementing classes. Note that a dashed line from the class to the interface is
used to indicate that the class implements the interface. We will use UML diagrams through-
out this text to show relationships between classes and interfaces. Appendix B provides
detailed coverage of UML diagrams.
FIGURE 1.2
UML Diagram Showing the ATM Interface and Its Implementing Classes
‹‹interface››
ATM
boolean verifyPIN(String pin)
String selectAccount()
boolean withdraw(String account, double amount)
void display(String account, double amount, boolean success)
void display(String pin, boolean success)
void showBalance(String account)
ATMbankAmerica ATMforAllBanks
P I T FA L L
Not Properly Defining a Method to Be Implemented
If you neglect to define method verifyPIN in class ATMforAllBanks or if you use a
different method signature, you will get the following syntax error:
class ATMforAllBanks should be declared abstract; it does not define method
verifyPIN(String) in interface ATM.
The above error indicates that the method verifyPin was not properly defined.
Because it contains an abstract method that is not defined, Java incorrectly believes
that ATM should be declared to be an abstract class. If you use a result type other than
boolean, you will also get a syntax error.
P I T FA L L
Instantiating an Interface
An interface is not a class, so you cannot instantiate an interface. The statement
ATM anATM = new ATM(); // invalid statement
will cause the following syntax error:
interface ATM is abstract; cannot be instantiated.
PROGRAMMING
1. Define an interface named Resizable with just one abstract method, resize, that is a void
method with no parameter.
2. Write a Javadoc comment for the following method of a class Person. Assume that class
Person has two String data fields familyName and givenName with the obvious meanings.
Provide preconditions and postconditions if needed.
public int compareTo(Person per) {
if (familyName.compareTo(per.familyName) == 0)
return givenName.compareTo(per.givenName);
else
return familyName.compareTo(per.familyName);
}
3. Write a Javadoc comment for the following method of class Person. Provide preconditions
and postconditions if needed.
public void changeFamilyName(boolean justMarried, String newFamily) {
if (justMarried)
familyName = newFamily;
}
4. Write method verifyPIN for class ATMbankAmerica assuming this class has a data field pin
(type String).
an inheritance of monetary value. As we grow up, we benefit from our ancestors’ resources,
FIGURE 1.3
Classes Mammal and knowledge, and experiences, but our experiences will not affect how our parents or ancestors
Human developed. Although we have two parents to inherit from, Java classes can have only one
parent.
Mammal
Inheritance and hierarchical organization allow you to capture the idea that one thing may be
a refinement or an extension of another. For example, an object that is a Human is a Mammal (the
drinkMothersMilk()
superclass of Human). This means that an object of type Human has all the data fields and meth-
ods defined by class Mammal (e.g., method drinkMothersMilk), but it may also have more data
Human fields and methods that are not contained in class Mammal (e.g., method thinkCreatively).
Figure 1.3 shows this simple hierarchy. The solid line in the UML class diagram shows that
thinkCreatively() Human is a subclass of Mammal, and, therefore, Human objects can use methods drinkMothersMilk
and thinkCreatively. Objects farther down the hierarchy are more complex and less general
than those farther up. For this reason an object that is a Human is a Mammal, but the converse is
not true because every Mammal object does not necessarily have the additional properties of a
Human. Although this seems counterintuitive, the subclass Human is actually more powerful
FIGURE 1.4 than the superclass Mammal because it may have additional attributes that are not present in
Classes NoteBook and
the superclass.
Computer
LISTING 1.2
Class Computer.java
/** Class that represents a computer. */
public class Computer {
// Data Fields
private String manufacturer;
private String processor;
private double ramSize;
private int diskSize;
private double processorSpeed;
// Methods
/** Initializes a Computer object with all properties specified.
@param man The computer manufacturer
@param processor The processor type
@param ram The RAM size
@param disk The disk size
@param procSpeed The processor speed
*/
public Computer(String man, String processor, double ram,
int disk, double procSpeed) {
manufacturer = man;
this.processor = processor;
ramSize = ram;
diskSize = disk;
processorSpeed = procSpeed;
}
Use of this.
In the constructor for the Computer class, the statement
this.processor = processor;
sets data field processor in the object under construction to reference the same string as
parameter processor. The prefix this. makes data field processor visible in the constructor.
This is necessary because the declaration of processor as a parameter hides the data field
declaration.
P I T FA L L
Not Using this. to Access a Hidden Data Field
If you write the preceding statement as
processor = processor; // Copy parameter processor to itself.
you will not get an error, but the data field processor in the Computer object under
construction will not be initialized and will retain its default value (null). If you later
attempt to use data field processor, you may get an error or just an unexpected result.
Some IDEs will provide a warning if this. is omitted.
Class Notebook
In theNotebook class diagram in Figure 1.4, we show just the data fields declared in class
Notebook; however, Notebook objects also have the data fields that are inherited from class
Computer (processor, ramSize, and so forth). The first line in class Notebook (Listing 1.3),
public class Notebook extends Computer {
indicates that class Notebook extends class Computer and inherits its data and methods. Next,
we define any additional data fields
// Data Fields
private double screenSize;
private double weight;
SYNTAX super( . . . );
FORM:
super();
super(argumentList);
EXAMPLE:
super(man, proc, ram, disk, procSpeed);
MEANING:
The super() call in a class constructor invokes the superclass’s constructor that has
the corresponding argumentList. The superclass constructor initializes the inherited
data fields as specified by its argumentList. The super() call must be the first
statement in a constructor.
LISTING 1.3
Class Notebook
// Methods
/** Initializes a Notebook object with all properties specified.
@param man The computer manufacturer
@param proc The processor type
@param ram The RAM size
P I T FA L L
Not Defining the No‐Parameter Constructor
If no constructors are defined for a class, the no‐parameter constructor for that class
will be provided by default. However, if any constructors are defined, the no‐parameter
constructor must also be defined explicitly if it needs to be invoked. Java does not
provide it automatically because it may make no sense to create a new object of that
type without providing initial data field values. (It was not defined in class Notebook or
Computer because we want the client to specify some information about a Computer
object when that object is created.) If the no‐parameter constructor is defined in a
subclass but is not defined in the superclass, you will get a syntax error constructor
not defined. You can also get this error if a subclass constructor does not explicitly call
a superclass constructor. There will be an implicit call to the no‐parameter superclass
constructor, so it must be defined.
We will use protected visibility on occasion when we are writing a class that we intend to
extend. However, in general, it is better to use private visibility because subclasses may be
written by different programmers, and it is always a good practice to restrict and control
access to the superclass data fields. We discuss visibility further in Section 1.7.
Another issue that sometimes arises is determining whether to define a new class in a hierarchy
or whether a new object is a member of an existing class. For example, netbook computers have
recently become very popular. They are smaller portable computers that can be used for general‐
purpose computing but are also used extensively for Web browsing. Should we define a separate
class NetBook, or is a netbook computer a Notebook object with a small screen and low weight?
2. Indicate where in the hierarchy you might want to add data fields for the following and
the kind of data field you would add.
Cost
The battery identification
Time before battery discharges
Number of expansion slots
Wireless Internet available
3. Can you add the following constructor to class Notebook? If so, what would you need to
do to class Computer?
public Notebook() {}
PROGRAMMING
1. Write accessor and modifier methods for class Computer.
2. Write accessor and modifier methods for class Notebook.
Method Overriding
Let’s use the following main method to test our class hierarchy.
/** Tests classes Computer and Notebook. Creates an object of each and
displays them.
@param args[] No control parameters
*/
public static void main(String[] args) {
Computer myComputer =
new Computer("Acme", "Intel", 4, 750, 3.5);
Notebook yourComputer =
new Notebook("DellGate", "AMD", 4, 500,
2.4, 15.0, 7.5);
System.out.println("My computer is:\n" + myComputer.toString());
System.out.println("\nYour computer is:\n" +
yourComputer.toString());
}
In the second call to println, the method call
yourComputer.toString()
applies method toString to object yourComputer (type Notebook). Because class Notebook
doesn’t define its own toString method, class Notebook inherits the toString method defined
in class Computer. Executing this method displays the following output lines:
My computer is:
Manufacturer: Acme
CPU: Intel
RAM: 4.0 gigabytes
Disk: 750 gigabytes
Speed: 3.5 gigahertz
Your computer is:
Manufacturer: DellGate
CPU: AMD
RAM: 4.0 gigabytes
Disk: 500 gigabytes
Speed: 2.4 gigahertz
Unfortunately, this output doesn’t show the complete state of object yourComputer. To show
the complete state of a notebook computer, we need to define a toString method for class
Notebook. If class Notebook has its own toString method, it will override the inherited method
and will be invoked by the method call yourComputer.toString(). We define method toString
for class Notebook next.
public String toString() {
String result = super.toString() +
"\nScreen size: " + screenSize + " inches" +
"\nWeight: " + weight + " pounds";
return result;
}
SYNTAX super.
FORM:
super.methodName()
super.methodName(argumentList)
EXAMPLE:
super.toString()
MEANING:
Using the prefix super. in a call to method methodName calls the method with that
name defined in the superclass of the current class.
PROGRAM STYLE
Calling Method toString() Is Optional
In the println statement shown earlier,
System.out.println("My computer is:\n" + myComputer.toString());
the explicit call to method toString is not required. The statement could be written as
System.out.println("My computer is:\n" + myComputer);
Java automatically applies the toString method to an object referenced in a String
expression. Normally, we will not explicitly call toString.
P I T FA L L
Overridden Methods Must Have Compatible Return Types
If you write a method in a subclass that has the same signature as one in the
superclass but a different return type, you may get the following error message: in
subclass‐name cannot override method‐name in superclass‐name; attempting to use
incompatible return type. The subclass method return type must be the same as or a
subclass of the superclass method’s return type.
Method Overloading
Let’s assume we have decided to standardize and purchase our notebook computers from
only one manufacturer. We could then introduce a new constructor with one less parameter
for class Notebook.
public Notebook(String proc, int ram, int disk, double procSpeed,
double screen, double wei) {
this(DEFAULT_NB_MAN, proc, ram, disk, procSpeed, screen, wei);
}
SYNTAX this( . . . );
FORM:
this(argumentList);
EXAMPLE:
this(DEFAULT_NB_MAN, proc, ram, disk, procSpeed);
MEANING:
The call to this() invokes the constructor for the current class whose parameter list
matches the argument list. The constructor initializes the new object as specified by its
arguments. The invocation of another constructor (through either this() or super())
must be the first statement in a constructor.
Listing 1.4 shows the complete class Notebook. Figure 1.5 shows the UML diagram, revised
to show that Notebook has a toString method and a constant data field. The next Pitfall dis-
cusses the reason for the @Override annotation preceding method toString.
LISTING 1.4
Complete Class Notebook with Method toString
P I T FA L L
Overloading a Method When Intending to Override It
To override a method, you must use the same name and the same number and types
of the parameters as the superclass method that is being overridden. If the name is
the same but the number or types of the parameters are different, then the method is
overloaded instead. Normally, the compiler will not detect this as an error. However, it
is a sufficiently common error that a feature was added to the Java compiler so that
programmers can indicate that they intend to override a method. If you precede the
declaration of the method with the annotation @Override, the compiler will issue an
error message if the method is overloaded instead of overridden.
PROGRAM STYLE
Precede an Overridden Method with the Annotation @Override
Whenever a method is overridden, we recommend preceding it with the annotation
@Override. Some Java integrated development environments such as Netbeans and
Eclipse will either issue a warning or add this annotation automatically.
Polymorphism
An important advantage of OOP is that it supports a feature called polymorphism, which
means many forms or many shapes. Polymorphism enables the JVM to determine at run time
which of the classes in a hierarchy is referenced by a superclass variable or parameter. Next
we will see how this simplifies the programming process.
Suppose you are not sure whether a computer referenced in a program will be a notebook or
a regular computer. If you declare the reference variable
Computer theComputer;
you can use it to reference an object of either type because a type Notebook object can be
referenced by a type Computer variable. In Java, a variable of a superclass type (general) can
reference an object of a subclass type (specific). Notebook objects are Computer objects with
more features. When the following statements are executed,
theComputer = new Computer("Acme", "Intel", 2, 160, 2.6);
System.out.println(theComputer.toString());
you would see four output lines, representing the state of the object referenced by
theComputer.
Now suppose you have purchased a notebook computer instead. What happens when the
following statements are executed?
theComputer = new Notebook("Bravo", "Intel", 4, 240, 2.4. 15.0, 7.5);
System.out.println(theComputer.toString());
Recall that theComputer is type Computer. Will the theComputer.toString() method call return a
string with all seven data fields or just the five data fields defined for a Computer object? The
answer is a string with all seven data fields. The reason is that the type of the object receiving the
toString message determines which toString method is called. Even though variable theComputer
is type Computer, it references a type Notebook object, and the Notebook object receives the
toString message. Therefore, the method toString for class Notebook is the one called.
2. Indicate whether methods with each of the following signatures and return types (if any)
would be allowed and in what classes they would be allowed. Explain your answers.
Computer()
Notebook()
int toString()
double getRamSize()
String getRamSize()
String getRamSize(String)
String getProcessor()
double getScreenSize()
3. For the loop body in the following fragment, indicate which method is invoked for each
value of i. What is printed?
Computer comp[] = new Computer[3];
comp[0] = new Computer("Ace", "AMD", 8, 750, 3.5);
comp[1] = new Notebook("Dell", "Intel", 4, 500, 2.2, 15.5, 7.5);
comp[2] = comp[1];
for (int i = 0; i < comp.length; i++) {
System.out.println(comp[i].getRamSize() + "\n" +
comp[i].toString());
}
4. When does Java determine which toString method to execute for each value of i in the
for statement in the preceding question: at compile time or at run time? Explain your
answer.
PROGRAMMING
1. Write constructors for both classes that allow you to specify only the processor, RAM size,
and disk size.
2. Complete the accessor and modifier methods for class Computer.
3. Complete the accessor and modifier methods for class Notebook.
E X A M P L E 1. 4 The Food Guide Pyramid provides a recommendation of what to eat each day based on
established dietary guidelines. There are six categories of foods in the pyramid: fats, oils, and
sweets; meats, poultry, fish, and nuts; milk, yogurt, and cheese; vegetables; fruits; and bread,
cereal, and pasta. If we wanted to model the Food Guide Pyramid, we might have each of
these as actual subclasses of an abstract class called Food:
/** Abstract class that models a kind of food. */
public abstract class Food {
// Data Field
private double calories;
// Abstract Methods
/** Calculates the percent of protein in a Food object. */
// Actual Methods
public double getCalories() { return calories; }
public void setCalories(double cal) {
calories = cal;
}
}
// Abstract Methods
public abstract double percentProtein();
public abstract double percentFat();
public abstract double percentCarbohydrates();
// Actual Methods
public double getCalories() { return calories; }
public void setCalories(double cal) {
calories = cal;
}
}
INTERPRETATION:
Abstract class className is defined. The class body may have declarations for data
fields and abstract methods as well as actual method definitions. Each abstract
method declaration consists of a method heading containing the keyword abstract.
All of the declaration kinds shown above are optional.
P I T FA L L
Omitting the Definition of an Abstract Method in a Subclass
If you write class Vegetable and forget to define method percentProtein, you will get
the syntax error class Vegetable should be declared abstract, it does not define
method percentProtein in class Food. Although this error message is misleading (you
did not intend Vegetable to be abstract), any class with undefined methods is abstract
by definition. The compiler’s rationale is that the undefined method is intentional, so
Vegetable must be an abstract class, with a subclass that defines percentProtein.
E X A M P L E 1. 5 The following statement creates a Vegetable object that is referenced by variable mySnack
(type Food).
Food mySnack = new Vegetable("carrot sticks");
Number
FIGURE 1.6
The Abstract Class
Number and Selected
Subclasses
Byte Double Integer Short
In the actual implementation of Number, the body of byteValue would be provided, but we
just indicate its presence in Listing 1.5.
LISTING 1.5
Part of Abstract Class java.lang.Number
public abstract class Number {
// Abstract Methods
/** Returns the value of the specified number as an int.
@return The numeric value represented by this object after
conversion to type int
*/
public abstract int intValue();
/** Returns the value of the specified number as a double.
@return The numeric value represented by this object
after conversion to type double
*/
public abstract double doubleValue();
...
// Actual Methods
/** Returns the value of the specified number as a byte.
@return The numeric value represented by this object
after conversion to type byte
*/
public byte byteValue() {
// Implementation not shown.
...
}
}
TA B L E 1 . 1
Comparison of Actual Classes, Abstract Classes, and Interfaces
An abstract class may implement an interface just as an actual class does, but unlike an actual
class, it doesn’t have to define all of the methods declared in the interface. It can leave the
implementation of some of the abstract methods to its subclasses.
Both abstract classes and interfaces declare abstract methods. However, unlike an interface,
an abstract class can also have data fields and methods that are not abstract. You can think
of an abstract class as combining the properties of an actual class, by providing inherited data
fields and methods to its subclasses, and of an interface, by specifying requirements on its
subclasses through its abstract method declarations.
Extending an Interface
Interfaces can also extend other interfaces. In Chapter 2 we will introduce the Java Collection
Framework. This class hierarchy contains several interfaces and classes that manage the col-
lection of objects. At the top of this hierarchy is the interface Iterable, which declares the
method iterator. At the next lower level is interface Collection, which extends Iterable.
This means that all classes that implement Collection must also implement Iterable and
therefore must define the method iterator.
An interface can extend more than one other interface. In this case, the resulting interface
includes the union of the methods defined in the superinterfaces. For example, we can define the
interface ComparableCollection, which extends both Comparable and Collection, as follows:
public interface ComparableCollection extends Comparable, Collection { }
Note that this interface does not define any methods itself but does require any implementing
class to implement all of the methods required by Comparable and by Collection.
4. What is the purpose of the if statement in the loop in Question 3? What would happen if
it were omitted?
PROGRAMMING
1. Write class
Vegetable. Assume that a vegetable has three double constants: VEG_FAT_CAL,
VEG_PROTEIN_CAL, and VEG_CARBO_CAL. Compute the fat percentage as VEG_FAT_CAL divided
by the sum of all the constants.
2. Earlier we discussed a Computer class with a Notebook class as its only subclass. However,
there are many different kinds of computers. An organization may have servers, main-
frames, desktop PCs, and notebooks. There are also personal data assistants and game
computers. So it may be more appropriate to declare class Computer as an abstract class
that has an actual subclass for each category of computer. Write an abstract class Computer
that defines all the methods shown earlier and declares an abstract method with the signa-
ture costBenefit(double) that returns the cost–benefit (type double) for each category of
computer.
E X A M P L E 1. 6 If we didn’t have a toString method in class Computer or Notebook, the method call aComputer.
toString() would call the toString method inherited from class Object. This method would
return a string such as Computer@ef08879, which shows the object’s class name and a special
integer value that is its “hash code”—not its state. Method hashCode is discussed in Chapter 7.
TA B L E 1 . 2
The Class Object
Method Behavior
boolean equals(Object obj) Compares this object to its argument
int hashCode() Returns an integer hash code value for this object
String toString() Returns a string that textually represents the object
Class<?> getClass() Returns a unique object that identifies the class of this object
Father Callaghan was with a man near this one time, one Tully, and
they were talking about the faeries and the man said he didn't
believe in them at all. And Father Callaghan called him to the door
and put up his fingers and bade him look out through them, and
there he saw hundreds and hundreds of the smallest little men he
ever saw and they hurling and killing one another.
The friars are gone and there are missioners come in their place and
all they would do for you is to bless holy water, and as long as you
would keep it, it would never get bad.
My daughter, Mrs. Meehan, that lives there below, was very bad
after her first baby being born, and she wasted away and the
doctors could do nothing for her. My husband went to Biddy Early for
her, but she said, "Mother for daughter, father for son" and she could
do nothing for her because I didn't go. But I had promised God and
the priest I would never go to her, and so I kept to my word. But
Mrs. Meehan was so bad she kept to the bed, and one day one of
the neighbours said I had a right to bring her to the friars at Esker.
And he said, "It's today you should be in it, Monday, for a Monday
gospel is the best, the gospel of the Holy Ghost." So I got the cart
after and put her in it, and she lying down, and we had to rest and
to take out the horse at Lenane, and we got to Craughwell for the
night. And the man of the house where we got lodging for the night
said the priest that was doing cures now was Father Blake and he
showed us the way to Esker. And when we got there he was in the
chapel, and my daughter was brought in and laid on a form, and I
went out and waited with the cart, and within half an hour the
chapel door opened, and my daughter walked out that was carried
in. And she got up on the cart herself. It was a gospel had been read
over her. And I said, "I wish you had asked a gospel to bring with
you home." And after that we saw a priest on the other side of a dry
stone wall, and he learning three children. And she asked a gospel of
him, and he said, "What you had today will do you, and I haven't
one made up at this time." So she came home well. She went
another time there, when she had something and asked for a
gospel, and Father Blake said, "We're out of doing it now, but as you
were with us before, I'll do it for you." And she wanted to give him
£1 but he said, "If I took it I would do nothing for you." So she said,
"I'll give it to the other man," and so she did.
I often saw Father Callaghan in Esker and the people brought to him
in carts. Many cures he did, but he was prevented often. And I knew
another priest did many cures, but he was carried away himself
after, to a lunatic asylum. And when he came back, he would do no
more.
There was a little chap had but seven years, and he was doing no
good, but whistling and twirling, and the father went to Father
Callaghan, that was just after coming out of the gaol when he got
there, for doing cures; it is a gaol of their own they had. The man
asked him to do a cure on his son, and Father Callaghan said, "I
wouldn't like him to be brought here, but I will go some day to your
house; I will go with my dog and my hound as if fowling, and I will
bring no sign of a car or a carriage at all." So he came one day to
the house and knocked at the door. And when he came in he said to
the father, "Go out and bring me in a bundle of sally rods that will be
as thin as rushes, and divide them into six small parts," he said,
"and twist every one of the six parts together." And when that was
done, he took the little bundle of rods, and he beat the child on the
head with them one after another till they were in flitters and the
child roaring. Then he laid the child in the father's arms, and no
sooner there than it fell asleep, and Father Callaghan said to the
father, "What you have now is your own, but it wasn't your own that
was in it before."
Priests can do cures if they will, and it's not out of the Gospel they
do them, but out of a book specially for the purpose, so I believe.
But something falls on them or on the things belonging to them, if
they do it too often.
But Father Keeley for certain did cures. It was he cured Mike
Madden's neck, when everyone else had failed—so they had—
though Mike has never confessed to it.
The priests can do cures surely, and surely they can put harm on
you. But they wouldn't do that unless they'd be sure a man would
deserve it. One time at that house you see up there beyond,
Roche's, there was a wedding and there was some fighting came out
of it, and bad blood. And Father Boyle was priest at that time, and
he was vexed and he said he'd come and have stations at the house,
and they should all be reconciled.
So he came on the day he appointed and the house was settled like
a chapel, and some of the people there was bad blood between
came, but not all of them, and Roche himself was not there. And
when the stations were over Father Boyle got his book, and he read
the names of those he had told to be there, and they answered, like
a schoolmaster would call out the names of his scholars. And when
Roche's name was read and he not there to answer, with the dint of
madness Father Boyle quenched the candles on the altar, and he
said this house and all that belong to it will go away to nothing, like
the froth that's going down the river.
And if you look at the house now you'll see the way it is, not a stable
or an outhouse left standing, and not one of the whole family left in
it but Roche, and he paralysed. So they can do both harm and good.
There was a man out in the mountains used to do cures, and one
day on a little road the priest met him, and stopped his car and
began to abuse him for the cures he was doing.
And then the priest went on, and when he had gone a bit of the
road his horse fell down. And he came back and called to the man
and said, "Come help me now, for this is your doing, to make the
horse fall." And the man said, "It's none of my doing, but it's the
doing of my master, for he was vexed with the way you spoke. But
go back now and you'll find the horse as he was before." So he went
back and the horse had got up and was standing, and nothing
wrong with him at all. And the priest said no more against him from
that day.
My son is lame this long time; a fine young man he was, about
seventeen years—and a pain came in his knee all of a moment. I
tried doctors with him and I brought him to the friars in Loughrea,
and one of them read a gospel over him, and the pain went after
that, but the knee grew out to be twisted like. The friar said it was
surely he had been overheated. A little old maneen he was, very
ancient. I knew well it was the drochuil that did it; there by the side
of the road he was sitting when he got the frost.
There was a needlewoman used to be sewing late on a Saturday
night, and sometimes if there was a button or a thread wanting she
would put it in, even if it was Sunday morning; and she lived in
Loughrea that is near your own home. And one day she went to the
loch to get a can of water, and it was in her hand. And in a minute a
blast of wind came that rose all the dust and the straws and knocked
herself. And more than that, her mouth was twisted around to her
poll.
There were some people saw her, and they brought her home, and
within a week her mother brought her to the priest. And when he
saw her he said, "You are the best mother ever there was, for if you
had left her nine days without bringing her to me, all I could do
would not have taken off her what is on her." He asked then up to
what time did she work on the Saturday night, and she said up to
one or two o'clock, and sometimes on a Sunday morning. So he took
off what was on her, and bade her do that no more, and she got
well, but to the last there was a sort of a twisted turn in her mouth.
That woman now I am telling you of was an aunt of my own.
Father Nolan has a kind heart, and he'd do cures. But it's hard to get
them, unless it would be for some they had a great interest in. But
Father McConaghy is so high in himself, he wouldn't do anything of
that sort. When Johnny Dunne was bad, two years ago, and all but
given over, he begged and prayed Father McConaghy to do it for
him. And he refused and said, "You must commit yourself to the
mercy of Almighty God," and Johnny Dunne, the poor man, said,
"It's a hard thing for a man that has a house full of children to be
left to the mercy of Almighty God."
But there's some that can help. My father told me long ago that my
sister was lying sick for a long time, and one night a beggarman
came to the door and asked for shelter. And he said, "I can't give
you shelter, with my daughter lying sick in the room." "Let me in, it's
best for you," says he. And in the morning he went away, and the
sick girl rose up, as well as ever she was before.
Father Flaherty, when he was a curate, could open the eyes that
were all but closed in death, but he wouldn't have such things
spoken of now. Losses they may have, but that's not all. Whatever
evil thing they raise, they may not have strength after to put it down
again, and so they may be lost themselves in the end.
Surely they can do cures, and they can tell sometimes the hour
you'd go. There was a girl I knew was sick, and when the priest
came and saw her, he said, "Between the two Masses tomorrow
she'll be gone," and so she was. And those that saw her after, said
that it was the face of her mother that died before that was on the
bed, and that it was her mother had taken her to where she was.
And Mike Barrett surely saw a man brought in a cart to Father
Curley's house when he lived in Cloon, and carried upstairs to him,
and he walked down out of the house again, sound and well. But
they must lose something when they do cures—either their health or
something else, though many say no one did so many cures as
Father Fitzgerald when he was a curate. Father Airlie one time was
called in to Glover's house where he was lying sick, and did a cure
on him. And he had a cow at the time that was in calf. And soon
after some man said to him "The cow will be apt soon to calve,"
though it wasn't very near the time. And Father Airlie said "She'll
never live to do that." And sure enough in a couple of days after she
was dead.
SWEDENBORG, MEDIUMS,
AND THE DESOLATE PLACES
SWEDENBORG, MEDIUMS, AND THE
DESOLATE PLACES
I
Some fifteen years ago I was in bad health and could not work, and
Lady Gregory brought me from cottage to cottage while she began
to collect the stories in this book, and presently when I was at work
again she went on with her collection alone till it grew to be, so far
as I know, the most considerable book of its kind. Except that I had
heard some story of "The Battle of the Friends" at Aran and had
divined that it might be the legendary common accompaniment of
death, she was not guided by any theory of mine, but recorded what
came, writing it out at each day's end and in the country dialect. It
was at this time mainly she got the knowledge of words that makes
her little comedies of country life so beautiful and so amusing. As
that ancient system of belief unfolded before us, with unforeseen
probabilities and plausibilities, it was as though we had begun to live
in a dream, and one day Lady Gregory said to me when we had
passed an old man in the wood: "That old man may know the secret
of the ages."
I had noticed many analogies in modern spiritism and began a more
careful comparison, going a good deal to séances for the first time
and reading all writers of any reputation I could find in English or
French. I found much that was moving, when I had climbed to the
top story of some house in Soho or Holloway, and, having paid my
shilling, awaited, among servant girls, the wisdom of some fat old
medium. That is an absorbing drama, though if my readers begin to
seek it they will spoil it, for its gravity and simplicity depends on all,
or all but all, believing that their dead are near.
I did not go there for evidence of the kind the Society for Psychical
Research would value, any more than I would seek it in Galway or in
Aran. I was comparing one form of belief with another, and like
Paracelsus, who claimed to have collected his knowledge from
midwife and hangman, I was discovering a philosophy. Certain
things had happened to me when alone in my own room which had
convinced me that there are spiritual intelligences which can warn us
and advise us, and, as Anatole France has said, if one believes that
the Devil can walk the streets of Lisbon, it is not difficult to believe
that he can reach his arm over the river and light Don Juan's
cigarette. And yet I do not think I have been easily convinced, for I
know we make a false beauty by a denial of ugliness and that if we
deny the causes of doubt we make a false faith, and that we must
excite the whole being into activity if we would offer to God what is,
it may be, the one thing germane to the matter, a consenting of all
our faculties. Not but that I doubt at times, with the animal doubt of
the Middle Ages that I have found even in pious countrywomen
when they have seen some life come to an end like the stopping of a
clock, or that all the perceptions of the soul, or the weightiest
intellectual deductions, are not at whiles but a feather in the daily
show.
I pieced together stray thoughts written out after questioning the
familiar of a trance medium or automatic writer, by Allen Cardec, or
by some American, or by myself, or arranged the fragments into
some pattern, till I believed myself the discoverer of a vast
generalization. I lived in excitement, amused to make Holloway
interpret Aran, and constantly comparing my discoveries with what I
have learned of mediæval tradition among fellow students, with the
reveries of a Neo-platonist, of a seventeenth-century Platonist, of
Paracelsus or a Japanese poet. Then one day I opened The Spiritual
Diary of Swedenborg, which I had not taken down for twenty years,
and found all there, even certain thoughts I had not set on paper
because they had seemed fantastic from the lack of some traditional
foundation. It was strange I should have forgotten so completely a
writer I had read with some care before the fascination of Blake and
Boehme had led me away.
II
It was indeed Swedenborg who affirmed for the modern world, as
against the abstract reasoning of the learned, the doctrine and
practice of the desolate places, of shepherds and of midwives, and
discovered a world of spirits where there was a scenery like that of
earth, human forms, grotesque or beautiful, senses that knew
pleasure and pain, marriage and war, all that could be painted upon
canvas, or put into stories to make one's hair stand up. He had
mastered the science of his time, he had written innumerable
scientific works in Latin, had been the first to formulate the nebular
hypothesis and wrote a cold abstract style, the result it may be of
preoccupation with stones and metals, for he had been assessor of
mines to the Swedish Government, and of continual composition in a
dead language.
In his fifty-eighth year he was sitting in an inn in London, where he
had gone about the publication of a book, when a spirit appeared
before him who was, he believed, Christ himself, and told him that
henceforth he could commune with spirits and angels. From that
moment he was a mysterious man describing distant events as if
they were before his eyes, and knowing dead men's secrets, if we
are to accept testimony that seemed convincing to Emmanuel Kant.
The sailors who carried him upon his many voyages spoke of the
charming of the waves and of favouring winds that brought them
sooner than ever before to their journey's end, and an ambassador
described how a queen, he himself looking on, fainted when
Swedenborg whispered in her ear some secret known only to her
and to her dead brother. And all this happened to a man without
egotism, without drama, without a sense of the picturesque, and
who wrote a dry language, lacking fire and emotion, and who to
William Blake seemed but an arranger and putter away of the old
Church, a Samson shorn by the churches, an author not of a book,
but of an index. He considered heaven and hell and God, the angels,
the whole destiny of man, as if he were sitting before a large table in
a Government office putting little pieces of mineral ore into small
square boxes for an assistant to pack away in drawers.
All angels were once men, he says, and it is therefore men who have
entered into what he calls the Celestial State and become angels,
who attend us immediately after death, and communicate to us their
thoughts, not by speaking, but by looking us in the face as they sit
beside the head of our body. When they find their thoughts are
communicated they know the time has come to separate the
spiritual from the physical body. If a man begins to feel that he can
endure them no longer, as he doubtless will, for in their presence he
can think and feel but sees nothing, lesser angels who belong to
truth more than to love take their place and he is in the light again,
but in all likelihood these angels also will be too high and he will slip
from state to state until he finds himself after a few days "with those
who are in accord with his life in the world; with them he finds his
life, and, wonderful to relate, he then leads a life similar to that he
led in the world." This first state of shifting and readjustment seems
to correspond with a state of sleep more modern seers discover to
follow upon death. It is characteristic of his whole religious system,
the slow drifting of like to like. Then follows a period which may last
but a short time or many years, while the soul lives a life so like that
of the world that it may not even believe that it has died, for "when
what is spiritual touches and sees what is spiritual the effect is the
same as when what is natural touches what is natural." It is the
other world of the early races, of those whose dead are in the rath
or the faery hill, of all who see no place of reward and punishment
but a continuance of this life, with cattle and sheep, markets and
war. He describes what he has seen, and only partly explains it, for,
unlike science which is founded upon past experience, his work, by
the very nature of his gift, looks for the clearing away of obscurities
to unrecorded experience. He is revealing something and that which
is revealed, so long as it remains modest and simple, has the same
right with the child in the cradle to put off to the future the
testimony of its worth. This earth-resembling life is the creation of
the image-making power of the mind, plucked naked from the body,
and mainly of the images in the memory. All our work has gone with
us, the books we have written can be opened and read or put away
for later use, even though their print and paper have been sold to
the buttermen; and reading his description one notices, a discovery
one had thought peculiar to the last generation, that the "most
minute particulars which enter the memory remain there and are
never obliterated," and there as here we do not always know all that
is in our memory, but at need angelic spirits who act upon us there
as here, widening and deepening the consciousness at will, can draw
forth all the past, and make us live again all our transgressions and
see our victims "as if they were present, together with the place,
words, and motives"; and that suddenly, "as when a scene bursts
upon the sight" and yet continues "for hours together," and like the
transgressions, all the pleasure and pain of sensible life awaken
again and again, all our passionate events rush up about us and not
as seeming imagination, for imagination is now the world. And yet
another impulse comes and goes, flitting through all, a preparation
for the spiritual abyss, for out of the celestial world, immediately
beyond the world of form, fall certain seeds as it were that exfoliate
through us into forms, elaborate scenes, buildings, alterations of
form that are related by "correspondence" or "signature" to celestial
incomprehensible realities. Meanwhile those who have loved or
fought see one another in the unfolding of a dream, believing it may
be that they wound one another or kill one another, severing arms or
hands, or that their lips are joined in a kiss, and the countryman has
need but of Swedenborg's keen ears and eagle sight to hear a noise
of swords in the empty valley, or to meet the old master hunting
with all his hounds upon the stroke of midnight among the moonlit
fields. But gradually we begin to change and possess only those
memories we have related to our emotion or our thought; all that
was accidental or habitual dies away and we begin an active present
life, for apart from that calling up of the past we are not punished or
rewarded for our actions when in the world but only for what we do
when out of it. Up till now we have disguised our real selves and
those who have lived well for fear or favour have walked with holy
men and women, and the wise man and the dunce have been
associated in common learning, but now the ruling love has begun
to remake circumstance and our body.
Swedenborg had spoken with shades that had been learned
Latinists, or notable Hebrew scholars, and found, because they had
done everything from the memory and nothing from thought and
emotion, they had become but simple men. We have already met
our friends, but if we were to meet them now for the first time we
should not recognize them, for all has been kneaded up anew,
arrayed in order and made one piece. "Every man has many loves,
but still they all have reference to his ruling love and make one with
it or together compose it," and our surrender to that love, as to
supreme good, is no new thought, for Villiers de l'Isle Adam quotes
Thomas Aquinas as having said, "Eternity is the possession of one's
self, as in a single moment." During the fusing and rending man flits,
as it were, from one flock of the dead to another, seeking always
those who are like himself, for as he puts off disguise he becomes
unable to endure what is unrelated to his love, even becoming
insane among things that are too fine for him.
So heaven and hell are built always anew and in hell or heaven all
do what they please and all are surrounded by scenes and
circumstance which are the expression of their natures and the
creation of their thought. Swedenborg because he belongs to an
eighteenth century not yet touched by the romantic revival feels
horror amid rocky uninhabited places, and so believes that the evil
are in such places while the good are amid smooth grass and garden
walks and the clear sunlight of Claude Lorraine. He describes all in
matter-of-fact words, his meeting with this or that dead man, and
the place where he found him, and yet we are not to understand
him literally, for space as we know it has come to an end and a
difference of state has begun to take its place, and wherever a
spirit's thought is, the spirit cannot help but be. Nor should we think
of spirit as divided from spirit, as men are from each other, for they
share each other's thoughts and life, and those whom he has called
celestial angels, while themselves mediums to those above,
commune with men and lower spirits, through orders of mediatorial
spirits, not by a conveyance of messages, but as though a hand
were thrust within a hundred gloves,[1] one glove outside another,
and so there is a continual influx from God to man. It flows to us
through the evil angels as through the good, for the dark fire is the
perversion of God's life and the evil angels have their office in the
equilibrium that is our freedom, in the building of that fabulous
bridge made out of the edge of a sword.
To the eyes of those that are in the high heaven "all things laugh,
sport, and live," and not merely because they are beautiful things
but because they arouse by a minute correspondence of form and
emotion the heart's activity, and being founded, as it were, in this
changing heart, all things continually change and shimmer. The
garments of all befit minutely their affections, those that have most
wisdom and most love being the most nobly garmented, in
ascending order from shimmering white, through garments of many
colours and garments that are like flame, to the angels of the
highest heaven that are naked.
In the west of Ireland the country people say that after death every
man grows upward or downward to the likeness of thirty years,
perhaps because at that age Christ began his ministry, and stays
always in that likeness; and these angels move always towards "the
springtime of their life" and grow more and more beautiful, "the
more thousand years they live," and women who have died infirm
with age, and yet lived in faith and charity, and true love towards
husband or lover, come "after a succession of years" to an
adolescence that was not in Helen's Mirror, "for to grow old in
heaven is to grow young."
There went on about Swedenborg an intermittent "Battle of the
Friends" and on certain occasions had not the good fought upon his
side, the evil troop, by some carriage accident or the like, would
have caused his death, for all associations of good spirits have an
answering mob, whose members grow more hateful to look on
through the centuries. "Their faces in general are horrible, and
empty of life like corpses, those of some are black, of some fiery like
torches, of some hideous with pimples, boils, and ulcers; with many
no face appears, but in its place a something hairy or bony, and in
some one can but see the teeth." And yet among themselves they
are seeming men and but show their right appearance when the
light of heaven, which of all things they most dread, beats upon
them; and seem to live in a malignant gaiety, and they burn always
in a fire that is God's love and wisdom, changed into their own
hunger and misbelief.
III
In Lady Gregory's stories there is a man who heard the newly
dropped lambs of faery crying in November, and much evidence to
show a topsy-turvydom of seasons, our spring being their autumn,
our winter their summer, and Mary Battle, my Uncle George
Pollexfen's old servant, was accustomed to say that no dream had a
true meaning after the rise of the sap; and Lady Gregory learned
somewhere on Sleive Ochta that if one told one's dreams to the
trees fasting the trees would wither. Swedenborg saw some like
opposition of the worlds, for what hides the spirits from our sight
and touch, as he explains, is that their light and heat are darkness
and cold to us and our light and heat darkness and cold to them, but
they can see the world through our eyes and so make our light their
light. He seems however to warn us against a movement whose
philosophy he announced or created, when he tells us to seek no
conscious intercourse with any that fall short of the celestial rank. At
ordinary times they do not see us or know that we are near, but
when we speak to them we are in danger of their deceits. "They
have a passion for inventing," and do not always know that they
invent. "It has been shown me many times that the spirits speaking
with me did not know but that they were the men and women I was
thinking of; neither did other spirits know the contrary. Thus
yesterday and today one known of me in life was personated. The
personation was so like him in all respects, so far as known to me,
that nothing could be more like. For there are genera and species of
spirits of similar faculty (? as the dead whom we seek), and when
like things are called up in the memory of men and so are
represented to them they think they are the same persons. At other
times they enter into the fantasy of other spirits and think that they
are them, and sometimes they will even believe themselves to be
the Holy Spirit," and as they identify themselves with a man's
affection or enthusiasm they may drive him to ruin, and even an
angel will join himself so completely to a man that he scarcely knows
"that he does not know of himself what the man knows," and when
they speak with a man they can but speak in that man's mother
tongue, and this they can do without taking thought, for "it is almost
as when a man is speaking and thinks nothing about his words." Yet
when they leave the man "they are in their own angelical or spiritual
language and know nothing of the language of the man." They are
not even permitted to talk to a man from their own memory for did
they do so the man would not know "but that the things he would
then think were his when yet they would belong to the spirit," and it
is these sudden memories occurring sometimes by accident, and
without God's permission that gave the Greeks the idea they had
lived before. They have bodies as plastic as their minds that flow so
readily into the mould of ours and he remembers having seen the
face of a spirit change continuously and yet keep always a certain
generic likeness. It had but run through the features of the
individual ghosts of the fleet it belonged to, of those bound into the
one mediatorial communion.
He speaks too, again and again, of seeing palaces and mountain
ranges and all manner of scenery built up in a moment, and even
believes in imponderable troops of magicians that build the like out
of some deceit or in malicious sport.
IV
There is in Swedenborg's manner of expression a seeming
superficiality. We follow an easy narrative, sometimes incredulous,
but always, as we think, understanding, for his moral conceptions
are simple, his technical terms continually repeated, and for the
most part we need but turn for his "correspondence," his symbolism
as we would say, to the index of his Arcana Celestia. Presently,
however, we discover that he treads upon this surface by an
achievement of power almost as full of astonishment as if he should
walk upon water charmed to stillness by some halcyon; while his
disciple and antagonist Blake is like a man swimming in a tumbling
sea, surface giving way to surface and deep showing under broken
deep. A later mystic has said of Swedenborg that he but half felt,
half saw, half tasted the kingdom of heaven, and his abstraction, his
dryness, his habit of seeing but one element in everything, his lack
of moral speculation have made him the founder of a church, while
William Blake, who grows always more exciting with every year of
life, grows also more obscure. An impulse towards what is definite
and sensuous, and an indifference towards the abstract and the
general, are the lineaments, as I understand the world, of all that
comes not from the learned, but out of common antiquity, out of the
"folk" as we say, and in certain languages, Irish for instance—and
these languages are all poetry—it is not possible to speak an
abstract thought. This impulse went out of Swedenborg when he
turned from vision. It was inseparable from this primitive faculty, but
was not a part of his daily bread, whereas Blake carried it to a
passion and made it the foundation of his thought. Blake was put
into a rage by all painting where detail is generalized away, and
complained that Englishmen after the French Revolution became as
like one another as the dots and lozenges in the mechanical
engraving of his time, and he hated histories that gave us reasoning
and deduction in place of the events, and St. Paul's Cathedral
because it came from a mathematical mind, and told Crabb Robinson
that he preferred to any others a happy, thoughtless person. Unlike
Swedenborg he believed that the antiquities of all peoples were as
sacred as those of the Jews, and so rejecting authority and claiming
that the same law for the lion and the ox was oppression, he could
believe "all that lives is holy," and say that a man if he but cultivated
the power of vision would see the truth in a way suited "to his
imaginative energy," and with only so much resemblance to the way
it showed in for other men, as there is between different human
forms. Born when Swedenborg was a new excitement, growing up
with a Swedenborgian brother, who annoyed him "with bread and
cheese advice," and having, it may be, for nearest friend the
Swedenborgian Flaxman with whom he would presently quarrel, he
answered the just translated Heaven and Hell with the paradoxical
violence of The Marriage of Heaven and Hell. Swedenborg was but
"the linen clothes folded up" or the angel sitting by the tomb, after
Christ, the human imagination, had arisen. His own memory being
full of images from painting and from poetry he discovered more
profound "correspondences," yet always in his boys and girls walking
or dancing on smooth grass and in golden light, as in pastoral
scenes cut upon wood or copper by his disciples Palmer and Calvert
one notices the peaceful Swedenborgian heaven. We come there,
however, by no obedience but by the energy that "is eternal delight,"
for "the treasures of heaven are not negations of passion but
realities of intellect from which the passions emanate uncurbed in
their eternal glory." He would have us talk no more "of the good
man and the bad," but only of "the wise man and the foolish," and
he cries, "Go put off holiness and put on intellect."
Higher than all souls that seem to theology to have found a final
state, above good and evil, neither accused, nor yet accusing, live
those, who have come to freedom, their senses sharpened by
eternity, piping or dancing or "like the gay fishes on the wave when
the moon sucks up the dew." Merlin, who in the verses of Chrétien
de Troyes was laid in the one tomb with dead lovers, is very near
and the saints are far away. Believing too that crucifixion and
resurrection were the soul's diary and no mere historical events,
which had been transacted in vain should a man come again from
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookball.com