100% found this document useful (2 votes)
28 views

Object Oriented Design and Patterns 2nd Edition Cay S. Horstmann - Download the ebook now to never miss important content

The document promotes instant ebook access at ebookgate.com, featuring various programming and design books, including 'Object Oriented Design and Patterns' by Cay S. Horstmann. It provides links to multiple editions of programming books and emphasizes the importance of object-oriented design principles for students. The preface outlines the book's structure, intended audience, and the integration of design patterns with programming concepts, particularly in Java.

Uploaded by

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

Object Oriented Design and Patterns 2nd Edition Cay S. Horstmann - Download the ebook now to never miss important content

The document promotes instant ebook access at ebookgate.com, featuring various programming and design books, including 'Object Oriented Design and Patterns' by Cay S. Horstmann. It provides links to multiple editions of programming books and emphasizes the importance of object-oriented design principles for students. The preface outlines the book's structure, intended audience, and the integration of design patterns with programming concepts, particularly in Java.

Uploaded by

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

Instant Ebook Access, One Click Away – Begin at ebookgate.

com

Object Oriented Design and Patterns 2nd Edition


Cay S. Horstmann

https://ebookgate.com/product/object-oriented-design-and-
patterns-2nd-edition-cay-s-horstmann/

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Click here to visit ebookgate.com and download ebook now
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Python for Everyone 2nd Edition Cay Horstmann

https://ebookgate.com/product/python-for-everyone-2nd-edition-cay-
horstmann/

ebookgate.com

Python for Everyone 1st Edition Cay S. Horstmann

https://ebookgate.com/product/python-for-everyone-1st-edition-cay-s-
horstmann/

ebookgate.com

ActionScript 3 0 design patterns object oriented


programming techniques 1st ed Edition William Sanders

https://ebookgate.com/product/actionscript-3-0-design-patterns-object-
oriented-programming-techniques-1st-ed-edition-william-sanders/

ebookgate.com

Applying UML and Patterns An Introduction to Object


Oriented Analysis and Design and the Unified Process 2nd
Edition Craig Larman
https://ebookgate.com/product/applying-uml-and-patterns-an-
introduction-to-object-oriented-analysis-and-design-and-the-unified-
process-2nd-edition-craig-larman/
ebookgate.com
Java Concepts Late Objects 3rd Edition Edition Cay S.
Horstmann

https://ebookgate.com/product/java-concepts-late-objects-3rd-edition-
edition-cay-s-horstmann/

ebookgate.com

Object Oriented Oracle Wenny Rahayu

https://ebookgate.com/product/object-oriented-oracle-wenny-rahayu/

ebookgate.com

Object oriented Analysis And Design Understanding System


Development With UML 2 0 First Edition Mike O'Docherty

https://ebookgate.com/product/object-oriented-analysis-and-design-
understanding-system-development-with-uml-2-0-first-edition-mike-
odocherty/
ebookgate.com

The principles of object oriented JavaScript Zakas

https://ebookgate.com/product/the-principles-of-object-oriented-
javascript-zakas/

ebookgate.com

C Design Patterns and Derivatives Pricing 2nd Edition M.


S. Joshi

https://ebookgate.com/product/c-design-patterns-and-derivatives-
pricing-2nd-edition-m-s-joshi/

ebookgate.com
Obj ect .. Oriented
Design
&
Patterns
Second Edition

Cay Horstmann
San Jose State University

@
WILEY

John W i l e y & Son s , I n c.


PUBLISHER: Bruce Spatz
SENIOR EDITORIAL ASSISTANT: Bridget Morrisey
PROJECT MANAGER: Cindy Johnson, Publishing Services
DIRECTOR OF MARKETING: Frank Lyman
SENIOR PRODUCTION MANAGER: Ken Santor
COVER DESIGNER: Harold Nolan
COVER PHOTO: © Corbis/Media Bakery

This book was set in Adobe Caslon by Publishing Services and printed and bound by Malloy,
Inc. The cover was printed by Phoenix Color Corporation.

This book is printed on acid-free paper. 00

Copyright © 2006 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 oth­
erwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright
Act, without either the prior written permission of the Publisher, or authorization through
payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood
Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher
for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc.,
111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008.
To order books or for customer service, please call 1-800-CALL-WILEY (225-5945).

ISBN 978-0-471-74487-0
Printed in the United States of America
10 9 8 7 6 5
Preface
Making Obj e c t,Oriented D e s ign Accessible
This book is an introduction to object-oriented design and design patterns at an
elementary level. It is intended for students with at least one semester of program­
ming in an object-oriented language such as Java or C++.
I wrote this book to solve a common problem. When students first learn an
object-oriented programming language, they cannot be expected to instantly mas­
ter object-oriented design. Yet, students should learn the principles of object-ori­
ented design early enough to put them to work throughout the computer science
curriculum.
This book is suitable for a second or third course in computer science-no back­
ground in data structures is required, and students are not assumed to have experi­
ence with developing large software systems. Alternatively, the book can be used
as a companion text in a course in software engineering. (If you need a custom
version of this book for integration into another course, please contact your Wiley
sales representative.)
This second edition is fully updated for Java 5.0, including
• the use of generic collections and the "for each" loop
• a detailed discussion of parameterized type constraints
• auto-boxing and varargs methods, particularly in the reflection API
• multithreading with the j ava . uti 1 . concu r rent package

Integration of D esign Patterns


The most notable aspect of this book is the manner in which the coverage of
design patterns is interwoven with the remainder of the material. For example,
• Swing containers and components motivate the COMPOSITE pattern.
• Swing scroll bars motivate the DECORATOR pattern, and Swing borders are
examined as a missed opportunity for that pattern.
• Java streams give a second example of the DECORATOR pattern. Seeing the
pattern used in two superficially different ways greatly clarifies the pattern
concept.
PREFACE

Without memorable examples, design patterns are just words. In order to visualize
design patterns, this book uses examples from graphical user interface programming.
Students will remember how a component is decorated by scroll bars, and how layout
managers carry out different strategies. (A small and carefully selected subset of Swing is
used for this purpose.)

A Foundation for Furthe r Study


Mter covering the material in this book, students will have mastered the following topics
in three subject areas:

1. Object-oriented design
• A simple design methodology
• CRC cards and UML diagrams
• Design patterns
2. Advanced Java language
• Interface types, polymorphism, and inheritance
• Inner classes
• Reflection
• Generic types
• Multithreading
• Collections
3. User interface programming
• Building Swing applications
• Event handling
• Java 2D graphics programming

These skills clearly form a useful foundation for advanced computer science courses. In
fact, students who have completed this book will have encountered all features of the Java
language (but not, of course, the entire standard Java library, which is too huge for any
one person to master). One advantage of using Java is indeed that students can compre­
hend the entire language. Contrast that with C++, a language that is so complex that
virtually no one can truthfully claim to understand all of its subdeties.
In summary: Use this book if you want your students to understand object-oriented
design and design patterns early in the curriculum. As a bonus, your students will gain a
complete overview of the Java language, and they will be able to program simple Swing
user interfaces.

Programming and Design Tools


Another important aspect of this book is the coverage of tools. While many C++
programmers live their entire programming life in a large and complex integrated
Preface

environment, the Java culture has embraced the use of different tools such as BlueJ,
j avadoc, and ]Unit. Due to the reflective nature of the Java language, there are many
interesting experimental tools. I highlight a number of them in the hope that students
will gain an interest and aptitude in evaluating and selecting tools that fit their working
style.
Students who learn object-oriented design also should become familiar with drawing
UML diagrams. An easy-to-use and no-cost tool for this purpose, the V iolet UML edi­
tor, is provided for their use. Chapter 8 of this book introduces the framework on which
V iolet is based. All UML diagrams in this book were drawn with V iolet.

A Tou r o f t h e B o o k
Chapter I A Crash Course i n Java
This chapter introduces the basic syntax ofJava and can serve either as a refresher or as a
transition for students with a background in C++. Topics covered include
• Defining classes and methods

• Objects and object references

• Exploring objects with BlueJ

• Documentation comments

• Numbers, strings, and arrays

• Packages

• Exception handling

• Common utility classes: Ar rayL; st and Scann er

• Programming style guidelines

Chapter 2 The Obj ect�Oriented Design Proc e s s


This chapter introduces the process o f object-oriented design, CRC cards, and UML
notation. It presents a case study of a simple voice mail system to illustrate the design
process, starting with the project's specification and culminating in its Java implementa­
tion. Topics covered include
• IdentifYing classes and methods

• Relationships between classes

• CRC cards

• UML class, sequence, and state diagrams

• Case study
PREFACE

Chapter 3 Guidelines for Class Design


Unlike Chapter 2, which took a top-down view of the discovery of classes and their rela­
tionships, this chapter focuses on the design of a single class or a small group of related
classes. Topics covered include
• Designing and implementing the interface of a class
• The importance of encapsulation
• Analyzing the quality of an interface
• Programming by contract: preconditions, postconditions, and invariants

Chapter 4 Interface Types and Polymorphism


This chapter introduces the notation of the Java interface type, without mentioning
inheritance. This approach has an important advantage: The reader learns about poly­
morphism in its �rest form, without being burdened by technical matters such as super­
class construction or the invocation of superclass methods.
The chapter also introduces the Swing user interface toolkit and AWT drawing opera­
tions. It starts with the Icon interface type, which allows the placement of arbitrary
drawings in a frame.
Anonymous classes are introduced as an easy mechanism for "ad-hoc" objects that imple­
ment a particular interface type. They are then put to use for Swing user interface
actions.
Up to this point, all interface types have been supplied in the standard library. The chap­
ter ends with the design of a custom interface type. Topics covered include
• Frames, images, and shapes
• The Icon interface type
• The Comparab l e and Comparat:or interface types
• Anonymous classes
• User interface actions
• Designing interface types

Chapter 5 Patterns and GU I Programming


This chapter i' ntroduces the concept of patterns and covers a number of patterns that
arise in the Swing user interface toolkit and the Java collections library. Topics include
• Alexander's architectural patterns
• Software design patterns
• The ITERATOR pattern as an example of a design pattern
• The OBSERVER pattern, model/view/controller, and Swing listeners
• The STRATEGY pattern and layout managers
• The COMPOSITE pattern, user interface components and containers
• The DECORATOR pattern, scroll panes, and borders
Preface

Chapter 6 Inheritance and Abstract Clas s es


This chapter introduces the mechanics o f inheritance using examples from the AWT
graphics library. There is an extensive discussion of abstract classes, a topic that many
beginners find challenging. An abstract shape class lays the foundation for the graph edi­
tor framework created in Chapter 8. Several inheritance hierarchies are examined,
including the hierarchies of Swing components, geometric shapes, and exception classes.
The chapter discusses advanced exception handling, including the definition of new
exception classes (which, of course, requires inheritance). The chapter closes with a dis­
cussion of when not to use inheritance. Topics covered include
• Defining and implementing subclasses
• Invoking superclass constructors and methods
• Abstract classes and the TEMPLATE METHOD pattern
• The inheritance hierarchy of Swing components
• The inheritance hierarchy of graphical shapes in the j ava . awt . geom package
• The inheritance hierarchy of exception classes
• When not to use inheritance

Chapter 7 The Java Obj ec t Model


This chapter covers the Java type system in detail and introduces the important reflection
capabilities ofJava. It then moves on to a rigorous treatment of the fundamental methods
of the Obj ect class: toStri ng, equal s , hashCode, and cl one. Generics are discussed at an
intermediate level, going well beyond the basics but stopping short of discussing techni­
cal minutiae. As an application of reflection techniques, the JavaBeans component model
and the implementation ofJavaBeans properties are introduced. Topics covered include
• The Java type system, primitive types, wrappers, and array types
• Type inquiry and reflection
• Object equality and cloning
• Serialization
• Generic types
• Components and JavaBeans

Chapter 8 Frameworks
This capstone chapter culminates in the development of a graph editor framework and
its specialization to a UML class diagram editor. Topics covered include
• The framework concept
• Applets as a simple framework
• The collections framework
• Application frameworks
• The graph editor framework
PREFACE

Chapter 9 Multithreading
This chapter introduces the multithreading pnmltlves of the Java language, thus
completing the students' introduction to Java language semantics. The synchronization
primitives can be challenging for students to grasp because they tightly combine several
related features. I first cover the Lock and (ondi ti on classes in the j ava . uti l . concu r­
rent package, then use that background to explain the built-in locks and wait sets.
Topics covered include
• Threads and the Runnab 1 e interface type
• Interrupting threads
• Thread synchronization
• The j ava . uti l . conc ur rent package
• An application: Algorithm animation

Chapter 10 More D e s ign Patterns


The book concludes with a chapter that covers additional important design patterns. A
summary at the end of the chapter briefly describes additional classical design patterns
whose coverage is beyond the scope of this book. Topics covered include
• The ADAPTER pattern
• Actions and the COMMAND pattern
• The FACTORY METHOD pattern
• The PROXY pattern
• The SINGLETON pattern
• The VISITOR pattern
• Other design patterns
Figure 1 shows the dependencies between the chapters.

P e da g o g i c a l S tr u c t u r e
Each chapter begins with an introduction and listing of the chapter topics. Concepts and
principles are presented in the context of programming examples, and many example
programs are printed in their entirety in the text to encourage students to read and
understand code listings. Complete source code for all of the examples in the text is
available from the book's Web site at http : //www . wi l ey . com/col l ege/horstmann (see
pages xvii-xix for a listing of the example programs that accompany this book).
Throughout the chapters, there are several kinds of special features to help your students.
These features are specially marked so they don't interrupt the flow of the main material.
Margin notes highlight important topics and help students navigate
Key concepts are highlighted
with margin notes. the core material of each chapter by highlighting where new concepts
are introduced.
Preface

1
A Crash Course in Java
(optional)

2
The Object-Oriented
Design Process

3
Guidelines for
Class Design

4 9
Interface Types and Multithreading
Polymorphism (optional)

5
Patterns and
Gill Programming

6 10
Inheritance and More Design Patterns
Abstract Classes (optional)

7.7
.-- Generic Types
(optional)
7.1-7.5 7.6
The Java Reflection -
Object Model (optional)
7.8
'-- JavaBeans Components
(optional)

8.1-8.4
I 8.5
Enhancing the Graph
Frameworks
Editor Framework (optional)

Figure 1

Dependencies Between the Chapters


PREFACE

Special Topics introduce background material or advanced subjects that can be skipped.
Several data structures that students in a second course may not have been introduced to
are presented in these Special Topics, making them available as needed. Other Special
Topics address features of languages other than Java that relate to the design principles in
the chapter. (See page xvi for a list of these topics by chapter.)
Design Patterns are specially marked with this icon. Each design pattern is presented in a
standard format that includes the context in which the pattern is useful, the solution that
the pattern provides, and a UML diagram of the pattern elements. Most design patterns
are then followed by a table that shows students how the pattern's structure is applied to
the example discussed in that section. (See page xvi for a list of patterns by chapter.)

NOTE Notes highlight important or interesting material, such as tips or pointers for further
reading.

INTERNET Internet notes contain links to further information on the Internet, including
locations for downloadable programming tools, documentation, and articles related to chap­
ter topics.

TIP Tips are used liberally throughout the text to explain good programming practices and
to help students avoid common errors.

Web R e s o u r c e s
Additional resources can be found on the book's Web site at http : //www . wi l ey . com/
col l ege/horstmann. These resources include:
• Solutions to selected exercises (accessible to students)
• Solutions to all exercises (for instructors only)
• Help with common compilers
• Presentation slides for lectures
• Source code for all examples in the book

The Vio l e t U M L E d i t o r
Students may download V iolet, an easy-to-use and no-cost UML editor, at htt p : //
ho rstmann . com/vi 01 et. V iolet was used to draw the UML diagrams in the text, so
students can use this same tool to create similar diagrams for the programs they design.
Preface

Acknowledgments
Many thanks to Bruce Spatz, Bill Zobrist, Bridget Morrisey, Catherine Shultz, Phyllis
Cerys, Ken Santor, and Lisa Gee at John Wiley & Sons for their support for this book
project.
I am very grateful to the many individuals who reviewed the manuscript, found embar­
rassing errors, made valuable suggestions, contributed to the supplements, and helped
me make the book more student friendly:
Carl G. Alphonce, UniversityoJBuffalo
Bill Bane, Tarleton State University
Dwight Barnette, Virginia Polytechnic Institute and State University
Alfred Benoit, Johnson & Wales University
Richard Borie, University ojAlabama
Bruce Char, Drexel University
Chia Chen, Tuskegee University
Ashraful Chowdhury, Georgia Perimeter College
David M. Dacus, Mountain View College
Roger deBry, Utah Valley State College
Preetam Desai, UniversityojMissouri, St. Louis
Chris Dovolis, UniversityojMinnesota
Robert Duvall, Duke University
Anne B. Horton, AT&T Laboratories
Robert Kelly, State University oJNew York, Stony Brook
Walter W. Kirchherr, SanJose State University
Blayne Mayfield, Oklahoma State University
Marlene Miller
Evelyn Obaid, SanJose State University
Edward G. Okie, Radford University
Jong-Min Park, San Diego State University
Richard Pattis, Carnegie Mellon University
Hao Pham, SanJose State University
Gary Pollice, Worcester Polytechnic Institute
Saeed Rajput, Florida Atlantic University
Gopal Rao, California State University, Sacramento
Mike Rowe, Universityoj Wisconsin, Platteville
Ken Slonneger, University oJIowa
PREFACE

Richard L. Upchurch, University ofMassachusetts, Dartmouth


Phil Ventura, State University of West Georgia
V ictor Yu, DeAnza College
Steven J. Zeil, Old Dominion University
Rong Zhao, State University ofNew York, Stony Brook
I appreciate the enthusiasm and patience of my students at San Jose State University who
participated in courses based on early versions of this book and provided valuable feed­
back for the development of this second edition.
Finally, a special thanks to Cindy Johnson of Publishing Services, who served as editor,
production supervisor, liaison with the publisher, general troubleshooter, and in innu­
merable other roles. Her work was essential for quality, timeliness, and sanity, through­
out the production of this book.
Contents
Prefac e iii

� Chapte r I A Crash Course i n Java I

1.1 "Hello, World! " in Java 2


1.2 Documentation Comments 6
1.3 Primitive Types 9
1.4 Control Flow Statements 12
1.5 Object References 12
1.6 Parameter Passing 14
1.7 Packages 16
1.8 Basic Exception Handling 18
1.9 Strings 21
1.10 Reading Input 23
1.11 Array Lists and Linked Lists 23
1.12 Arrays 26
1.13 Static Fields and Methods 28
1.14 Programming Style 29

� Chapte r 2 The Object-Orie nted Design Proc ess 35

2.1 From Problem to Code 36


2.2 The Object and Class Concepts 39
2.3 Identifying Classes 41
2.4 Identifying Responsibilities 45
2.5 Relationships Between Classes 46
2.6 Use Cases 48
2.7 CRC Cards 50
2.8 UML Class Diagrams 53
2.9 Sequence Diagrams 58
2.10 State Diagrams 60
2.11 Using j avadoc for Design Documentation 61
2.12 Case Study: A Voice Mail System 62

� Chapte r 3 Guideli n es for Class Desi g n 89


3.1 An Overview of the Date Classes in the Java Library 90
3.2 Designing a Day Class 94
3.3 Three Implementations of the Day Class 98
3.4 The Importance of Encapsulation 109
3.5 Analyzing the Quality of an Interface 118
3.6 Programming by Contract 122
3.7 Unit Testing 131
CONTENTS

� Chapter 4 Interface Types and Polymorphism 137

4.1 The Icon Interface Type 138


4.2 Polymorphism 143
4.3 The Comparabl e Interface Type 144
4.4 The Comparator Interface Type 147
4.5 Anonymous Classes 148
4.6 Frames and User Interface Components 151
4.7 User Interface Actions 153
4.8 Timers 157
4.9 Drawing Shapes 159
4.10 Designing an Interface Type 164

� Chapter 5 Patterns and GUI Programming 173

5.1 The Iterator as a Pattern174


5.2 The Pattern Concept 176
5.3 The OBSERVER Pattern 180
5.4 Layout Managers and the STRATEGY Pattern 183
5.5 Components, Containers, and the COMPOSITE Pattern 193
5.6 Scroll Bars and the DECORATOR Pattern 195
5.7 How to Recognize Patterns 198
5.8 Putting Patterns to Work 200

� Chapter 6 Inheritance and Abstract Classes 215

6.1 The Concept of Inheritance 216


6.2 Graphics Programming with Inheritance 223
6.3 Abstract Classes 228
6.4 The TEMPLATE METHOD Pattern 236
6.5 Protected Interfaces 240
6.6 The Hierarchy of Swing Components 243
6.7 The Hierarchy of Standard Geometric Shapes 247
6.8 The Hierarchy of Exception Classes 252
6.9 When Not to Use Inheritance 254

� Chapter 7 T he Java Object Model 261

7.1 The Java Type System 262


7.2 Type Inquiry 268
7.3 The Obj ect Class 271
7.4 Shallow and Deep Copy 280
7.5 Serialization285
7.6 Reflection 287
7.7 Generic Types 294
7.8 JavaBeans Components 302
Contents

� Chapter 8 Frameworks 319

8.1 Frameworks 320


8.2 Applets as a Simple Framework 321
8.3 The Collections Framework 324
8.4 A Graph Editor Framework 334
8.5 Enhancing the Graph Editor Framework 353

� Chapter 9 Multithreading 361

9.1 Thread Basics 362


9.2 Thread Synchronization 370
9.3 Animations 387

� Chapter 10 More Design Patterns 397

10.1 The ADAPTER Pattern 398


10.2 Actions and the COMMAND Pattern 401
10.3 The FACTORY METHOD Pattern 406
10.4 The PROXY Pattern 408
10.5 The SINGLETON Pattern 413
10.6 The VISITOR Pattern 415
10.7 Other Design Patterns 422

Glossary 427

Index 437

Photo Credits 45 1
SPECIAL FEATURES

� Special Topics � Patterns


A Crash Course in
Java

2 The Object-Oriented ECMAScript-An Object-Oriented


Design Process Language Without Classes 40
Queues 44

3 Guidelines for Class Total Orderings 91


Design Operator Overloading 97

4 Interface Types Accurate Positioning of Text 163


and Polymorphism

5 Patterns and SHORT PASSAGES 176


GUI Programming ITERATOR 178
OBSERVER 182
STRATEGY 192
COMPOSITE 194
DECORATOR 196

6 Inheritance and Refactoring 234 TEMPLATE METHOD 237


Abstract Classes Multiple Inheritance 246
Stacks 257

7 The Java Object Consequences of the Symmetry FACADE 305


Model Condition for Equality Testing 276
Hash Tables 278
Accessing Java Properties from
JavaScript 308

8 Frameworks PROTOTYPE 337

9 Multithreading Synchronized Blocks 385


Volatile Fields 386

10 More Design Patterns ADAPTER 399


COMMAND 403
FACTORY METHOD 407
PROXY 409
SINGLETON 414
VISITOR 421
Companion Code Listing

� C o d e i n Tex t � C o m p a n i o n C od e
A Crash Course in helioworld/GreeterTester.java 3 inputllnputTester.java
Java helloworld/Greeter.java 6

2 The Object-Oriented mail/Message .java 75


Design Process mail/MessageQueue .java 75
mail/Mailbox.java 76
mail/Connection.java 78
mail/MailSystem.java 83
maillTelephone.java 83
mail/MailSystemTester.java 84

3 Guidelines for Class day1/Day.java 100 day1/DayTester.java


Design day2/Day.java 104 day2/DayTester.java
day3/Day.java 107 day3/DayTester.java
queue/MessageQueue .java 124 junitlDay.java
junitiDayTest.java

4 Interface Types icon2/Marslcon.java 141 action2/ActionTester.java


and Polymorphism sort1/Country.java 145 icon1/1conTester.java
sort1/CountrySortTester.java 146 icon1/MessageTester.java
frame/FrameTester.java 152 icon2/1conTester.java
action1/ActionTester.java 155 icon3/1conTester.java
timermmerTester.java 158 sort2/ComparatorTester.java
icon3/Carlcon .java 161 sort2/Country.java
animation/MoveableShape.java 166 sort2/CountryComparatorByName.java
animation/Shapelcon.java 167 sort3/ComparatorTester.java
animation/AnimationTester.java 167 sort3/Country.java
animation/CarShape.java 168

5 Patterns and mailguiITelephone.java 187 decorator/ScroIiPaneTester.java


GUI Programming layoutiFormLayout.java 190 mailgui/Connection.java
layoutiFormLayoutTester.java 191 mailguilMailbox.java
invoice/Lineltem.java 200 mailgui/MaiISystem.java
invoice/Product.java 200 mailgui/MaiISystemTester.java
invoice/Bundle.java 202 mailgui/Message.java
invoice/Discountedltem.java 203 mailgui/MessageQueue.java
invoice/lnvoiceFormatter.java 207
invoice/SimpleFormatter.java 209
invoice/lnvoice.java 209
invoice/lnvoiceTester.java 211
COMPANION CODE LISTING

� C od e i n Tex t � C om p a n i o n C od e
6 Inheritance and car/CarComponent.java 226 car/CarShape.java
Abstract Classes car/CarMover.java 227 scene1/CarShape.java
scene1/SceneComponent.java 232 scene1/HouseShape.java
scene1/SceneEditor.java 233 scene1/SceneShape.java
scene2/SelectableShape.java 238 scene1/SelectableShape.java
scene2/HouseShape.java 238 scene2/CarShape.java
scene3/CompoundShape.java 240 scene2/SceneComponent.java
scene2/SceneEditor.java
scene2/SceneShape.java
scene3/CarShape.java
scene3/CompoundShape.java
scene3/HouseShape .java
scene3/SceneComponent.java
scene3/SceneEditor.java
scene3/SceneShape.java
scene3/SelectableShape.java

7 The Java Object reflect1/HardHello.java 291 seriaM/Employee.java


Model reflect2/FieldTester.java 292 seriaM/SerializeEmployeeTester.java
generic/Utils.java 301 seriaI2/Car.java
generic/UtilsTester.java 302 seriaI2/SerializeCarTester.java
carbean/CarBean.mf 311
carbean/CarBean.java 313

8 Frameworks appletiBannerApplet.java 323 appletiBannerApplet.html


queue/BoundedQueue.java 328 graphed/GraphFrame.java
queue/QueueTester.java 330 graphed/GraphPanel.java
graphed/Node.java 339 graphed/PointNode.java
graphed/Edge.java 339 graphedfToolBar.java
graphed/AbstractEdge .java 341 graphed2/AbstractEdge.java
graphed/Graph.java 342 graphed2/CircleNode.java
graphed/SimpleGraph.java 347 graphed2/Edge.java
graphed/SimpleGraphEditor.java 348 graphed2/EnumEditor.java
graphed/CircleNode.java 348 graphed2/FormLayout.java
graphed/LineEdge.java 349 graphed2/Graph.java
graphed2/GraphFrame.java
graphed2/GraphPanel.java
graphed2/LineEdge .java
graphed2/LineStyle.java
graphed2/Node.java
graphed2/PointNode.java
graphed2/PropertySheet.java
graphed2/SimpleGraph.java
graphed2/SimpleGraphEditor.java
graphed2fToolBar.java
umleditor/AbstractEdge.java
umleditor/ArrowHead.java
umleditor/BentStyle.java
Companion Code Listing

.... C od e In Text .... C om p a n i o n C o d e


8 Frameworks umleditor/ClassDiagramGraph.java
(continued) umleditor/ClassNode.java
umleditor/ClassRelationshipEdge.java
umleditor/Edge.java
umleditor/EnumEditor.java
umleditor/FormLayout.java
umleditor/Graph.java
umleditor/GraphFrame.java
umleditor/GraphPanel.java
umleditor/LineStyle.java
umleditor/MultiLineString.java
umleditor/MultiLineStringEditor.java
umleditor/Node.java
umleditor/PointNode.java
umleditor/PropertySheet.java
umleditor/RectangularNode .java
umleditorlSegmentedLineEdge.java
umleditorlShapeEdge .java
umleditorlToolBar.java
umleditor/UMLEditor.java

9 Multithreading greeting/GreetingProducer.java 363 animation1/MergeSorter.java


greetinglThreadTester.java 365 animation21ArrayComponent.java
queue1IThreadTester.java 371 animation2/MergeSorter.java
queue1/Producer.java 371 queue2/Consumer.java
queue1/Consumer.java 372 queue2/Producer.java
queue1/BoundedQueue.java 373 queue2IThreadTester.java
queue2/BoundedQueue.java 380 queue3/Consumer.java
queue3/BoundedQueue.java 384 queue3/Producer.java
animation1/Sorter.java 388 queue3IThreadTester.Java
animation11ArrayComponent.java 389
animation11AnimationTester.java 390
animation2/Sorter.java 391
animation21AnimationTester.java 392

10 More Design Patterns adapter/lconAdapter.java 398 adapter/Carlcon.java


adapter/lconAdapterTester.java 399
command/CommandTester.java 404
command/GreetingAction.java 405
proxy/lmageProxy.java 411
proxy/ProxyTester.java 412
visitor/FileSystemNode.java 417
visitor/FileNode.java 418
visitor/DirectoryNode.java 418
visitor/FileSystemVisitor.java 419
visitor/PrintVisitor.java 419
visitorNisitorTester.java 419
Chapter

A-Crasn Course
inJava

� "Helio, World!" in Java

� Documentation Comments

� Primitive Types

� Control Flow Statements

� Object References

� Parameter Passing

� Packages

� Basic Exception Handling

� Strings

� Reading I nput

� Array Lists and Linked Lists

� Arrays

� Static Fields and Methods

� Programming Style

The purpose of this chapter is to teach you the elements of the Java
programming language-or to give you an opportunity to review them­
assuming that you know an object-oriented programming language. In
CHAPTER 1 A Crash Course in Java

particular, you should be familiar with the concepts of classes and objects.
If you know C++ and understand classes, member functions, and construc­
tors, then you will find that it is easy to make the switch to Java.

"He l l o , Wo rl d!" i n J ava


Classes are the building blocks ofJava programs. Let's start our crash course by looking
at a simple but typical class:
publ i c cl ass Greete r
{
publ i c Greete r (Stri ng aName)
{
name = aName ;
}

publ i c Stri ng sayHel l o ()


{
ret ur n "Hel l o , " + name + "!";
}

pri vate Stri ng name ;


}
This class has three features:
• A constructor G reete r (St ri ng aName) that is used to construct new objects of this
class.
• A method sayHe 1 1 0 0 that you can apply to objects of this class. (Java uses the term
"method" for a function defined in a class.)
• Afield name. Every object of this class has an instance of this field.
Each feature is tagged as publ i c or pri vate. Implementation details
A class definition contains the
implementation of construc­ (such as the name field) are private. Features that are intended for the
tors, methods, and fields. class user (such as the constructor and sayHe 1 1 0 method) are public.
The class itself is declared as public as well. You will see the reason in
the section on packages.
To construct an object, you use the new operator, which invokes the constructor.
new G reete r ( "Worl d " )
The new operator returns the constructed object, or, more precisely, a reference t o that
object-we will discuss this distinction in detail in the section on object references.
The object that the new operator returns belongs to the G reeter class.
The new operator constructs
new instances of a class. In object-oriented parlance, we say that it is an instance of the Greeter
class. The process of constructing an object of a class is often called
"instantiating the class".
1.1 "Hello, World!" in Java

Mter you obtain an instance of a class, you can call (or invoke) methods on it. The call
(new Greet e r ( "Wo r l d " ) ) . sayHe11 0 0
creates a new object and causes the sayHe 1 10 method t o b e executed. The result i s the
string "He110 , Wo rl d ! , the concatenation of the strings " Hel l o , " , name, and" ! " .
"

The code that invokes a method is often called the client code. We
Object-oriented programming
follows the "client-server" think of the object as providing a service for the client.
model. The client code You often need variables to store object references that are the result
requests a service by invoking of the new operator or a method call:
a method on an object.
Greeter wo rl dGreeter new Greete r ( "Worl d " ) ;
=

Stri ng g reeti ng = worl dGreete r . sayHel l o () ;


Now that you have seen how to define a class, you're ready to build your first Java pro­
gram, the traditional program that displays the words "Hello, World!" on the screen.
You will define a second class, Greet e rTester, to produce the output.

II!! _=

I
Chr/helloworld/GreeterTester.java
1 __
1 publ i c cl ass Greete rTester
2 {
3 publ i c stati c voi d mai n (Stri ng [ ] args)
4 {
5 G reete r wo rl dGreeter = new G reete r ( "Wo r l d " ) ;
6 Stri ng g reeti ng = wo rl dGreete r . sayHel l o () ;
7 System . out . pri ntl n (g reeti ng) ;
8 }
9 }
This class has a rna i n method, which is required to start a Java applica­
Execution of a Java program
starts with the mai n method tion. The mai n method is static, which means that it doesn't operate on
of a class. an obj ect. (We will discuss static methods-also called class meth-
ods---- i n greater detail later in this chapter.) When the application is
launched, there aren't any objects yet. It is the job of the mai n method to construct the
objects that are needed to start the program.
The args parameter of the mai n method holds the command-line arguments, which are
not used in this example. We will discuss command-line arguments in the section on
arrays.
You have already seen the first two statements inside the mai n method. They construct a
G reet e r object, store it in an object variable, invoke the sayHel l o method, and capture
the result in a string variable. The last statement invokes the pri ntl n method on the
System . out object. The result is to print the message and a line terminator to the
standard output stream.
To build and execute the program, put the Greete r class inside a file G reete r . j ava and
the Greet e rTester class inside a separate file Greete rTeste r . j ava. The directions for
compiling and running the program depend on your development environment.
The Java Software Development Kit (SDK) from Sun Microsystems is a set of
command-line programs for compiling, running, and documenting Java programs.
CHAPTER 1 A Crash Course in Java

Versions for several platforms are available at http : //j ava . sun . corn/j 2 se. If you use the
Java SDK, then follow these instructions:
1. Create a new directory of your choice to hold the program files.
2. Use a text editor of your choice to prepare the files Greete r . j ava and
GreeterTeste r . j ava. Place them inside the directory you just created.
3. Open a shell window.
4. Use the cd command to change to the directory you just created.
5. Run the compiler with the command
j avac GreeterTeste r . j ava
If the Java compiler is not on the search path, then you need to use the full path
(such as lusr1 1 oca 1 Ij dkl . 5. O/bi n/j avac or c : \jdkl . 5. O\bi n\j avac) instead of
just j avac. Note that the Greete r . j ava file is automatically compiled as well since
the G reeterTester class requires the Greeter class. If any compilation errors are
reported, then make a note of the file and line numbers and fix them.
6. Have a look at the files in the current directory. Verify that the compiler has gen­
erated two classfiles, Greete r . c1 ass and GreeterTeste r . c1 ass.
7. Start the Java interpreter with the command
j ava Greete rTester
Now you will see a message "Hello, World!" in the shell window (see Figure 1).
The structure of this program is typical for a Java application. The program consists of a
collection of classes. One class has a rnai n method. You run the program by launching the
Java interpreter with the name of the class whose rnai n method contains the instructions
for starting the program activities.

Eile .Edit Ytew Ienni � TaQs Help

-$ cd oodp/Chl/helloworld
-/oodp/Chl/helloworld$ javac GreeterTester.java .... ------ Run compiler

�-�d$ -----------
-/oodp/Chl/helloworld$ java GreeterTester ...
...
____
>--- ___

ello, World! Start interpreter


-/oodp/Chl/helloworld$
___
_
Message printed

Figure 1

Running the "Hello, World!" Program in a Shell Window


1.1 "Hello, World!" in Java

Some programming environ­ The Blue] development environment, developed at Monash Univer­
ments allow you to execute sity, lets you test classes without having to write a new program for
Java code without requiring a every test. Blue] supplies an interactive environment for constructing
mai n method. objects and invoking methods on the objects. You can download Blue]
from http : //www . b 1 uej . o rg.
With Blue], you don't need a GreeterTester class to test the G reete r class. Instead, just
follow these steps.
1. Select "Project -+ New . . . " from the menu; point the file dialog box to a directory
of your choice and type in the name of the subdirectory that should hold your
classes-this must be the name of a new directory. Blue] will create it.
2. Click on the "New Class . . . " button and type in the class name Greeter. Right­
click on the class rectangle and type in the code of the Greeter class.
3. Click on the "Compile" button to compile the class. Click on the "Close" button.
4. The class is symbolized as a rectangle. Right-click on the class rectangle and select
"new Greeter(aName)" to construct a new object. Call the object wor1 dG reete r
and supply the constructor parameter "Wor 1 d" (including the quotation marks).
5. The object appears in the object workbench. Right-click on the object rectangle
and select "String sayHello( )" to execute the sayHe 1 1 0 method.
6. A dialog box appears to display the result (see Figure 2).
As you can see, Blue] lets you think about objects and classes without fussing with
publ i c stati c voi d mai n.

��
frojtct Edit Iools �It!w Help

rNewclass ,l
_ _ Class
[ -;:]
Gru.er
...---

/ Resuit dialog box


--

C----El
[ ;P � ]
CO il

!: BlueJ MNhoa Re<"ult X

Ii Gr��' w·1n3 'HeHo" mf'ssaQe


// #te!um a mtSS8Qe comamll10 �Hel!(}· and the name 01
// U')e ;nUi'lM person or emIlY
SUing uyHelloO

worldGrttter.s;ayHelloO
returned:

SUing -H.llo, World!- I "------'

Object workbench

Figure 2

Testing a Class with BlueJ


CHAPTER 1 A Crash Course in Java

D o c u m e n tation C o m m e n t s
Java has a standard form for comments that describe classes and their features. The Java
development kit contains a tool, called j avadoc, that automatically generates a conve­
nient set of HTML pages that document your classes.
Documentation comments are delimited by /** and * /. Both class and method com­
ments start with freeform text. The j avadoc utility copies the first sentence of each
comment to a summary table. Therefore, it is best to write that first sentence with some
care. It should start with an uppercase letter and end with a period. It does not have to be
a grammatically complete sentence, but it should be meaningful when it is pulled out of
the comment and displayed in a summary.
Method and constructor comments contain additional information. For each parameter,
supply a line that starts with @param, followed by the parameter name and a short expla­
nation. Supply a line that starts with @retu rn to describe the return value. Omit the
@param tag for methods that have no parameters, and omit the @return tag for methods
whose return type is voi d .
Here i s the Greeter class with documentation comments for the class and its public
interface.

Chr/helloworld/Greeter.java
1 /**
2 A class for producing simple greetings.
3 */
4 publ i c cl ass Greeter
5 {
6 /**
7 Constructs a Greeter object that can greet a person or entity.
8 @param aName the name of the person or entity who should
9 be addressed in the greetings.
10 */
11 publ i c Greete r (Stri ng aName)
12 {
13 name aName ;
=

14 }
15
16 /**
17 Greet with a "Hello" message.
18 @ret u rn a message containing "Hello" and the name of
19 the greeted person or entity.
20 */
21 publ i c Stri ng sayHel l o ()
22
+ "!";
{
23 return "Hel l o , " + name
24 }
25
26 pri vate St ri ng name ;
27 }
1.2 Documentation Comments

Your first reaction may well be "Whoa! I am supposed to write all this stuffi" These com­
ments do seem pretty repetitive. But you should still take the time to write them, even if
it feels silly at times. There are three reasons.
First, the j avadoc utility will format your comments into a nicely formatted set of
HTML documents. It makes good use of the seemingly repetitive phrases. The first
sentence of each method comment is used for a summary table of all methods of your
class (see Figure 3). The @param and @ret:urn comments are neatly formatted in the detail
descriptions of each method (see Figure 4). If you omit any of the comments, then
j avadoc generates documents that look strangely empty.
Next, it is possible to spend more time pondering whether a comment
Supply comments for all
methods and public fields of is too trivial to write than it takes just to write it. In practical pro­
a class. gramming, very simple methods are rare. It is harmless to have a triv-
ial method overcommented, whereas a complicated method without
any comment can cause real grief to future maintenance programmers. According to the
standard Java documentation style, every class, every method, every parameter, and every
return value should have a comment.
Finally, it is always a good idea to write the method comment first, before writing the
method code. This is an excellent test to see that you firmly understand what you need to
program. If you can't explain what a class or method does, you aren't ready to implement
it.

"" Eile Edit Ylew .Go ,eool:.man:.s loots ytlndow tfelp

...
I� fileJ/lhomelcayloodpICh1IhelloworidIGreeter.html Cl fjJ
.

Package �Tree Deprecated Index �


PREv CLASS NEXT CLASS � J:I2.£l!IIIrul �
SUMMARV; NESTED I FIELD I � I M.IilllQQ DETAil FIElDI�I�

Class Greeter -

LGreeter
java.lang.Object

public class Greeter


extends java.lang.Object

A class for producing simple greeting:s.

Constructor Summary

Constructs a Greeter object that can greet a person or entity.


�(java.lang.Strin9 aHame)

Stringl.saYHCllO ()
Method Summary
ja
... lang.

Greet with a "Hello" message.

,)iil,.Q�U� ...- ---.�. -.- - "'.CC _ L


7
. - .=!"

Figure 3

A j avadoc Class Summary


CHAPTER 1 A Crash Course in J ava

... file fdit YJew yO Bookmarks Ioois WlndO\ll l:felp

:
I� fileJllhomelcay/oodpIChl lheIiOWOridIGn1eter.html 1:11 III
IConstructor Detail I
Greeter

pub l ic Greeter (java . l ang . S tring aName)


Constructs a Greeter object that can greet a person or entil¥.

Parameters:
aName - the name of the person or entil¥ who should be addressed in the greeting.<.

IMethod Detail I
sayHello
public java.lang. String sayHello()

Greet with a "Hello" message.

Returns:
a m�sage containing "Hello" and the name of the greeted person or entil¥.

LJi.: bit,!:! 4I>i

Figure 4

Parameter and Return Value Documentation in j avadoc

Mter you have written the documentation comments, invoke the j avadoc utility.
1 . Open a shell window.
2 . Use the cd command to change to the directory you just created.
3. Run the j avadoc utility
j avadoc * . j ava
If the Java development tools are not on the search path, then you need to use the
full path (such as /usr /1 oca 1 /j dkl . 5. O/b; n/j avadoc or c : \j dkl . 5 . O\b; n\j ava­
doc) instead ofjust j avadoc.
The j avadoc utility then produces one HTML file for each class
The j avadoc utility extracts
documentation comments and (such as Greete r . htm1 and Greete rTeste r . htm1 ) as well as a file
produces a set of cross-linked ; ndex . htm1 and a number of other summary files. The ; ndex . htm1 file
HTML files. contains links to all classes.

The j avadoc tool is wonderful because it does one thing right: It allows you to put the
documentation together with your code. That way, when you update your programs, you
can see immediately which documentation needs to be updated. Hopefully, you will then
update it right then and there. Mterwards, run j avadoc again and get a set of nicely for­
matted HTML pages with the updated comments.

INTERNET The DocCheck program reports any missing j avadoc comments. Download it
from http : //j ava . sun . com/j 2 se/j avadoc/doccheck/.
1.3 Primitive Types

.
.. fUe .Edit Yl8'¥l yO UOokmarts Ioois :l!lindow Help

·
·
Iv file:lllusrltocalljdk.1 S OIdocslaplllndex.ntml al [Em
. .
ava,beans
ava,beans,beanC( -
Overview Package mEmUse Tree Deprecated Index !:!!!!p J_
St.

� � t:fl.6Mll I!l!...E!!8Mil


SUMMARY, NESTED I EID..Il I � I MilI:JQJl DETAIL' EID..Il I � I MilI:JQJl

ava.la
na.annotatl

Ja....lang
ava.lana.instru me •

Class String
�able
tateEdit

Ljava . lanq. str ing


aleFactofY java . l ang. Object


�-
reamable All Implemented Interfaces:
reamableValU6 Serializable. Olar$eguence, Comparable<String>
treamCorruDted

Str ing
treamHandler
treamPrintServic pub l i c final class
extends Object
implemen ts Ser i a l i z able, Comparable<String> , CharSequence
treamPrintServi
treamResult
treamSource
The S t r ing class represents character strings. All string lirerals in Java
treamT okenizer


programs, such as "abc", are implemented as instances of this class.

• ,
c •. .
• •
I1iI Q (>'1' ihomeJlcIpMdk I .s.�tri'l9 html
flo'"
-=�

F i g u re 5

The Java API Documentation

The Java development kit contains the documentation for all classes in the Java library,
also called the application programming interface or API. Figure 5 shows the documen­
tation of the St ri ng class. This documentation is directly extracted from the library
source code. The programmers who wrote the Java library documented every class and
method and then simply ran j avadoc to extract the HTML documentation.

TIP Download the SDK documentation from http : //j ava . sun . com/j 2se. Install the doc­
umentation into the same location as the Java development kit. Point your browser to the
docs/api Ii ndex . html file inside your Java development kit directory, and make a bookmark.
Do it now! You will need to access this information frequently.

P r i m i t i v e Typ e s
In Java, numbers, characters, and Boolean values are not objects but
Java has eight primitive types
for integers, floating-paint values of a primitive type. Table 1 shows the eight primitive types of
numbers, bytes, characters, the Java language.
and bool ean values. To indicate l ong constants, use a suffix L, such as 10000000000L. Sim­
ilarly, fl oat constants have a suffix F, such as 3 . 141S92 7F.
CHAPTER 1 A Crash Course in Java

Characters are encoded in Unicode, a uniform encoding scheme for characters in many
languages around the world. Character constants are enclosed in single quotes, such as
, a ' . Several characters, such as a newline ' \n ' , are represented as two-character escape

Type Size Range

; nt: 4 bytes -2,147,483,648 . . . 2,147,483,647

l ong 8 bytes -9,223,372,036,854,775,808L . . .


9,223,372,036,854,775,807L

short: 2 bytes -32768 . . . 32767

byt:e 1 byte -128 . . . 127

char 2 bytes ' \uOOOO ' . . . ' \u FFFF '


\
bool ean fV se , t: rue

doubl e 8 bytes approximately ± 1 . 79769313486231570E+308

fl oat: 4 bytes approximately ± 3.40282347E+38F

Ta b l e 1

The Primitive Types of the Java Language

Escape Sequence Meaning

\b backspace (\uOOO8)

\f form feed (\uOOOC)

\n newline (\uOOOA)

\r return (\uOOOD)

\t: tab (\uOOO9)

\\ backslash

\' single quote

\" double quote

\unln2n3n4 Unicode encoding

Ta b l e 2

Character Escape Sequences


1.3 Primitive Types

sequences. Table 2 shows the most common permitted escape sequences. Arbitrary
Unicode characters are denoted by a \u, followed by four hexadecimal digits enclosed in
single quotes. For example, ' \u 2 12 2 ' is the trademark symbol (TM) .

INTERNET You can find the encodings of tens of thousands of letters in many alphabets at
http : //www . uni code . o rg.

Conversions that don't incur information loss (such as short to i nt or fl oat to doubl e)
are always legal. Values of type char can be converted to i nt. All integer types can be
converted to fl oat or doubl e, even though some of the conversions (such as l ong to
doubl e ) lose precision. All other conversions require a cast:
doub 1 e x = 10 . 0 / 3 . 0 ; // sets x to 3.3333333333333335
i nt n = (i nt) x ; / / sets n to 3
fl oat f = (fl oat) x ; // sets f to 3.3333333
It is not possible to convert between the bool ean type and number types.
The Math class implements useful mathematical methods. Table 3 contains some of the
most useful ones. The methods of the Math class do not operate on objects. Instead,
numbers are supplied as parameters. (Recall that numbers are not objects in Java.) For
example, here is how to call the sq rt method:
doubl e y = Math . sq rt (x) ;
Since the method doesn't operate on an object, the class name must be supplied to tell
the compiler that the sqrt method is in the Math class. In Java, every method must
belong to some class.

Method Description

Math . sq rt (x) Square root of x, Fx

Math . pow (x , y) xY (x > 0, or x ° and y > 0, or x < ° and y is an integer)


=

Math . toRadi ans (x) Converts x degrees to radians ( i.e., returns


x . n/180)
Math . toDegrees (x) Converts x radians to degrees ( i.e., returns x 180/n)
.

Math . rou nd (x) Closest integer to x ( as a l ong )

Math . abs (x) Absolute value I x I

Ta b l e 3

Mathematical Methods
CHAPTER 1 A Crash Course in Java

C o n t r o l F l o w S ta t e m e n t s
The i f statement is used for conditional execution. The el se branch is optional.
i f (x >= 0) y = Math . sq rt (x) ; el se y = 0 ;
The whi 1 e and do statements are used for loops. The body of a do loop is executed at least
once.
whi l e (x < target)
{
x = x * a;
n++ ;
}
do
{
x = x * a;
n++ ;
}
whi l e (x < target) ;
The for statement is used for loops that are controlled by a 100F counter.
fo r (i = 1 ; i <= n ; i ++ )
{
x = x * a;
sum sum + x ;
}
A variable can be defined in a fo r loop. Its scope extends to the end of the loop.
for ( i n t = 1; i <= n ; i ++)
{
x = x * a;
sum sum + x ;
}
// i no longer defined here
Java 5.0 introduces an enhanced form of the fo r loop. We will discuss that construct later
in this chapter.

Obj e c t R e f e r e n c e s
In Java, an object value is always a reference to an object, or, i n other words, a value that
describes the location of the object. For example, consider the statement
G reete r wo rl dGreete r = new Greete r ( "Wo rl d " ) ;

An object reference describes


The value of the new expression is the location of the newly con­
the location of an object. In structed object. The variable wo rl dGreete r can hold the location of
Java, you manipulate object any Greete r object, and it is being filled with the location of the new
references, not objects. object (see Figure 6.)
1.5 Object References

wo rl dGreet e r
G re e t e r

name = "Wo r l d "

F i g u re 6

An Object Reference

There can be multiple variables that store references to the same object. For example,
after the assignment
Greeter anothe rGreete r = wo r l dG reete r ;
the two object variables refer to the same object (see Figure 7).

When you copy object refer­


If the Greete r class has a setName method that allows modification of
ences, the copy accesses the the object, and if that method is invoked on the object reference, then
same object as the original. both variables access the modified object.

anotherGreeter . setName ("Dave" ) ;


// now wo rl dGreete r also refers to the changed object
To make a copy of the actual object, instead of just copying the object reference, use the
cl one method. Implementing the cl one method correctly is a subtle process that is dis­
cussed in greater detail in Chapter 7. However, many library classes have a cl one
method. It is then a simple matter to make a copy of an object of such a class. For exam­
ple, here is how you clone a Date object:
Date aDate = . . . ;
Date anothe rDate = (Date) aDate . c l on e () ;
The cast (Date) is necessary because c l one is a generic method with return type Obj ect.
In Java, all classes extend the class Obj ect.
The special reference nul l refers to no object. You can set an object variable to nul l :
wo rl dGreete r = nul l ;
You can test if an object reference is currently nul l :
i f (wor l dGreete r == nul l ) . . .
If you invoke a method on a nul l reference, a Nul l Poi nterExcepti on
The nul l reference refers to
no object. is thrown. Unless you supply a handler for the exception, the program
terminates. (Exception handling is discussed later in this chapter.)

� G reet e r
wo rl dGreete r

anotherGreete r � I------{ name = "Wo r l d "

Figure 7

A Shared Object
CHAPTER 1 A Crash Course in Java

It can happen that an object has no references pointing to it, namely when all object vari­
ables that previously referred to it are filled with other values or have been recycled. In
that case, the memory that was used for storing the object will be automatically
reclaimed by the garbage collector. In Java, you never need to manually recycle memory.

NOTE If you are familiar with the C++ programming language, you will recognize that object
references in Java behave just like pointers in C++. In C++, you can have multiple pointers to
the same value, and a NULL pointer points to no value at all. Of course, in C++, pointers strike
fear in the hearts of many programmers because it is so easy to create havoc with invalid
pointers. It is sometimes said that Java is easier than C++ because it has no pointers. That
statement is not true. Java always uses pointers (and calls them references), so you don't have
to worry about the distinction between pointers and values. More importantly, the pointers in
Java are safe. It is not possible to create invalid pointers, and the garbage collector automati­
cally reclaims unused objects.

P a r a m e t e r P a s s in g
The object reference on which you invoke a method is called the implicit parameter. In
addition, a method may have any number of explicitparameters that are supplied between
parentheses. For example, in the call
myG reete r . setName ("Mars" ) ;
the reference stored in myG reete r is the implicit parameter, and the string "Mars" is the
explicit parameter. The explicit parameters are so named because they are explicitly
defined in a method, whereas the implicit parameter is implied in the method definition.
Occasionally, you need to refer to the implicit parameter of a method by its special name,
thi s. For example, consider the following implementation of the setName method:
publ i c cl ass Greete r
{

/**
Sets this greeter's name to the given name.
@param name the new name for this greeter
*/
publ i c voi d setName (Stri ng name)
{
thi s . name = name ;
}

}
The thi s reference refers to the object on which the method was
The t hi s reference refers to
the object on which a method invoked (such as myG reete r in the call myGreete r . setName ( "Mar s " ) ) .
was invoked. The name field i s set to the value o f the explicit parameter that i s also
called name. In the example, the use of the thi s reference was neces­
sary to resolve the ambiguity between the name field and the name parameter.
1.6 Parameter Passing

Occasionally, the thi s reference is used for greater clarity, as in the next example.

A method can change the state


In Java, a method can modifY the state of an object because the corre­
of an object whose reference sponding parameter variable is set to a copy of the passed object refer­
it receives. ence. Consider this contrived method of the G reeter class:

publ i c cl ass Greete r


{
/**
Sets another greeter's name to this greeter's name.
@param othe r a reference to the other Greeter
*/
publ i c voi d copyNameTo (Greeter other)
{
othe r . name = thi s . name ;
}

}
N ow consider this call:
G reete r wo rl dGreete r = new Greete r ( "Worl d " ) ;
G reete r daveG reete r = new Greet e r ( " Dave " ) ;
wo rl dGreete r . copyNameTo (daveGreete r) ;
Figure 8 shows how the other parameter variable is initialized with the daveGreete r
reference. The copyNameTo method changes othe r . name, and after the method returns,
daveG reete r . name has been changed.
However, in Java, a method can never update the contents ofa variable that is passed as a
parameter. For example, after the call
wo rl dGreete r . copyNameTo(daveG reete r) ;
the contents of daveGreete r is the same object reference before and after the call. It is
not possible to write a method that would change the contents of daveG reeter to
another object reference. In this regard, Java differs from languages such as C++ and C#
that have a "call by reference" mechanism.
To see that Java does not support call by reference, consider yet another set of contrived
methods. These methods try to modifY a parameter, but they have no effect at all.

� G reete r
daveG reete r

other � I-------l name = "Dave"

F i g u re 8

Accessing an Object through a Parameter Variable


CHAPTER 1 A Crash Course in Java

publ i c cl ass G reete r


{

/* ;'
Tries to copy the length of this greeter's name into an integer variable.
@param n the variable into which the method tries to copy the length
*/
publ i c voi d copyLengthTo (i nt n)
{
/ / this assignment has no effect outside the method
n = name . l ength () ;
}
/**
Tries to set another Greeter object to a copy of this object.
@param other the Greeter object to initialize
*/
publ i c voi d copyG reete rTo (Greeter other)
{
// this assignment has no effect outside the method

(
other = new G reete r (name) ;
}

}
Let's call these two methods:
i nt l ength = 0 ;
G reete r wo rl dGreete r = new G reete r ( "Wo rl d " ) ;
G reete r daveG reet e r = new Greete r ( "Dave " ) ;
wo rl dGreete r . copyLengthTo(l ength) ;
/ / has no effect on the contents of 1 ength
wo rl dGreete r . copyG reete rTo (daveG reeter) ;
/ / has no effect on the contents of daveG reete r

Neither method call has any effect. Changing the value of the param­
Java uses "call by value" when
passing parameters. eter variable does not affect the variable supplied in the method call.
Thus, Java has no call by reference. Java uses the "call by value" mech­
anism for both primitive types and object references.

Packages
Java classes can be grouped into packages. Package names are dot-separated sequences of
identifiers, such as
j ava . uti l
j avax . swi ng
com . su n . mi sc
edu . sj su . cs . cs1 5 1 . al i ce
1.7 Packages

Java uses packages to group


To guarantee the uniqueness of package names, the inventors of Java
related classes and to ensurerecommend that you start a package name with a domain name in
unique class names. reverse (such as com . s un or edu . sj s u . c s ) , because domain names are
guaranteed to be unique. Then use some other mechanism within your
organization to ensure that the remainder of the package name is unique as well.
You place a class inside a package by adding a package statement as the first statement of
the source file:
package edu . sj su . cs . cs151 . al i ce ;
publ i c cl ass G reeter
{

}
Any class without a package statement is in the "default package" with no package name.
ThefoIl name of a class consists of the package name followed by the class name, such as
edu . sj su . cs . cs15 1 . al i ce . Greete r . Some full class name examples from the Java library
are j ava . uti l . Ar rayLi st and j avax . swi ng . J Opti onPane.

The i mpo rt directive allows


It is tedious to use these full names in your code. Use the i mport
programmers to omit package statement to use the shorter class names instead. For example, after
names when referring to you place a statement
classes.
i mport j ava . uti l . Scanner ;
into your source file, then you can refer to the class simply as Scann e r. If you simulta­
neously use two classes with the same short name (such as j ava . uti 1 . Date and
j ava . sql . Date) , then you are stuck-you must use the full name for one of them.
You can also import all classes from a package:
i mport j ava . uti l . * ;
However, you never need to import the classes in the j ava . 1 ang package, such as Stri ng
or Math .

Organize your class files in Large programs consist of many classes in multiple packages. The
directories that match the class files must be located in subdirectories that match the package
package names. names. For example, the class file G reete r . c l ass for the class
edu . sj su . cs . cs 1 51 . al i ce . G reete r
must be in a subdirectory
edu/sj s u/cs/cs151/al i ce
or
edu\sj s u\cs\cs151\al i ce

of the project's base directory (see Figure 9). The base directory is the directory that con­
tains all package directories as well as any classes that are contained in the default pack­
age (that is, the package without a name).
CHAPTER 1 A Crash Course in Java

Base directory - [j
? [j edu
9 [j cs
� [j cs151
? [j alice
D Greeter.java

F i g u re 9

Package Name Must Match the Directory Path

Always compile from the base directory, for example


j avac edu/sj su/cs/cs151/al i ce/Greete r . j ava
or
j avac edu\sj su\cs\cs151\al i ce\Greete r . j ava
Then the class file is automatically placed in the correct location.

To run a program, you must start the Java virtual machine in the base directory and spec­
ifY the full class name of the class that contains the main method:
j ava edu . sj su . c s . cs 15 1 . al i ce . Greete r

B a s i c E x c e p ti o n Handling
When a program carries out a n illegal action, an exception i s generated. Here i s a com­
mon example. Suppose you initialize a variable with the nul l reference, intending to
assign an actual object reference later, but then you accidentally use the variable when it
is still nu 1 1 .
St ri ng name = nul l ;
i nt n = name . l ength () ; II Illegal

Applying a method call to nul l is illegal. The virtual machine now


When an exception occurs and
there is no handler for it, the throws a Nul l Poi nte rExcepti on. Unless your program handles this
program terminates. exception, it will terminate after displaying a stack trace (the sequence
of pending method calls) such as this one:
Exception i n th read " mai n " j ava . l ang . Nu1 1 Poi nte rExcepti on
at Greete r . sayHel l o (Greete r . j ava : 2 5)
at Greete rTeste r . mai n (Greete rTeste r . j ava : 6)

Different programming errors lead to different exceptions. For example, trying to open a
file with an illegal file name causes a Fi 1 eNotFound Excepti on.
1.8 Basic Exception Handling

You can also throw your own exceptions ifyou find that a programmer
Throw an exception to indicate
makes an error when using one of your classes. For example, if you
an error condition that the cur­
rent method cannot handle. require that the parameter of one of your methods should be positive,
and the caller supplies a negative value, you can throw an II I ega 1 -
ArgumentExcepti on:
i f (n <= 0) throw new Il l egal ArgumentExcepti on ( " n shou l d be > 0 " ) ;

There are two categories of


We will discuss the hierarchy of exception types in greater detail in
exceptions: checked and Chapter 6. At this point you need to be aware of an important dis­
unchecked. If you call a tinction between two kinds of exceptions, called checked exceptions and
method that might throw a unchecked exceptions. The Nul l Poi nte r Excepti on is an example of an
checked exception, you must unchecked exception. That is, the compiler does not check that your
either declare it or catch it.
code handles the exception. If the exception occurs, it is detected at
runtime and may terminate your program. The IOExcepti on, on the
other hand, is a checked exception. If you call a method that might throw this exception,
you must also specify how you want the program to deal with this failure.
In general, a checked exception is caused by an external condition beyond the program­
mer's control. Exceptions that occur during input and output are checked because the file
system or network may spontaneously cause problems that the programmer cannot con­
trol. Therefore, the compiler insists that the programmer provide code to handle these
situations.
On the other hand, unchecked exceptions are generally the programmer's fault. You
should never get a Nul l Poi nte rExcepti on. Therefore, the compiler doesn't tell you to
provide a handler for a Nul l Poi nte rExcepti on. Instead, you should spend your energy on
making sure that the error doesn't occur in the first place. Either initialize your variables
properly, or test that they aren't nul l before making a method call.
Whenever you write code that might cause a checked exception, you must take one of
two actions:
1. Declare the exception in the method header.
2. Handle (or catch) the exception.
Consider this example. You want to read data from a file.
publ i c voi d read (St ri ng fi l ename)
{
Fi l eRead e r reader = new Fi l eReade r (fi l ename) ;

}
If there is no file with the given name, the Fi l eReade r constructor throws a
Fi 1 eNotFoundExcepti on. Because it is a checked exception, the compiler insists that you
handle it. However, the implementor of the read method probably has no idea how to
correct this situation. Therefore, the optimal remedy is to let the exception propagate to its
caller. That means that the read method terminates, and that the exception is thrown to
the method that called it.
Whenever a method propagates a checked exception, you must declare the exception in
the method header, like this:
CHAPTER 1 A Crash Course in Java

publ i c voi d read (St ri ng fi l ename) throws Fi l eNotFoundException


{
Fi l e Reader reader = new Fi l eReade r (fi l ename) ;

TIP There is no shame associated with acknowledging that your method might throw a
checked exception-it is just "truth in advertising".

If a method can throw multiple exceptions, you list them all, separated by commas. Here
is a typical example. As you will see in Chapter 7, reading objects from an object stream
can cause both an IOExcepti on (if there is a problem with reading the input) and a
Cl assNotFound Excepti on (if the input contains an object from an unknown class). A
read method can declare that it throws both exceptions:
publ i c voi d read (Stri ng fi l ename)
th rows IOExcept i on , Cl assNotFoundException
When you tag a method with a th rows clause, the callers of this method are now put on
notice that there is the possibility that a checked exception may occur. Of course, thost,­
calling methods also need to deal with these exceptions. Generally, the calling methods
also add th rows declarations. When you carry this process out for the entire program, the
ma i n method ends up being tagged as well:
publ i c stati c voi d mai n (Stri ng [ ] args)
throws IOExcepti on , Cl assNotFoundExcepti on
{

}
If an exception actually occurs, the mai n method is terminated, a stack trace is displayed,
and the program exits.
However, if you write a professional program, you do not want the program to terminate
whenever a user supplies an invalid file name. In that case, you want to catch the excep­
tion. Use the following syntax:
t ry
{
code that might throw an IOExcepti on

}
catch (IOExcepti on excepti on)
{
take corrective action
}
An appropriate corrective action might be to display an error message
When an exception is thrown,
the program jumps to the clos­ and to inform the user that the attempt to read the file has failed.
est matching catch clause. In most programs, the lower-level methods simply propagate excep­
tions to their callers. Some higher-level method, such as mai n or a part
of the user interface, catches exceptions and informs the user.
1.9 Strings

For debugging purposes, you sometimes want to see the stack trace. Call the pri nt­
StackTrace method like this:
t ry
{
}
catch (IOExcepti on excepti on)
{
excepti on . p ri ntStackTrace () ;
take corrective action
}
Occasionally, a method must carry out an action even if a prior statement caused an
exception. A typical example is closing a file. A program can only open a limited number
of files at one time, and it should close all files that it opened. To ensure that a file is
closed even if an exception occurred during file processing, use the fi na 1 1 y clause:
Fi l eReade r reader = nu l l ;
reader = new Fi l eRead e r (name) ;
t ry
{
}
fi nal l y
{
reade r . cl oseO ;
}
Code in a fi na 1 1 y clause
The fi na 1 1 y clause is executed when the t ry block exits without an
is executed during normal exception, and also when an exception is thrown inside the t ry block.
processing and when an In either case, the cl ose method is called. Note that the Fi 1 eReader
exception is thrown. constructor is not contained inside the t ry block. If the constructor
throws an exception, then reade r has not yet been assigned a value, and
the cl ose method should not be called.

S tr i n g s
Java strings are sequences of Unicode characters. The charAt method yields the individ­
ual characters of a string. String positions start at O.
St ri ng g reeti ng "Hel l o" ;
=

char ch = g reeti ng . charAt (l) ; II sets ch to ' e '

A Java string is an
Java strings are immutable. Once created, a string cannot be changed.
immutable sequence of Thus, there is no setCharAt method. This may sound like a severe
Unicode characters. restriction, but in practice it isn't. For example, suppose you initialized
g reeti ng to " Hel l o " . You can still change your mind:
g reeti ng = "Goodbye" ;
The string object " Hel l o " hasn't changed, but g reeti ng now refers to a different string
object.
The 1 ength method yields the length of a string. For example, " Hel l o " 1 engt h O is 5.
.
CHAPTER 1 A Crash Course in Java

Figure 1 0
I' H 'I' e '1' 1 '1' 1 'I' 0 'I
o 1 2 3 4
Extracting a Substrin g '-y---'

Note that the empty string .. .. oflength 0 is different from nu1 1-a reference to no string
at all.
The substri ng method computes substrings of a string. You need to specifY the positions
of the first character that you want to include in the substring and the first character that
you no longer want to include. For example, "Hel l o " . substri n g C 1 , 3) is the string "e1 "
(see Figure 10). Note that the difference between the two positions equals the length of
the substring.
Since strings are objects, you need to use the equal s method to compare whether two
strings have the same contents.
i f Cg reeti ng . equa1 s C "Hel l o" ) ) . . . II OK
If you use the == operator, you only test whether two string references have the identical
location. For example, the following test fails:
i f C " Hel l o" . substri n g C 1 , 3) == "e1 " ) . . . II NO
The substring is not at the same location as the constant string "e1 " , even though it has
the same contents.
You have already seen the string concatenation operator: " Hel l o , + name is the con­ ..

catenation of the string " He 1 1 0 , and the string object to which name refers.
..

If either argument of the + operator is a string, then the other is converted to a string. For
example,
i nt n = 7 ;
Stri ng g reeti ng = " He l l o , .. + n;
constructs the string " He 1 1 0 , 7 " .
I f a string and a n object are concatenated, then the object i s converted to a string by
invoking its toSt ri ng method. For example, the toStri ng method of the Date class in
the j ava . uti 1 package returns a string containing the date and time that is encapsulated
in the Date object. Here is what happens when you concatenate a string and a Date
object:
II default Date constructor sets current date/time
Date now =new Date C) ;
St ri ng g reeti ng = " He l l o , + now ;
..

II g reeti ng is a string such as " Hel l o , Wed J an 18 16 : 5 7 : 18 PST 2006"


Sometimes, you have a string that contains a number, for example the string " 7 " . To con­
vert the string to its number value, use the I ntege r . parseInt and Doub1 e . parseDoub1 e
methods. For example,
Stri ng i nput = " 7 " ;
n = I ntege r . parseInt Ci nput) ; II sets n to 7
If the string doesn't contain a number, or contains additional characters besides a num­
ber, the unchecked Numbe rFo rmatExcepti on is thrown.
1.10 Reading Input

R e ading I n p u t

The Scanner class can be Starting with Java 5.0, the simplest way to read input in a Java pro­
used to read input from the gram is to use the Scanner class. To read console input, construct a
console or a file. Scan ner from System . i n . Call the nextInt or nextDoubl e method to
read an integer or a floating-point number. For example,
Scanner i n new Scanner(System . i n) ;
System . out . pri n t ( " How ol d are you? " ) ;
i nt age = i n . nextlnt () ;
If the user types input that is not a number, an (unchecked) InputMi smatchExcepti on is
thrown. You can protect yourself against that exception by calling the hasNextlnt or has­
NextDou bl e method before calling nextInt or nextDoubl e.
The next method reads the next whitespace-delimited token, and nextL i ne reads the
next input line.
You can read input from a file by constructing a Scanne r from a Fi 1 eReade r. For exam­
ple, the following loop reads all lines from the file i nput . txt:
Scanner i n = new Scanner (new Fi l eRead e r ( " i n put . txt ") ) ;
whi l e (i n . hasNextLi n e ( ) )
{
Stri ng l i ne = i n . nextLi n e () ;

Array L i s t s and L i n k e d L i s t s
The Ar rayL i st class of the j ava . uti 1 package lets you collect a sequence of objects of
any type. The add method adds an object to the end of the array list.
ArrayLi st<Stri ng> count ri es = new Ar rayLi st<St r i ng> () ;
countri es . ad d ( " Bel gi um") ;
countri es . add(" Ital y" ) ;
countri es . add ( "Thai l and " ) ;
Starting with Java 5.0, the Ar rayL i st class is a generic class with a type parameter. The
type parameter ( Stri ng in our example) denotes the type of the list elements. You can
form array lists of any type, except for primitive types. For example, you can use an
Ar rayL i st<Date> but not an Ar rayL i st<i nt>.
The s i ze method returns the number of elements in the array list. The get method
returns the element at a given position; legal positions range from ° to s i ze O - 1. For
example, the following loop prints all elements of the countri es list:
for (i nt i = 0 ; i < countri es . s i ze () ; i ++)
{
St ri ng country countri es . get ( i ) ;
System . out . pri ntl n (count ry) ;
}
CHAPTER 1 A Crash Course in Java

Figure 1 1

Inserting into an Array List

New value

t===::
t===

==:
This loop is so common that Java 5.0 introduces a convenient shortcut: the enhanced fo r
loop or "for each" loop:
fo r (Stri ng country : countri es)
System . out . p ri ntl n (count ry) ;
In each loop iteration, the variable before the : is set to the next element of the cou n­
tri es list.
The set method lets you overwrite an existing element with another:
count ri es . set ( l , " F rance " ) ;
If you access a nonexistent position « 0 or >= s i z e O ) , then an IndexOutOfBounds­
Excepti on is thrown.
Finally, you can insert and remove elements in the middle of the array list.
countri es . add ( l , "Ge rmany " ) ;
countri es . remove (O) ;
These operations move the remammg elements up or down. The
An array list is a collection of
objects that supports efficient name "array list" signifies that the public interface allows both array
access to all storage locations. operations ( get/set ) and list operations ( add/ remove ) .
Inserting and removing elements in the middle of an array list is not
A linked list is a collection of
efficient. All elements beyond the location of insertion or removal
objects that supports efficient
insertion and removal of ele- must be moved (see Figure 11). A linked list is a data structure that
ments. You use an iterator to supports efficient insertion and removal at any location. When insert­
traverse a linked list. ing or removing an element, all elements stay in place, and only the
neighboring links are rearranged (see Figure 12). The standard Java
library supplies a class L i nkedL i st implementing this data structure.

Figure 1 2

I nserting into a Linked List


1.11 Array Lists and Linked Lists

As with array lists, you use the add method to add elements to the end of a linked list.

Li nkedLi st<St ri ng> count ri es = new Li n kedLi st<St ri ng> () ;


count ri es . add ( " Bel gi um" ) ;
countri es . add ( " Ital y " ) ;
count r i e s . add ( "Thai l and " ) ;

However, accessing elements in the middle of the linked list is not as simple. You don't
want to access a position by an integer index. To find an element with a given index, it is
necessary to follow a sequence of links, starting with the head of the list. That process is
not very efficient. Instead, you need an iterator, an object that can access a position any­
where in the list:

Li stlte rator<Stri ng> i te rator = countri es . l i stlte rato r () ;

The next method advances the iterator to the next position of the list and returns the
element that the iterator just passed (see Figure 13). The hasNext method tests whether
the iterator is already past the last element in the list. Thus, the following loop prints all
elements in the list:

whi l e (i te rato r . hasNext ( ) )


{
Stri ng country = i te rato r . next () ;
System . out . p ri ntl n (coun t ry) ;
}
To add an element in the middle of the list, advance an iterator past the insert location
and call add:

i te rator = countri es . l i stlterato r () ;


i te rato r . next O ;
i te rato r . add ( " France " ) ;

To remove an element from the list, call next until you jump over the element that you
want to remove, then call remove. For example, this code removes the second element of
the countri es list.

i te rator = count ri es . l i stlterato r () ;


i te rator . next O ;
i te rator . next O ;
i te rato r . remove () ;

Figure 1 3

Iterator Movement

next n ext next


Another Random Document on
Scribd Without Any Related Topics
works.... Flagellations were superadded to these practices.... They
accordingly invented that system of barter celebrated under the title
of Indulgences.... A bull of Clement VII declared it an article of
faith.... The philosophers of Alexandria had spoken of a fire in which
men were to be purified. Many ancient doctors had adopted this
notion; and Rome declared this philosophical opinion a tenet of the
church. The pope by a bull annexed purgatory to his domain.”[82]
“The Catholic Church was not the papacy,” says D’Aubigné. “The
latter was the oppressor, the former the oppressed.” Draper tersely
defines the papacy as “the tyranny of theology over thought.”
Men departed from the simplicity of a gospel by Summary
faith. Reason and scientific research took the place
of faith in the Word. Education turned men’s minds from God to self,
and reason was exalted. The papacy was thus formed. If we look for
a visible union of the church and the state before recognizing it as
the papacy, we shall find ourselves entrapped; for it is the working
out of a system of education based on human philosophy that forms
the papacy; and the body which adopts this system of education
naturally turns to the state for support.
It is because of the truth of this statement that Papacy
the papacy wields its influence through its schools; overthrown by
this is why it has always feared a revival of learning Christian
education
more than the combined forces of all the armies of
the world. A death-blow to the papacy can be struck only by
introducing a system of education founded upon the teachings of
Christ, placing God’s Word as guide, and inspiring faith as the one
avenue to wisdom.
XI
EDUCATION OF THE MIDDLE AGES

The development of the papacy led directly to the Dark Ages, for
“the noontide of the papacy was the world’s moral midnight.” The
papacy was the logical working out of an educational scheme; hence
the moral darkness which spread over the world during the
prophetic period of twelve hundred and sixty years was due to
wrong methods of education. People do not sink into degradation
and sin when properly educated. Truth elevates, and, when
embodied in man, brings him nearer to his Maker. Faith is the ladder
by which he climbs, and when that element has been lacking in an
educational system, the masses have sunk lower and lower.
Mind is a wonderful thing, the most profound Papacy’s
study of the universe. It was designed to be free, tyranny of
to grasp the mighty laws of its own Creator, and a theology
thought
over

means was supplied by which that very thing could


be done: “If any of you lack wisdom, let him ask of God, ... but let
him ask in faith, nothing wavering.”
In order to maintain the supremacy thus gained, it was necessary
for the education of the young to lie wholly within the control of the
papal hierarchy; and it is with their educational institutions and
educational methods that we have now to deal. It is hoped that the
study of the Dark Ages will so accentuate the importance of
Protestants’ maintaining their own schools, that the tendency now so
strong in the other direction may receive a check. The education
begun in the schools of the early Christians has been followed into
the monastic institutions of the Middle Ages. The life and power of
Christianity departed, and form alone remained. It has been said
that “paganism in the garb of Christianity walked into the church,”
and it can truthfully be added that it gained admittance through the
schools.
In order to trace carefully the education offered Papal primary
by the papacy,—and that comprised all that was schools
then offered,—the first quotations are concerning
primary instruction. Laurie says: “Instruction began about the age of
seven. The alphabet, written on tables or leaves, was learned by
heart by the children, then syllables and words. The first reading-
book was the Latin psalter, and this was read again and again until it
could be said by heart; and numerous priests, and even monks,
were content all their lives with the mere sound of Latin words,
which they could both read and recite, but did not understand.”[83]
Note carefully that work for these children was Prominence of
almost wholly memory work. They were to learn by memory work
heart and to repeat without understanding. This
was the first step in that great system which binds the minds of the
masses to the will of one sovereign mind.
“Writing followed.” “The elements of arithmetic were also taught,
but merely with a view to the calculation of church days and
festivals.”[84]
“Latin was begun very early (apparently Early use of
immediately after the psaltery was known), with Latin
the learning by heart of declensions and
conjugations and lists of vocables. The rule was to use Latin in the
school in conversing.... In the eleventh century, if not earlier, Latin
conversation-books ... were not only read, but, like everything else,
learned by heart.”[85] Their method of studying Latin emphasizes the
thought of the formal abstract way of teaching, which tended to
conservatism and mental subjection. “Memory is the faculty that
subordinates the present under the past, and its extensive training
develops a habit of mind that holds by what is prescribed, and
recoils from the new and untried. In short, the educational
curriculum that lays great stress on memorizing, produces a class of
conservative people.”[86] The papal schools employed methods
which, in themselves, in the course of a few generations would
develop dependent rather than independent thinking; therefore
methods are as important as the subject taught.
Again it is well to remember that there was a Result of
deep design in making the Latin tongue universal. universal
It was one of the ways by which the papacy kept language
its control of all nations and tongues. Draper explains it thus:—
“The unity of the church, and, therefore, its power, required the
use of Latin as a sacred language. Through this Rome had stood in
an attitude strictly European, and was enabled to maintain a general
international relation. It gave her far more power than her asserted
celestial authority.... Their officials could pass without difficulty into
every nation, and communicate without embarrassment with each
other, from Ireland to Bohemia, from Italy to Scotland.”[87]
The character of the youth was formed, says Fables and
Painter, from memorizing “the fables of Æsop and traditions of
collections of maxims and proverbs. After this, men
Virgil was usually the text-book, and was handled in the same style.”
Of the monastic schools Mosheim says: “In most Studies of
of the schools, the so-called seven liberal arts were Monastic
taught. The pupil commenced with grammar, then schools
proceeded to rhetoric, and afterward to logic or dialectics. Having
thus mastered the Trivium, as it was called, those who aspired to
greater attainments proceeded with slow steps through the
Quadrivium [a course including arithmetic, music, geometry, and
astronomy] to the honor of perfectly learned men.”[88]
Says Painter: “Seven years were devoted to the completion of the
course in liberal arts [the Trivium and the Quadrivium].... Dialectic or
logic was based somewhat remotely on the writings of Aristotle. At a
later period, logic was rigidly applied to the development of
theology, and gave rise to a class of scholars called the schoolmen....
Arithmetic was imperfectly taught, importance being attached to the
supposed secret properties of numbers. Geometry was taught in an
abridged form, while astronomy did not differ materially from
astrology. The study of music consisted chiefly in learning to chant
the hymns of the church.”[89]
Mosheim thus continues his description of the Greater
work of the schools in the eleventh century: “This emphasis on
course of study, adopted in all the schools of the logic
West, was not a little changed after the middle of this century. For
logic, ... having been improved by the reflection and skill of certain
close thinkers, and being taught more fully and acutely, acquired
such an ascendency in the minds of the majority, that they neglected
grammar, rhetoric, and the other sciences, both the elegant and the
abstruse, and devoted their whole lives to dialectics, or to logical and
metaphysical discussions. For whoever was well acquainted with
dialectics, or what we call logic and metaphysics, was supposed to
possess learning enough, and to lose nothing by being ignorant of all
other branches of learning.... In this age, the philosophy of the
Latins was confined wholly to what they called dialectics; and the
other branches of philosophy were unknown even by name.
Moreover their dialectics was miserably dry and barren.”[90]
This is sufficient, perhaps, on the use of Patristical
language and logic, and we turn to geography and Geography
some of the sciences. Even the children to-day will
smile at the teachings of some of the Church Fathers on the subject
of geography. Says Draper: “In the Patristic Geography the earth is a
flat surface bordered by the waters of the sea, on the yielding
support of which rests the crystalline dome of the sky. These
doctrines were for the most part supported by passages from the
Holy Scriptures, perversely wrested from their proper meaning. Thus
Cosmas Indicopleustes, whose Patristic Geography had been an
authority for nearly eight hundred years, triumphantly disposed of
the sphericity of the earth by demanding of its advocates, how, in
the day of judgment, men on the other side of a globe could see the
Lord descending through the air!”[91]
It was in opposition to such theories, and a The beneficial
hundred absurdities concerning the ocean, the work of
boiling waters of the equator, the serpents in the explorers
West, etc., that Columbus, De Gama, and other explorers had to
contend; and one of the most wonderful effects of the work of these
navigators was the thrust given papal education. A wound was then
received which was incurable.
If, in the mind of the reader, the question arises, Why should the
papal schools teach such things? simply consider that the whole
system of papal theology was intended to make the people feel that
the world was the center of the universe, and that the pope was the
center of the world. Christ and his position in creation were usurped
by the head of the church. This was the papacy.
This could be brought about only by education, Modern schools
and could be maintained only as generation after cling to papal
generation was taught from infancy to old age to methods
place faith in man, not God. Not only the subjects taught, but the
manner of teaching them, served well the purpose of the papacy.
Only within the last few years, comparatively speaking, have our
own schools seen the necessity of breaking away from some of
those relics of the educational system of the Dark Ages.
Memory work, pure and simple, has given way in Detection of
a great measure to research and experiment, even wrong methods
in the primary grades. The alphabet is no longer
driven into the childish mind by the ferule, nor kept there by mere
force of repetition. The advanced methods in dealing with the mind
are a step in the right direction. The pity is that educators, while
groping for light, while casting off some of the moth-eaten garments
of past ages, have failed to see the cause of the evil, and deal so
largely with results instead of removing the cause. The evil began by
renouncing the Scriptures and faith in Holy Writ as a part of
education. The spirit and power will accompany reform only when
these are replaced in their proper setting.
While educators of the world are realizing the New books
need of a change in methods, it is time for them to
see also the need of a change in subject matter and text-books.
Protestants in particular should arouse to the times. If the study of
paganism, instead of Christianity or truth, produced the Dark Ages,
and if wrong methods held the minds of men and prolonged that
darkness, forbidding the shining of the light, it is time for both
methods and material to be reconstructed in the schools of to-day.
We can with profit notice the attitude of the Science in the
papal schools toward some of the sciences, taking papal schools
for example that most practical of modern
branches, the science of medicine. What was the work of the
physician during the Dark Ages? Draper says: “Physicians were
viewed by the church with dislike, and regarded as atheists by the
people, who held firmly to the lessons they had been taught, that
cures must be wrought by relics of martyrs and bones of saints, by
prayers and intercessions.”[92]
It is well to remember that Christ was the Great True healing
Physician, healing not only soul maladies, but forsaken
physical infirmities as well; and to the apostles was
given the commission to heal the sick and restore sight to the blind.
Gradually, however, as the power of the gospel in its purity was lost
by the substitution of error for truth, the leaders of the church
introduced miracle cures, and preached the efficacy of the bones of
saints, etc., in the cure of disease. This became popular, and
increased throughout the Dark Ages.
Draper describes the fanaticism of the monastic Medical study
schools, and finally assigns a reason for the discouraged
exclusion from them of the study of physiology and
anatomy and the science of medicine. “The body,” he says, “was
under some spiritual charge,—the first joint of the right thumb being
in the care of God the Father, the second under that of the blessed
Virgin, and so on of other parts. For each disease there was a saint.
A man with sore eyes must invoke St. Clara, but if it were an
inflammation elsewhere, he must turn to St. Anthony.... For the
propitiation of these celestial beings it was necessary that fees
should be paid, and thus the practice of imposture—medicine
became a great source of profit. In all this there was no other
intention than that of extracting money.”[93]
While such was the teachings of the papacy, the Doctors in
Jews and Mohammedans were achieving wonderful secret
success, and making discoveries of lasting benefit
to mankind in Spain and Asia Minor. “Bishops, princes, kings, and
popes had each in private his Hebrew doctor; though all understood
that he was a contraband luxury, in many countries pointedly and
absolutely prohibited by the law. In the eleventh century nearly all
the physicians in Europe were Jews.” One reason for this was: “The
church would tolerate no interference with her spiritual methods of
treating disease, which formed one of her most productive sources
of gain; and the study of medicine had been formally introduced into
the rabbinical schools.”[94]
The bitter hatred of the papacy toward Jewish
independence of mind is well illustrated in the physicians
treatment that the Jewish physicians received from prohibited
the popes. Draper says: “The school at Salerno was still sending
forth its doctors. In Rome, Jewish physicians were numerous, the
popes themselves employing them.... At this period Spain and
France were full of learned Jews; and perhaps partly by their
exerting too much influence upon the higher classes with whom they
came in contact (for the physician of a Christian prince was very
often the rival of his confessor), and partly because the practice of
medicine, as they pursued it, interfered with the gains of the church,
the clergy took alarm, and caused to be re-enacted or enforced the
ancient laws. The Council of Beziers (a.d. 1246) and the Council of
Alby (a.d. 1254) prohibited all Christians from resorting to the
services of an Israelitish physician.”[95]
To show that this was a matter which concerned Hatred of
the schools, and in proof of the statement that
papal schools still adhere to formalism, miracle physicians
cure, and relic worship, we need only to notice that
“the faculty of Paris [University], awakening at last to the danger of
the case, caused, a.d. 1301, a decree to be published prohibiting
either man or woman of the religion of Moses from practicing
medicine upon any person of the Catholic religion. A similar course
was pursued in Spain. At this time the Jews were confessedly at the
head of French medicine. It was the appointment of one of their
persuasion, Profatius, as regent of the faculty of Montpellier, a.d.
1300, which drew upon them the wrath of the faculty of Paris.”
“The animosity of the French ecclesiastics Jews banished
against the Jewish physicians at last led to the
banishment of all the Jews from France, a.d. 1306.”[96] The papal
universities were unwilling to teach medicine, and finding that the
Jewish schools of science were greatly weakening papal authority in
France, this race was banished bodily.
Comparing this history with the present work of Position of
the medical fraternity, and especially with that class physiology
of medical students whose life work is to spread
the gospel while relieving the body, one better understands that
physiology should be the basis of every educational effort, and the
place that it and kindred sciences should occupy in the courses of
instruction pursued by our children, youth, and maturer minds; and
also the cause of that spiritual darkness which is even now hanging
over the world, and for centuries held Europe in its clutches; but it
shall be pierced by Christian education.
The papacy, in case of opposition which Papal method
threatened her authority, had two methods of of meeting
procedure. The first was an attempt to annihilate opposition
both the trouble and the troublers. Thus she simply banished all
Jews from France that her own universities might not be
overshadowed by the light of truth. Her second method of procedure
was a counter-reformation; that is, if a reform in education arose
outside the church which threatened to undermine her doctrines, it
might be met by a partial reform within her borders, the reform
going only so far as was absolutely necessary to satisfy the cravings
of minds that dared think for themselves.
It was not always possible to completely crush a Papacy can
reformation, or the reformers; and as was quite compromise
often the case in the schools, studies which could
not be entirely banished, were taught, but in such a way as best to
conserve the needs of the church. That medicine, as well as law,
was taught in the higher papal schools, can not be denied. Says
Mosheim: “The seven liberal arts [The Trivium and the Quadrivium]
were gradually included under the term philosophy; to which were
added theology, jurisprudence, and medicine. And thus these four
faculties, as they are called, were in the next century formed in the
universities.”[97]
But in the study of medicine, as in philosophy or Medical study
law, memory work devoid of understanding—the corrupted
form without the spirit—was the characteristic. As
the saints and martyrs in theology had taken the place of the Greek
gods and goddesses, so in the study of other branches a multitude
of pagan terms, clothed with what was then known as the “Christian
spirit,” was made to satisfy the longing for real mental culture. The
simplicity of the gospel was laid aside. What God had revealed was
made to appear too complex for the human mind, and the secret
things which are known only to God were pried into. In theology,
dialectics, or logic, became the study of endless queries, difficult
syllogisms, meaningless quibbles. Men delighted in propounding
such questions as, “How many angels can stand on the point of a
needle?” and others prided themselves on the acuteness of their
reasoning powers in arguing such questions. Likewise in medicine,
the study of the simple needs of the body and the rational treatment
of disease was obscured by hundreds of Latin terms, and these were
memorized to the neglect of the simple philosophy of the science. It
is with this multitude of names, hoary with age, and savoring
strongly of their pagan origin, that the student of medicine is still
compelled to grapple.
The history of the rise of European universities The Arabs as
throws light on the attitude of the papacy toward educators
education. While Europe was overspread by
spiritual and intellectual darkness, God used another people to
disseminate truth. When faith in God was lost, and in its place was
substituted that blind faith in man and obedience to the church
which is known in European history as the age of faith, learning was
propagated by the Arabs. That power which had failed to conquer
the world by the sword, now gained by intellectual culture what the
arms of Mohammed and his immediate successors failed to achieve.
Spain, while in the hands of the Moors, contributed more to
European civilization than at any other time in her history; and it
was as an educator and through the influence of her schools that
the papacy received its blow from the south which made her more
readily succumb to the revolt of Germany under Luther. By the Arabs
“flourishing schools were established in all the principal cities,
notably at Bagdad and Damascus in the East, and at Cordova,
Salamanca, and Toledo in the West. Here grammar, mathematics,
astronomy, philosophy, chemistry, and medicine were pursued with
great ardor and success. The Arabians originated chemistry,
discovering alcohol, and nitric and sulphuric acids. They gave
algebra and trigonometry their modern form; applied the pendulum
to the reckoning of time; ascertained the size of the earth by
measuring a degree, and made catalogues of the stars.”[98] And all
this was done when Europe as a whole was lying in darkness, when
the chemist was considered a wizard, when astronomy was merely
astrology, and whatever learning existed was formal and spiritless.
But the discoveries of the Arab teachers could Arabs and papal
not long remain with them alone, and it is with the schools
spread of their ideas through the schools by means
of the students that we are concerned. “For a time they [the Arabs]
were the intellectual leaders of Europe. Their schools in Spain were
largely attended by Christian youth from other European countries,
who carried back with them to their homes the Arabian science, and
through it stimulated intellectual activity in Christian [papal]
nations.”[99]
The specialization of studies such as theology, Arabs and
medicine, or philosophy, together with the impulse universities
derived from the Mohammedans in Africa and the
Arabs in Spain, led to the establishment of the universities, which
were, as before stated, composed of four faculties, or colleges.
“They arose independently of both church and state.” The University
of Paris “became the most distinguished seat of learning in Europe.
At one time it was attended by more than twenty thousand
students.”
The growth of the universities was very rapid, Papacy seized
and they threatened speedily to revolutionize the universities
society of Europe and overthrow the papal
hierarchy. “The influence and power of the universities were speedily
recognized,” says Painter; “and though originally free associations,
they were soon brought into relation with the church and the state,
by which they were officially authorized and endowed.” If learning
could not be suppressed, then it must be controlled by the church;
and the “church sought to attach them [the universities] to itself, in
order to join to the power of faith the power of knowledge. The first
privileges that the universities received proceeded from the popes.”
“While Rome was not the mother, she was yet the nurse of
universities.” Scientific investigation had by this time received such
an impulse from youth who had been students in the Arab schools
that the church could not hope to crush it. The only hope of the
papacy was to so surround the truth with fables and mysteries, and
to so conduct the schools, that again the spirit of progress would be
lost in its labyrinthine wanderings through empty forms. Monopoly in
education works havoc in the same way that a monopoly in
commerce leads to oppression. And so it was.
“The students led a free and uncontrolled life, Character of
seeking and finding protection in their own students
university authorities even from the civil
power.”[100]
Youth from the age of twelve and upward Origin of
attended these universities, making it necessary to courses and
teach the secondary studies which terminated in a degrees
bachelor’s degree. “Boys ... attended the Parisian university merely
for instruction in ... grammar, rhetoric, and dialectic; and after three
or four years’ study they received the title of Baccalaureus.” “When
he reached ... the age of seventeen or eighteen, he then began the
study for the mastership.”[101]
It will be remembered that the schools established by the early
church were marked for the simplicity of their methods, and their
singleness of purpose. Their object was to educate workers for the
spread of the gospel. For the accomplishment of this object the
course of instruction was arranged, and students were sent forth
into the world commissioned of God, as were the disciples after their
ordination. There was no call for the granting of degrees. These, it is
true, were used in the pagan schools, and indicated that the receiver
had been initiated, after years of study, into the hidden mysteries of
Greek wisdom. Among the pagans, indeed, the principle of degrees
and diplomas dated back to the days of Egyptian and Babylonian
supremacy, where it was indicative of fellowship in the grossest
forms of licentiousness.
Greece, the country which united the learning of Babylon and the
wisdom of Egypt, and offered it to Europe in the form of Platonism,
naturally enough made use of diplomas and degrees. And the fact
that her wisdom was so complicated in its nature made it necessary
to spend long years in mastering her sciences.
Paganism, moreover, has but one model for all men; its aim is
ever to crush individuality and mold all characters alike. To
accomplish this purpose the schools arranged their studies in
courses, demanding that each student should pass over the same
ground. This is characteristic of all educational systems aside from
that one, the true education, which comes from God. If you look to
China, you find it there, as it develops the disciples of Confucius;
India educates her Brahmans in the same manner; the priests and
wise men of Egypt were taught in schools of a similar type. The
Jews had aped the fashion of the pagan world, and it was from this
custom that Christ called his disciples. One of the surest signs that
the schools established in the days of Christian purity had lost the
spirit which characterized the apostolic teaching, is the fact that the
schools of the Middle Ages had adopted this pagan custom.
Students were called into the universities when mere boys, and by
hundreds and thousands were run through the “grind” which we
term “course of instruction,” and were turned out at the end of ten,
twenty, and sometimes even forty years with a degree, which, in
dignity, corresponded to the years spent in completing the course.
This custom is papal. It is opposed to the very spirit of
Christianity; and any institution of learning which deigns to accept
the approval of the state, while at the same time passing as a
Christian institution, is not only linking itself with the papacy, but
with paganism as well. Of His followers Christ says, “They are not of
the world, even as I am not of the world.”
“Older students, those especially in the theological faculty, with
their fifteen or sixteen years’ course of study, achieved in this
respect far greater notoriety. At the age of thirty or forty the student
at the university was still a scholar.”[102] The idea of long courses is
not, then, a modern one, and American colleges can truthfully point
to the university of Paris for the precedent in this respect as in some
others. In the granting of degrees another interesting subject is
approached. Laurie continues: “Up to the middle of the twelfth
century, anyone taught in the infant universities who thought he had
the requisite knowledge.... In the second half of the twelfth century,
when bishops and abbots, who acted, personally or through their
deputies, as chancellors of the rising university schools, wished to
assume to themselves exclusively the right of granting the license, ...
Pope Alexander III forbade them, on the ground that the teaching
faculty was a gift of God.”[103] This, however, must have been the
work of a liberal pope, for earlier,—that is, in 1219,—“Pope Honorius
III interfered with the granting of degrees; and in order to impose a
check on abuses, directed that they should be conferred not by, but
by permission of, the archdeacon of the cathedral, and under his
presidency.”[104]
The church had gained control of the universities, and through her
representative, usually the chancellor, granted degrees. Now, in
order to keep the authority well in her own hands, no one was
allowed to teach who did not hold a license granted by the university
after an examination. Thus the educational trust developed, and the
iron hand of Rome, though concealed in a silken glove, clinched her
victories, and strove to crush all opponents.
Our modern B.S., M.A., LL.D., D.D., etc., were Degrees and
adopted into the universities at this stage of the papacy
educational history. “Itter informs us,” says Laurie,
“that ... a complete university course was represented by four
degrees—bachelor, master, licentiate, and finally doctor, which last
was usually taken at the age of thirty or thirty-five.” “The next
development of the degree system was the introduction of the
grades of bachelor and master, or licentiate, into each of the higher
faculties—theology, law, and medicine. Thus a man who had finished
his preliminary art studies, generally at the age of twenty-one, and
wished to specialize in theology, medicine, or law, had to pass
through the stages of bachelor of theology, or of medicine, or of law,
and then of master or licentiate, before he obtained the title of
doctor. The bachelorship of medicine or law was reached in three
years, of theology in seven. Four years’ further study brought the
doctor’s degree.”[105] “The conferring of degrees was originated by a
pope.”[106] The educational monopoly appeared quite complete; and
having gained the form of godliness and the civil power, the old
scheme of killing the life and substituting those things which would
recognize the papal hierarchy, were again introduced. Leading
educators are awakening to the true situation. Christian education
alone can deliver.
“The moral tone of the universities was low,” Form had
says Painter; “there were brawls, outbreaks, and replaced the life
abominable immoralities. ‘The students,’ say the
Vienna statutes, ‘shall not spend more time in drinking, fighting, and
guitar playing than at physics, logic, and the regular courses of
lectures; and they shall not get up public dances in the streets.
Quarrelers, wanton persons, drunkards, those that go about
serenading at night, or who spend their leisure in following after
lewd women; thieves, those that insult citizens, players at dice—
having been properly warned and not reforming, besides the
ordinary punishment provided by law for those misdemeanors, shall
be deprived of their academical privileges and expelled.’ These
prohibitions give us a clear insight into university life of the time, for
it was not worse at Vienna than at Paris and elsewhere.”[107]
Could some of those medieval students be resurrected and placed
in some of the universities of the nineteenth century, they might feel
quite at home, not only as far as courses of study and the granting
of degrees is concerned, but in revelings, parties, etc., judging from
the reports of the hazing, drinking, and general carousing of the
students in our university towns.“[108] The conduct of students is the
reflex of the instruction given. It is not, therefore, to be wondered at
that the instruction of the universities, containing as it did the form
without the life, should fail to develop stability of character in its
students.
“The true Catholic attitude to all investigation was, and is, one
admitting of great advances in every department of learning, while
checking all true freedom of thought.”[109]
The North American Review for October, 1842, expresses in
concise language the relation of students and schools to the general
government and consequent state of society. It says: “In the
colleges is determined the character of most of the persons who are
to fill the professions, teach the schools, write the books, and do
most of the business of legislation for the whole body of the people.
The general direction of literature and politics, the prevailing habits
and modes of thought throughout the country, are in the hands of
men whose social position and early advantages have given them an
influence, of the magnitude and permanency of which the
possessors themselves are hardly conscious.”
Recognizing this fact, the papacy controlled the education of the
Middle Ages, and is to-day seeking to do the same thing. Luther and
other reformers, also recognizing this fact, sought to overthrow the
tyranny of the papacy by establishing new schools where freedom of
thought would be fostered through faith in God’s Word.
Protestants to-day, looking upon the system of Work for
education as it now exists, and tracing there the Protestants to-
same long courses in the classics and the sciences; day
the same degrees granted in a manner similar to the Dark Ages, the
text-book containing the same theories, the same terms, the same
doctrines of philosophy; the same tendency toward monarchism, or
the monopoly of education by certain universities, and through them
by the same power that has borne sway, should, for the sake of their
government, and for the sake of their faith, establish schools of their
own. As the papacy, by the subjection of thought, builds up a
monarchy in place of democracy; as she in the same way overthrows
faith in God, substituting faith in man or the church, so Protestant
schools should educate children in the pure principles of that gospel
freedom which recognizes the equality of every man in the sight of
heaven, and makes it possible for the government to be of, for, and
by the people by developing the Christian character through faith in
Jesus Christ.
XII
THE SIXTEENTH CENTURY REFORMATION AN
EDUCATIONAL REFORM

While following the history of education through the Dark Ages,


we have often been compelled to recognize that an influence was at
work slowly but surely undermining the structure which the papacy
was, with the greatest perseverance, erecting, and which that power
purposed should withstand all the attacks brought against it. The
papacy had calculated well; it had, in absorbing the educational
system of the times, laid its hand on the very tap-root of society,
and, in its education as well as in its doctrines, woven about the
human race meshes which only the Prince of heaven could rend with
the sword of eternal truth.
Never has the world seen such an enduring Secret of papal
system as the papacy. Patterned so nearly after the strength
truth of God, and resembling so closely, both in
church government and educational principles, the plan delivered to
the chosen nation, that only an expert, guided by the Spirit of truth,
could judge between the true and the counterfeit, it had, as had the
Jews before them, replaced the life by the mere form. Nevertheless,
so firmly laid was the foundation, and so substantially built were the
walls, that for centuries it baffled all attempts at overthrow.
This structure had as its foundation an educational system; the
mortar which held the bricks in the wall was educational methods,
and should the building fall, the foundation itself must be attacked.
As a civil power, the papacy was periodically attacked by ambitious
kings and princes; but these shocks scarcely disturbed the serenity
of the papal head, so firm was his throne. The sword of the
Mohammedans was broken at Tours; and the Crescent, instead of
advancing to the full by encircling the Mediterranean, waned as its
light receded to the shores of Africa and the west of Asia.
What the Turk could not do by force of arms, he The revival of
did in another way. In 1453 Constantinople fell into learning
the hands of the calif, yet this did not affect the
strength of the papal hierarchy. But as the Turk came into Greece,
Greek art and literature fled to Italy. Here is the attack on the
papacy which came from the east. Painter says: “The revival of
classical learning, which had its central point in the downfall of
Constantinople in 1453, exerted a favorable influence. It opened the
literary treasures of Greece and Rome, provided a new culture for
the mind, awakened dissatisfaction with the scholastic teaching of
the church, and tended to emancipate thought from subjection to
ecclesiastical authority.”[110] The taking of Constantinople did still
more toward hastening the Reformation. Venice had controlled the
commerce of the eastern Mediterranean, but Turkish supremacy in
those waters transferred that power to her rival, Genoa, on the other
side of Italy; and from this latter center began the search for a
western passage to the East Indies which led to the accidental
discovery of America.
Again, “The revival of learning was so intimately Greek classics
related to the Reformation, and to the educational
advancement dating from that time, that it calls for consideration in
some detail. It had its origin in Italy.... Eager scholars from England,
France, and Germany sat at the feet of Italian masters, in order
afterward to bear beyond the Alps the precious seed of the new
culture.”[111] However, this Greek culture, or new learning, was
nothing more nor less than a revival of the study of Greek paganism.
Notwithstanding that fact, a life and enthusiasm attended its study
which drew students from the papal universities, and induced men
to travel hundreds of miles for the sake of sitting at the feet of
masters of the Greek classics.
This was the attempted reform of the papacy made by classic
literature. Its results can not but interest us. Painter further says:
“The revival of letters produced different results in different
countries. Everywhere it contributed to the emancipation of the
human mind, but in Italy it tended strongly to paganize its
adherents.”
Bear in mind that the classics were attempting to reform the
papacy. Here was the result in Italy. Italian schools undoubtedly
needed reforming, for the words of Luther describing German
schools are applicable to all papal institutions. Of these he said:
“What have they been taught in the universities and convents, but to
become blockheads? A man has studied twenty, forty years, and has
learned neither Latin nor German.” But as much as reform was
needed, Greek classics “in Italy tended strongly to paganize its
adherents.” We can not look for the classics, then, to Christianize the
Italian papists.
But while “in Italy the new learning became a Greek in
minister of infidelity, in Germany [it became a German schools
minister] of religion.” Why this difference? The
work of Erasmus, Luther, and Melancthon, as they introduced the
study of the Greek and Hebrew Scriptures into the German schools,
will answer why. The Italians studied the Greek classics for the
thought, and it paganized its adherents; the Germans studied the
Greek New Testament, translating it into the mother tongue, and it
became one of the greatest helps in the spread of the Reformation
of the sixteenth century.
So much for the attempted reform by Greek classics. They played
their part, but they could not overthrow the papacy; and why should
we expect it when papal education was, in the first place, built upon
those same classics and the philosophy of Greek writers?
We now turn to the southern attack upon the Papacy and
papal system. This was also an educational attack. Arab education
Already we have seen the Arab schools in Spain.
Before the eleventh century Christian youth attended these schools,
taking across the Pyrenees the science of the Moors. The papacy
quailed before this attack, and in order to lessen its force, the
sciences of the Arabs were adopted in the papal universities. This, as
we have already seen, was done in medicine and mathematics. But
again the form was retained without the life. France, because of her
jealousy of the Jewish physicians, through the influence of the
University of Paris, banished every Jew from her borders. A scientific
attack could not overthrow the papacy.
However, the Moors went quietly on in their Science and
scientific discoveries; and when the fall of discovery of
Constantinople closed the eastern route to the America
Indian Ocean, and Genoa wanted a western route, Spain was
prepared to offer sailors the necessary charts and maps, compasses,
and other mariners’ instruments. Her astronomical studies, celestial
maps, and measurements of the degrees on the earth’s surface
encouraged voyages both to the south and west, in direct
contradiction to the theories of the patristic geographies. When
Columbus asked aid at the Spanish court to fit vessels for the tour
across the Atlantic, it is strange to note that the wife of the king of
Spain, who took from the Moors the keys of Granada, and drove the
Arab and his learning out of Europe, was the same woman who
pledged her jewels to this man,—a man, who, dependent upon
Arabic scientific investigation, discovered a world where those same
truths might be planted, and mature untrammeled by papal tyranny.
I say this was more than a coincidence. The hand of God was in it;
and, as D’Aubigné says: “He prepares slowly and from afar that
which he designs to accomplish. He has ages in which to work.”
While scientific knowledge could not overthrow Science and the
the papacy, it had its part to play along with the Reformation
classics. When men were spiritually dead, and the
Word of God was hidden, minds were freed from papal thraldom by
the work of the scientist and the classical student. Bear in mind,
however, that the classics helped only as they offered the Scriptures;
and science helped only as it opened men’s minds to the reception
of the truths of God’s Word. Mighty forces were at work: the earth
itself must be moved, and the fulcrum whereon rested the lever by
which it was to be turned in its orbit was the throne of God, and the
Word of the Eternal was the moving power. Men, weak in
themselves but resolute in purpose, were the instruments in the
hand of God to accomplish a task which ages had waited for, and
principalities and powers in heavenly places had longed to see.
The Reformation was not the work of a year, nor Reformation
yet of one man, even in Germany. It was the and education
gradual work of a system of education, and that
system was the same as had formerly been given to Israel, as had
been exemplified and amplified in the life of Christ, and was at the
time of the Reformation to be revealed, little by little, as men’s
minds, long darkened by oppression, were able to grasp it.
Agricola, known as the father of German Forerunners of
humanism, was one of the earliest reformers, and the
his attitude as a teacher and his expressions Reformation
concerning education prove the fact that the Reformation began in
the educational institutions. This man was for a time “a pupil of
Thomas à Kempis; he passed several years at the university of
Louvain; subsequently he studied at Paris, and afterward in Italy,” so
that he was well acquainted with the institutions of the day. He
became a teacher at Heidelberg. At the age of forty-one he began
the study of Hebrew, in order to read the Hebrew Bible.
He was urged to take charge of a school at Agricola’s ideas
Antwerp, but refused, expressing his opinion of the of the school
school in this advice sent to the authorities: “It is
necessary to exercise the greatest care in choosing a director for
your school. Take neither a theologian nor a so-called rhetorician,
who thinks he is able to speak of everything without understanding
anything of eloquence. Such people make in school the same figure,
according to the Greek proverb, that a dog does in a bath. It is
necessary to seek a man resembling the phœnix of Achilles; that is,
who knows how to teach, to speak, and to act at the same time. If
you know such a man, get him at any price; for the matter involves the
future of your children, whose tender youth receives with the same
susceptibility the impress of good and of bad examples.”
His ideas concerning methods were as clear as Recognizes
those expressed on the subject of schools and the errors of papal
character of the teacher. He was evidently able to system
see things in advance of his age, and in the spirit of a seer can
truthfully be classed with the forerunners of the Reformation. In
another letter he writes: “Whoever wishes to study with success
must exercise himself in these three things: in getting clear views of
a subject; in fixing in his memory what he has understood; and in
producing something from his own resources.” Each of the three
things specified cuts directly across the methods employed in papal
schools, and which were so necessary to the stability of that
hierarchy. This was the beginning of the Reformation as seen in
education.
One more quotation from Agricola’s letter Thought versus
emphasizes the thought that schools were then mere form
conducted where dry form and abstract memory
work were giving place to thought,—original thought. “It is
necessary,” he says, “to exercise one’s self in composition; when we
have produced nothing, what we have learned remains dead. The
knowledge that we acquire ought to be like seed sown in the earth,
germinating and bearing fruit.”[112]
Reuchlin, one of Melancthon’s teachers, Reuchlin
recognized the best means of winning opponents advises
to the truth, and said: “The best way to convert teaching
Bible
the

the Israelites would be to establish two professors


of the Hebrew language in each university, who should teach the
theologians to read the Bible in Hebrew, and thus refute the Jewish
doctors.” The fact that such a position exposed Reuchlin to violent
opposition from the monks and papal teachers shows that he rightly
divined the remedy for papal oppression; and it is significant of an
approaching reformation when he thus recommends that the Bible
be placed in the universities for study by theologians.
There is a rift in the clouds, and ere long the sun will appear. But
“men loved darkness rather than light.” Why?
Erasmus, recognized by all as a reformer, did his Erasmus
work by the publication of the New Testament in
Greek. “The work was undertaken in the interests of a purer
Christianity.” “It is my desire,” he said, “to lead back that cold
dispute about words called theology to its real fountain. Would to
God that this work may bear as much fruit to Christianity as it has
cost me toil and application.” Here was a direct thrust at the study of
dialectics in the universities. The meaningless disputes which
constituted the course in theology was, by Erasmus, to be replaced
by the living word of God. The Reformation drew nearer, and the
papacy shuddered at the prospect. Gradually the Spirit was
returning, and this is seen more and more as we take up the life of
Luther. The highway had been cleared by such forerunners as have
already been mentioned.
“The fundamental principles of Protestantism are Protestantism
favorable to education,” says Painter.[113] “With the fosters
education
Scriptures and his conscience for guides, every man is elevated to
the freedom and dignity of ordering his own religious life. The
feeling of individual responsibility is awakened, and the spirit of
inquiry fostered. Intelligence becomes a necessity. The Bible must be
studied; teachers must be provided; schools must be established.
Protestantism becomes the mother of popular education.”
Again the same author says: “It [Christianity] does not withdraw
man from the ordinary callings and relations of life; it makes him a
steward of God in the world, and exalts his daily labors in the
household, in the schoolroom, in the workshop, on the farm, into a
divine service. The Protestant view restores nature, as a subject of
investigation, to its rights. The whole circle of knowledge—whatever
is elevating, whatever prepares for useful living—is held in honor.
Primary and secondary schools are encouraged; the best methods of
instruction, based upon a study of man’s nature and not upon the
interests of the church, are sought out. Protestantism is a friend of
universal learning.” One French scholar says: “The Reformation
contracted the obligation of placing everyone in a condition to save
himself by reading and studying the Bible. Instruction became then
the first of the duties of charity; and all who had charge of souls,
from the father of a family to the sovereign of the state, were called
upon ... to favor popular education.[114]”
It is no wonder, then, that much of Luther’s time Luther an
and ambition was spent in the cause of education. educator
“The necessities of the Reformation gave Luther,”
says Painter, “an intense interest in education. The schools of the
time, already inadequate in number and defective in method, were
crippled during the early stages of the Reformation by the excited
and unsettled condition of society. A new generation was growing up
without education. The establishment of schools became a
necessary measure for the success and permanence of the
Reformation. The appeal had been made to the Word of God, and it
was necessary to teach the masses to read it. Preachers and
teachers were needed for the promulgation and defense of the
gospel.... As early as 1524, Luther made an appeal of marvelous
energy to the authorities of the German cities for the establishment
of schools. If we consider its pioneer character, in connection with its
statement of principles and admirable recommendations, the
address must be regarded the most important educational treatise
ever written.”[115] God had trained him for his position.
Here are the words of the Reformer. Judge for Luther’s plea
yourselves if they should not voice the sentiment of for schools
every true Protestant to-day! “He wrote,” says
D’Aubigné, “to the councilors of all the cities of Germany, calling
upon them to found Christian schools.” “Dear sirs,” said Luther, “we
annually expend so much money on arquebuses, roads, and dikes,
why should we not spend a little to give one or two schoolmasters to
our poor children? God stands at the door and knocks; blessed are
we if we open to him! Now the Word of God abounds. O my dear
Germans, buy, buy, while the market is open before your houses.
The Word of God and His grace are like a shower that falls and
passes away. It was among the Jews; but it passed away, and now
they have it no longer. Paul carried it into Greece; but in that country
also it has passed away, and the Turk reigns there now. It came to
Rome and the Latin empire; but there also it has passed away, and
Rome now has the pope. O Germans, do not expect to have this
Word forever. The contempt that is shown to it will drive it away. For
this reason let him who desires to possess it lay hold of it and keep
it.
“Busy yourselves with the children; for many parents are like
ostriches, they are hardened toward their little ones, and, satisfied
with having laid the egg, they care nothing for it afterward.... The
true wealth of a city, its safety, and its strength, is to have many
learned, serious, worthy, well-educated citizens. And whom must we
blame, because there are so few at present, except your magistrates
who have allowed your youth to grow up like trees in a forest?”[116]
D’Aubigné says truly: “It was not the public worship alone that the
Reformation was ordained to change. The school was early placed
beside the church, and these two great institutions, so powerful to
regenerate the nations, were equally reanimated by it. It was by a
close alliance with learning that the Reformation entered into the
world; in the hour of its triumph it did not forget its ally.”[117] Luther
“felt that to strengthen the Reformation it was requisite to work on the
young, to improve the schools, and to propagate throughout
Christendom the knowledge necessary for a profound study of the
Holy Scriptures. This was one of the results.”[118]
Painter, describing the educational work of the Schools
great Reformer, says: “With Luther, education was strengthen the
not an end in itself, but a means to more effective church
service in church and state. If people or rulers neglect the education
of the young, they inflict an injury upon both the church and state;
they become enemies of God and man; they advance the cause of
Satan, and bring down upon themselves the curse of heaven. This is
the fundamental thought that underlies all Luther’s writings upon
education.”[119]
Luther expresses his views briefly in these Schools not
words: “The common man does think that he is appreciated
under obligation to God and the world to send his
son to school. Everyone thinks that he is free to bring up his son as
he pleases, no matter what becomes of God’s word and command.
Yea, even our rulers act as if they were exempt from the divine
command. No one thinks that God has earnestly willed and
commanded that children be brought up to his praise and work—a
thing that can not be done without schools. On the contrary, everyone
hastens with his children after worldly gain.” Luther’s words ringing
down the centuries must be echoed by all true Protestants to-day.
Where are the men with the courage of educational reformers?
“Luther did not concern himself about the Luther’s
education of the clergy only, it was his desire that educational
knowledge should not be confined to the church; plans
he proposed extending it to the laity, who hitherto had been
deprived of it.... He emancipated learning from the hands of the
priests, who had monopolized it, like those of Egypt in times of old,
and put it within the reach of all.”[120] Luther grasped with
wonderful clearness the real meaning of Christian education, and
there is scarcely a phase of it which he has left untouched.
“If we survey,” says Dittes, “the pedagogy of Luther’s
Luther in all its extent, and imagine it fully realized methods a
in practice, what a splendid picture the schools and model
education of the sixteenth century would present! We should have
courses of study, text-books, teachers, methods, principles, and
modes of discipline, schools and school regulations, that could serve
as models for our own age.”
The Reformer writes: “Where would preachers, Luther’s ideals
lawyers, and physicians come from if the liberal of teachers
arts were not taught? From this source must they
all come. This, I say, no one can ever sufficiently remunerate the
industrious and pious teacher that faithfully educates.... Yet people
shamefully despise this calling among us, as if it were nothing, and
at the same time they pretend to be Christians! If I were obliged to
leave off preaching and other duties, there is no office I would
rather have than that of school-teacher; for I know that this work is,
with preaching, the most useful, greatest, and best; and I do not
know which of the two is to be preferred. For it is difficult to make
old dogs docile, and old rogues pious, yet that is what the ministry
works at, and must work at in great part, in vain; but young trees,
although some may break, are more easily bent and trained.
Therefore, let it be one of the highest virtues on earth faithfully to
educate the children of others who neglect it themselves.”[121]
Germany was aroused. “In 1525 he was Germany
commissioned by the Duke of Mansfield to established
establish two schools in his native town, ... one for schools
the primary and the other for secondary instruction.” They were not
conducted after the manner of papal schools, differing only in the
fact that the teacher was a Protestant. “Both in the course of study
and in the methods of instruction these schools become models after
which many others were fashioned.... In a few years the Protestant
portion of Germany was supplied with schools. They were still
defective, ... but, at the same time, they were greatly superior to
any that had preceded them. Though no complete system of popular
instruction was established, the foundation for it was laid. To this
great result, Luther contributed more than any other man of his
time; and this fact makes him the leading educational reformer of
the sixteenth century.”[122]
The changes wrought by Luther were not mere No compromise
superficial, formal changes; but as the
Reformation, as a religious movement, struck a death-blow to the
papacy, viewed as an educational movement, it is found to have cut
directly across the established methods of popular education. It
meant a change in the courses, a different idea of graduation, a
change in text-books, in methods of teaching, methods of study, and
character of the teachers.
He was perhaps the first of the reformers to Value of nature
recognize the value of nature study. He once said: study
“We are at the dawn of a new era; for we are
beginning to recover the knowledge of the external world that we
have lost since the fall of Adam. Erasmus is indifferent to it; he does
not care to know how fruit is developed from the germ. But by the
grace of God, we already recognize in the most delicate flower the
wonders of divine goodness and the omnipotence of God. We see in
His creatures the power of His word. He commanded, and the thing
stood fast. See that force display itself in the stone of a peach. It is
very hard, and the germ that it incloses is very tender; but, when
the moment has come, the stone must open to let out the young
plant that God calls into life.”[123] It may at first seem strange that
the bold, brave man who aroused the world by his theses nailed to
the church door, should have a character to which the gentleness of
nature made such a strong appeal. But Luther was a true preacher
in that he was a teacher. What wonder that his work was enduring!
It stands close beside the life-work of his Master, Jesus,—the
Teacher sent of God.
Before carrying the work of Luther further, it is Melancthon,
necessary to introduce a new character, born, it Luther’s
would seem, at a moment when his special mental companion
education
in

qualities were most needed and fitted by heaven to


stand by Luther’s side as an aid and as a comfort in the mighty
storm through which he must pass. I refer to Melancthon; God
chose him as a teacher, and imparted to him, in a wonderful degree,
that gift of the Spirit. A few extracts from D’Aubigné will show clearly
how he was guided into the paths of the Reformation, there to
become one of the greatest workers for that cause.
He was born in 1497; hence, when Luther began his work in 1517,
Melancthon was a youth of twenty. “He was remarkable for the
excellence of his understanding, and his facility in learning and
explaining what he had learnt.” “Melancthon at twelve years of age
went to the University of Heidelberg, ... and took his bachelor’s
degree at fourteen.” “In 1512, Reuchlin [the reformer referred to on
a previous page] invited him to Tubingen.... The Holy Scriptures
especially engaged his attention.... Rejecting the empty systems of
the schoolmen, he adhered to the plain word of the gospel.”[124]
Erasmus wrote: “I entertain the most distinguished and splendid
expectations of Melancthon. God grant that this young man may
long survive us. He will entirely eclipse Erasmus.”
“In 1514 he was made doctor of philosophy, and Melancthon
then began to teach. He was seventeen years old. teaches
The grace and charm that he imparted to his
lessons formed the most striking contrast to the tasteless method
which the doctors, and above all, the monks, had pursued till then.”
Frederick applied to Erasmus and Reuchlin for an Melancthon
instructor for the University of Wittemberg. goes to
Melancthon was recommended. Reaching the Wittemberg
university, he did not make the most favorable impression on Luther
and other professors, “when they saw his youth, his shyness, and
diffident manners.” After his opening address, however, Luther and
others became his ardent admirers. Luther wrote: “I ask for no other
Greek master. But I fear that his delicate frame will be unable to
support our mode of living, and that we shall be unable to keep him
long on account of the smallness of his salary.”
The spirit of Christianity and of Christian education had drawn two
souls together, and the success of the work from this time on
depended largely upon this union. Says D’Aubigné: “Melancthon was
able to respond to Luther’s affection. He soon found in him a
kindness of disposition, a strength of mind, a courage, a discretion,
that he had never found till then in any man.... We can not too much
admire the goodness and wisdom of God in bringing together two
men so different, and yet so necessary to one another. Luther
possessed warmth, vigor, and strength; Melancthon clearness,
discretion, and mildness. Luther gave energy to Melancthon;
Melancthon moderated Luther. They were like substances in a state
of positive and negative electricity, which mutually act upon each
other. If Luther had been without Melancthon, perhaps the torrent
would have overflowed its banks; Melancthon, when Luther was
taken from him by death, hesitated, and gave way, even where he
should not have yielded.”
Should you question why I thus dwell upon the life and character
of Melancthon, I reply, Because from this union of two souls flowed
the great educational reform of the sixteenth century. The two did
what neither could have done alone; and the study of their lives
alone reveals the secret of success in Christian education to-day.
It was a notable day to Wittemberg when Melancthon
Melancthon arrived. “The barrenness that revolutionizes
scholasticism had cast over education was at an Wittemberg
end. A new manner of teaching and of studying began with Melancthon.
‘Thanks to him,’ says an illustrious German historian, ‘Wittemberg
became the school of the nation.’”
“The zeal of the teachers [Luther and Papal education
Melancthon] was soon communicated to the dropped
disciples. It was decided to reform the method of
instruction. With the electors’ consent, certain courses that possessed
merely scholastic importance were suppressed; and at the same time the
study of the classics received a fresh impulse. [Remember, however,
that this study of the classics was the Greek and Hebrew Scriptures.]
The school at Wittemberg was transformed, and the contrast with other
universities became daily more striking.”
[125]

The results of these changes were no less Result of


marvelous than the changes themselves. The changes
author last quoted says: Wittemberg “flourished
daily more and more, and was eclipsing all the other schools. A
crowd of students flocked thither from all parts of Germany to hear
this extraordinary man, whose teaching appeared to open a new era
in religion and learning. These youths, who came from every
province, halted as soon as they discovered the steeples of
Wittemberg in the distance; they raised their hands to heaven, and
praised God for having caused the light of truth to shine forth from
this city, as from Zion in times of old, and whence it spread even to
the most distant countries. A life and activity, till then unknown,
animated the university.”
Such a school did not call together a class of students careless in
habit and listless in study; for the fare, as before noted, was meager,
and there was no great outward display. Those who attended came
seeking for truth; and as their souls were filled with spiritual meat,
they returned to their homes, “even to the most distant countries,”
to spread the truths of Christian education. Luther himself wrote:
“Our students here are as busy as ants.” Two thousand students
from all parts of Europe thronged the lecture room of Melancthon.
The life and work of those two animating spirits Melancthon’s
at Wittemberg can not be measured by any earthly view of
standard. Melancthon said: “I apply myself solely education
to one thing, the defense of letters. By our example we must excite
youth to the admiration of learning, and induce them to love it for its
own sake, and not for the advantage that they may derive from it.
The destruction of learning brings with it the ruin of everything that
is good,—religion, morals, and all things human and divine. The
better a man is, the greater his ardor in the preservation of learning;
for he knows that, of all plagues, ignorance is the most pernicious.”
“To neglect the young in our schools is just like taking the spring out
of the year. They, indeed, take away the spring from the year who
permit the schools to decline, because religion can not be maintained
without them.”

Luther had stated that a reform in methods and Melancthon


courses was necessary. Melancthon had assisted in prepared text-
that work. He did still more. Breaking away as they books
did from the educational system of the universities of the world, and
basing instruction upon the Word of God, it became necessary to
have new text-books. Melancthon applied himself with great
diligence to this duty. He was an arduous student, often arising at
three in the morning, and many of his works were written between
that hour and the dawn. Besides his Greek and Latin grammars he is
the author of works on logic, rhetoric, physics, and ethics. “These
works, written in a clear and scientific form, soon became popular,
and some of them held their place in the schools for more than a
hundred years.”
The Study of Theology had been degraded into the pursuit of subtle
arguments and idle controversies. Melancthon wrote a work on
dogmatic theology, publishing it in 1521. Of this work, Luther wrote:
“Whoever wishes to become a theologian now enjoys great
advantages; for, first of all, he has the Bible, which is so clear that
he can read it without difficulty. Then let him read in addition the
Loci Communes of Melancthon.... If he has these two things, he is a
theologian from whom neither the devil nor heretics shall be able to
take away anything.”
Melancthon’s life was not devoted alone to the Preparatory
education of such students as could attend schools
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like