Jones & Bartlett Learning 5 Wall Street Burlington, MA 01803 978-443-5000 info@jblearning.com www.jblearning.com
Jones & Bartlett Learning books and products are available through most bookstores and online booksellers. To contact Jones & Bartlett Learning directly, call 800-832-0034, fax 978-443-8000, or visit our website, www.jblearning.com.
Substantial discounts on bulk quantities of Jones & Bartlett Learning publications are available to corporations, professional associations, and other qualified organizations. For details and specific discount information, contact the special sales department at Jones & Bartlett Learning via the above contact information or send an email to specialsales@jblearning.com.
All rights reserved. No part of the material protected by this copyright may be reproduced or utilized in any form, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written permission from the copyright owner.
The content, statements, views, and opinions herein are the sole expression of the respective authors and not that of Jones & Bartlett Learning, LLC. Reference herein to any specific commercial product, process, or service by trade name, trademark, manufacturer, or otherwise does not constitute or imply its endorsement or recommendation by Jones & Bartlett Learning, LLC and such reference shall not be used for advertising or product endorsement purposes. All trademarks displayed are the trademarks of the parties noted herein. Object-Oriented Data Structures Using Java, Fourth Edition is an independent publication and has not been authorized, sponsored, or otherwise approved by the owners of the trademarks or service marks referenced in this product.
09820-4
Production Credits
VP, Executive Publisher: David D. Cella
Acquisitions Editor: Laura Pagluica
Editorial Assistant: Taylor Ferracane
Director of Vendor Management: Amy Rose
Marketing Manager: Amy Langlais
VP, Manufacturing and Inventory Control: Therese Connell Composition and Project Management: S4Carlisle Publishing Services
Library of Congress Cataloging-in-Publication Data
Classification: LCC QA76.64 .D35 2017 | DDC 005.13/3--dc23 LC record available at https://lccn.loc.gov/2016025145
6048
To Alfred G. Dale
ND
To Kathy, Tom, and Julie, thanks for the love and support
DJ
To Lisa, Charlie, and Abby, thank you . . .
CW
Preface
Welcome to the fourth edition of Object-Oriented Data Structures Using Java™. This book presents the algorithmic, programming, and structuring techniques of a traditional data structures course in an object-oriented context. You’ll find the familiar topics of linked lists, recursion, stacks, queues, collections, indexed lists, trees, maps, priority queues, graphs, sorting, searching, and complexity analysis, all covered from an object-oriented point of view using Java. We stress software engineering principles throughout, including modularization, information hiding, data abstraction, stepwise refinement, the use of visual aids, the analysis of algorithms, and software verification methods.
To the Student
You know that an algorithm is a sequence of unambiguous instructions for solving a problem. You can take a problem of moderate complexity, design a small set of classes/objects that work together to solve the problem, code the method algorithms needed to make the objects work, and demonstrate the correctness of your solution.
Algorithms describe actions. These actions manipulate data. For most interesting problems that are solved using computers, the structure of the data is just as important as the structure of the algorithms used to manipulate the data. Using this text you will discover that the way you structure data affects how efficiently you can use the data; you will see how the nature of the problem you are attempting to solve dictates your structuring decisions; and you will learn about the data structures that computer scientists have developed over the years to help solve problems.
Object-Oriented Programming with Java
Our primary goal is to present both the traditional and modern data structure topics with an emphasis on problem solving and software design. Using the Java programming language as a vehicle for problem solutions, however, presents an opportunity for students to expand their
familiarity with a modern programming language and the object-oriented paradigm. As our data structure coverage unfolds, we introduce and use the appropriate Java constructs that support our primary goal. Starting early and continuing throughout the text, we introduce and expand on the use of many Java features such as classes, objects, generics, polymorphism, packages, interfaces, library classes, inheritance, exceptions, and threads. We also use Universal Modeling Language (UML) class diagrams throughout to help model and visualize our objects, classes, interfaces, applications, and their interrelationships.
Features
Data Abstraction In this text we view our data structures from three different perspectives: their specification, their application, and their implementation. The specification describes the logical or abstract level—what the logical relationships among the data elements are and what operations can be performed on the structure. The application level, sometimes called the client level, is concerned with how the data structure is used to solve a problem—why the operations do what they do. The implementation level involves the coding details—how the structures and operations are implemented. In other words we treat our data structures as abstract data types (ADTs).
Efficiency Analysis In Chapter 1 we introduce order of growth efficiency analysis using a unique approach involving the interaction of two students playing a game. Time and space analysis is consistently applied throughout the text, allowing us to compare and contrast data structure implementations and the applications that use them.
Recursion Treatment Recursion is introduced early (Chapter 3) and used throughout the remainder of the text. We present a design and analysis approach to recursion based on answering three simple questions. Answering the questions, which are based on formal inductive reasoning, leads the programmer to a solid recursive design and program.
Interesting Applications Eight primary data structures (stacks, queues, collections, indexed lists, trees, maps, priority queues, and graphs) are treated in separate chapters that include their definition, several implementations, and one or more interesting applications based on their use. Applications involve, for example, balanced expressions, postfix expressions, image generation (new!), fractals (new!), queue simulation, card decks and games (new!), text analysis (new!), tree and graph traversals, and big integers.
Robust Exercises We average more than 40 exercises per chapter. The exercises are organized by chapter sections to make them easier for you to manage. They vary in level of difficulty, including short and long programming problems (marked with “programming-required” icons—one icon to indicate short exercises and two icons for projects), the analysis of algorithms, and problems to test students’ understanding of abstract concepts. In this edition we have streamlined the previous exercises, allowing us to add even more options for you to choose from. In particular we have added several larger programming exercises to many of the chapters.
Input/Output Options It is difficult to know what background the students using a data structures text will have in Java I/O. To allow all the students using our text to concentrate on the
primary topic of data structures, we use the simplest I/O approach we can, namely a command line interface. However, to support those teachers and students who prefer to work with graphical user interfaces (GUIs), we provide GUIs for many of our applications. Our modular approach to program design supports this approach—our applications separate the user interface code, problem solution code, and ADT implementation code into separate classes.
Concurrency Coverage We are pleased to be one of the only data structures texts to address the topics of concurrency and synchronization, which are growing in importance as computer systems move to using more cores and threads to obtain additional performance with each new generation. We introduce this topic in Section 4.9, “Concurrency, Interference, and Synchronization,” where we start with the basics of Java threads, continue through examples of thread interference and synchronization, and culminate in a discussion of efficiency concerns.
New to the Fourth Edition
This edition represents a major revision of the text’s material, although the philosophy and style that our loyal adopters have grown to appreciate remain unchanged. We removed material we felt was redundant or of lesser/outdated importance to the core topic of data structures, added new key material, and reworked much of the material that we kept. Although the length of the textbook was reduced by about 10%, the coverage of data structures has been expanded. We believe this new edition is a great improvement over previous editions and hope you do, too. Major changes include:
• Simplified Architecture: We continue to use the Java interface construct to define the abstract view of our ADTs, but we have reduced the number of levels of inheritance, simplifying the architecture and making it easier to understand and use.
• New Chapters: Chapter 5, “The Collection ADT,” and Chapter 8, “The Map ADT,” are brand new. The Collection ADT material introduces the idea of a data structure as a repository and concentrates on storage and retrieval of data based on key attributes. The Map ADT has become increasingly important with the rise in popularity of scripting languages with built-in associative arrays.
• New Section: Section 1.6, “Comparing Algorithms: Order of Growth Analysis,” was completely rewritten and features an introduction to efficiency analysis driven by a game played between two students, plus analysis of sequential search, binary search, and sequential sort algorithms.
• New Sections: In response to reader’s suggestions, Chapter 3, “Recursion,” features two new sections: Section 3.3, “Recursive Processing of Arrays,” is devoted to recursive processing of arrays and Section 3.4, “Recursive Processing of Linked Lists,” is devoted to recursive processing of linked lists. These new sections provide practical examples of the use of recursion, before the reader moves on to the less practical but nevertheless popular Towers of Hanoi example covered in Section 3.5, “Towers.”
• New Section: Fractals! A fun section related to recursively generating fractal-based images now wraps up the examples of Chapter 3, “Recursion.”
• New Sections: We added “Variations” sections to the Stack, Queue, Collection, List, Tree, and Map chapters. In the primary exposition of each of these ADTs we record design decisions and specify the operations to be supported by the ADT. We also develop or at least discuss various implementation approaches, in most cases highlighting one array-based approach and one reference/linked-list-based approach. The “Variations” section discusses alternate approaches to defining/implementing the ADT and in most cases reviews the ADT counterparts available in the standard Java Library. Some of these sections also introduce related ADTs, for example, in the “Variations” section of the Collection chapter we define and discuss both the Set and Bag ADTs.
• Glossary: The text’s glossary has always been available online. With this edition we make it available as Appendix E. Throughout the text we highlight important terms that might be unfamiliar to the student in green, the first time they are featured, to indicate that their definition can be found in the glossary.
Prerequisite Assumptions
In this book, we assume that readers are familiar with the following Java constructs:
• Built-in simple data types and the array type
• Control structures while, do, for, if, and switch
• Creating and instantiating objects
• Basic user-defined classes:
■ variables and methods
■ constructors, method parameters, and the return statement
■ visibility modifiers
• Commonly used Java Library Classes: Integer, Math, Random, Scanner, String, and System
Chapter Content
Chapter 1 is all about Getting Organized. An overview of object orientation stresses mechanisms for organizing objects and classes. The Java exception handling mechanisms, used to organize response to unusual situations, are introduced. Data structures are previewed and the two fundamental language constructs that are used to implement those structures, the array and the reference (link/pointer), are discussed. The chapter concludes with a look at efficiency analysis—how we evaluate and compare algorithms.
Chapter 2 presents The Stack ADT. The concept of abstract data type (ADT) is introduced. The stack is viewed from three different levels: the abstract, application, and implementation levels. The Java interface mechanism is used to support this three-tiered view. We also investigate using generics to support generally usable ADTs. The Stack ADT is implemented using both arrays and references. To support the reference-based approach we introduce the linked list structure. Sample applications include determining if a set of grouping symbols is well formed and the evaluation of postfix expressions.
Chapter 3 discusses Recursion, showing how recursion can be used to solve programming problems. A simple three-question technique is introduced for verifying the correctness of recursive methods. Sample applications include array processing, linked list processing, the classic Towers of Hanoi, and fractal generation. A detailed discussion of how recursion works shows how recursion can be replaced with iteration and stacks.
Chapter 4 presents The Queue ADT. It is also first considered from its abstract perspective, followed by a formal specification, and then implemented using both array-based and referencebased approaches. Example applications include an interactive test driver, a palindrome checker, and simulating a system of real-world queues. Finally, we look at Java’s concurrency and synchronization mechanisms, explaining issues of interference and efficiency.
Chapter 5 defines The Collection ADT. A fundamental ADT, the Collection, supports storing information and then retrieving it later based on its content. Approaches for comparing objects for equality and order are reviewed. Collection implementations using an array, a sorted array, and a linked list are developed. A text processing application permits comparison of the implementation approaches for efficiency. The “Variations” section introduces two more well-known ADTs: the Bag and the Set.
Chapter 6 follows up with a more specific Collection ADT, The List ADT. In fact, the follow ing two chapters also develop Collection ADTs. Iteration is introduced here and the use of anonymous inner classes to provide iterators is presented. As with the Collection ADT we develop array, sorted array, and linked-list–based implementations. The “Variations” section includes an example of how to “implement” a linked list within an array. Applications include a card deck model plus some card games, and a Big Integer class. This latter application demonstrates how we sometimes design specialized ADTs for specific problems.
Chapter 7 develops The Binary Search Tree ADT. It requires most of the chapter just to design and create our reference-based implementation of this relatively complex structure. The chapter also discusses trees in general (including breadth-first and depth-first searching) and the problem of balancing a binary search tree. A wide variety of special-purpose and self-balancing trees are introduced in the “Variations” section.
Chapter 8 presents The Map ADT, also known as a symbol table, dictionary, or associative array. Two implementations are developed, one that uses an ArrayList and the other that uses a hash table. A large part of the chapter is devoted to this latter implementation and the important concept of hashing, which provides a very efficient implementation of a Map. The “Variations” section discusses a map-based hybrid data structure plus Java’s support for hashing.
Chapter 9 introduces The Priority Queue ADT, which is closely related to the Queue but with a different accessing protocol. This short chapter does present a sorted array-based implementation, but most of the chapter focuses on a clever, interesting, and very efficient implementation called a Heap.
Chapter 10 covers The Graph ADT, including implementation approaches and several important graph-related algorithms (depth-first search, breadth-first search, path existence, shortest paths, and connected components). The graph algorithms make use of stacks, queues, and priority queues, thus both reinforcing earlier material and demonstrating the general usability of these structures.
Chapter 11 presents/reviews a number of Sorting and Searching Algorithms. The sorting algorithms that are illustrated, implemented, and compared include straight selection sort, two versions of bubble sort, insertion sort, quick sort, heap sort, and merge sort. The sorting algorithms are compared using efficiency analysis. The discussion of algorithm analysis continues in the context of searching. Previously presented searching algorithms are reviewed and new ones are described.
Organization
Chapter Goals Sets of knowledge and skill goals are presented at the beginning of each chapter to help the students assess what they have learned.
Sample Programs Numerous sample programs and program segments illustrate the abstract concepts throughout the text.
Feature Sections Throughout the text these short sections highlight topics that are not directly part of the flow of material but nevertheless are related and important.
Boxed Notes These small boxes of information scattered throughout the text highlight, supplement, and reinforce the text material, perhaps from a slightly different point of view.
Chapter Summaries Each chapter concludes with a summary section that reviews the most important topics of the chapter and ties together related topics. Some chapter summaries include a UML diagram of the major interfaces and classes developed within the chapter.
Appendices The appendices summarize the Java reserved word set, operator precedence, primitive data types, the ASCII subset of Unicode, and provide a glossary of important terms used in the text.
Website http://go.jblearning.com/oods4e
This website provides access to the text’s source code files for each chapter. Additionally, registered instructors are able to access selected answers to the text’s exercises, a test item file, and presentation slides. Please contact the authors if you have material related to the text that you would like to share with others.
Acknowledgments
We would like to thank the following people who took the time to review this text: Mark Llewellyn at the University of Central Florida, Chenglie Hu at Carroll College, Val Tannen at the University of Pennsylvania, Chris Dovolis at the University of Minnesota, Mike Coe at Plano Senior High School, Mikel Petty at University of Alabama in Huntsville, Gene Sheppard at Georgia Perimeter College, Noni Bohonak at the University of South Carolina–Lancaster, Jose Cordova at the University of Louisiana–Monroe, Judy Gurka at the Metropolitan State College of Denver, Mikhail Brikman at Salem State University, Amitava Karmaker at University of Wisconsin–Stout, Guifeng Shao at Tennessee State University, Urska Cvek at Louisiana State University at Shreveport, Philip C. Doughty Jr. at Northern Virginia Community College, Jeff Kimball at Southwest Baptist University, Jeremy T. Lanman at Nova Southeastern University, Rao Li at University of South Carolina Aiken, Larry Thomas at University of Toledo, and Karen Works at Westfield State University. A special thanks to Christine Shannon at Centre College, to Phil LaMastra at Fairfield University, to Allan Gottlieb of New York University, and to J. William Cupp at Indiana Wesleyan University for specific comments leading to improvements in the text. A personal thanks to Kristen Obermyer, Tara Srihara, Sean Wilson, Christopher Lezny, and Naga Lakshmi, all of Villanova University, plus Kathy, Tom, and Julie Joyce for all of their help, support, and proofreading expertise.
A virtual bouquet of roses to the editorial and production teams who contributed so much, especially Laura Pagluica, Taylor Ferracane, Amy Rose, and Palaniappan Meyyappan.
Contents
1 Getting Organized 1
1.1 Classes, Objects, and Applications 2 Classes 2
The Unified Method 7 Objects 8 Applications 10
1.2 Organizing Classes 12
Inheritance 12
Packages 19
1.3 Exceptional Situations 22
Handling Exceptional Situations 22
Exceptions and Classes: An Example 23
1.4 Data Structures 27
Implementation-Dependent Structures 28
Implementation-Independent Structures 29
What Is a Data Structure? 31
1.5 Basic Structuring Mechanisms 32 Memory 32
References 34
Arrays 38
1.6 Comparing Algorithms: Order of Growth Analysis 43
Measuring an Algorithm’s Time Efficiency 44
Complexity Cases 45
Size of Input 46
Comparing Algorithms 47
Order of Growth 49
Selection Sort 50
Common Orders of Growth 53
Summary 54
Exercises 55
2 The Stack ADT 67
2.1
Abstraction 68
Information Hiding 68
Data Abstraction 69
Data Levels 70
Preconditions and Postconditions 71
Java Interfaces 72
Interface-Based Polymorphism 76
2.2 The Stack 78
Operations on Stacks 79
Using Stacks 79
2.3 Collection Elements 81
Generally Usable Collections 81
2.4 The Stack Interface 84
Exceptional Situations 85
The Interface 88
Example Use 89
2.5 Array-Based Stack Implementations 90
The ArrayBoundedStack Class 91
Definitions of Stack Operations 93
The ArrayListStack Class 99
2.6 Application: Balanced Expressions 101
The Balanced Class 102
The Application 107
The Software Architecture 111
2.7 Introduction to Linked Lists 111
Arrays Versus Linked Lists 111
The LLNode Class 113
Operations on Linked Lists 115
2.8 A Link-Based Stack 121
The LinkedStack Class 122
The push Operation 124
The pop Operation 127
The Other Stack Operations 129
Comparing Stack Implementations 131
2.9 Application: Postfix Expression Evaluator 132
Discussion 132
Evaluating Postfix Expressions 133
Postfix Expression Evaluation Algorithm 134
Error Processing 136
The PostFixEvaluator Class 137
The PFixCLI Class 139
2.10 Stack Variations 142
Revisiting Our Stack ADT 142
The Java Stack Class and the Collections Framework 143
Summary 145 Exercises 147
3 Recursion 161
3.1 Recursive Definitions, Algorithms, and Programs 162
Recursive Definitions 162
Recursive Algorithms 163
Recursive Programs 166
Iterative Solution for Factorial 167
3.2 The Three Questions 167
Verifying Recursive Algorithms 168
Determining Input Constraints 169
Writing Recursive Methods 169
Debugging Recursive Methods 170
3.3 Recursive Processing of Arrays 170
Binary Search 170
3.4 Recursive Processing of Linked Lists 174
Recursive Nature of Linked Lists 175
Traversing a Linked List 175
Transforming a Linked List 178
3.5 Towers 182
The Algorithm 182
The Method 184
The Program 186
3.6 Fractals 186
A T-Square Fractal 187
Variations 190
3.7 Removing Recursion 191
How Recursion Works 191
Tail Call Elimination 195
Direct Use of a Stack 196
3.8 When to Use a Recursive Solution 197
Recursion Overhead 198
Inefficient Algorithms 198
Clarity 200
Summary 202
Exercises 202
4 The Queue ADT 217
4.1 The Queue 218
Operations on Queues 219
Using Queues 219
4.2 The Queue Interface 220
Example Use 222
4.3 Array-Based Queue Implementations 223
The ArrayBoundedQueue Class 223
The ArrayUnboundedQueue Class 230
4.4 An Interactive Test Driver 234
The General Approach 234
A Test Driver for the ArrayBoundedQueue Class 235 Using the Test Driver 235
4.5 Link-Based Queue Implementations 237
The Enqueue Operation 238
The Dequeue Operation 239
A Circular Linked Queue Design 241
Comparing Queue Implementations 242
4.6 Application: Palindromes 244
The Palindrome Class 244
The Applications 246
4.7 Queue Variations 248
Exceptional Situations 248
The GlassQueue 248
The Double-Ended Queue 251
Doubly Linked Lists 252
The Java Library Collection Framework Queue/Deque 255
4.8 Application: Average Waiting Time 257
Problem Discussion and Example 258
The Customer Class 259
The Simulation 262
Testing Considerations 268
4.9 Concurrency, Interference, and Synchronization 268
The Counter Class 270
Java Threads 271
Interference 274
Synchronization 275
A Synchronized Queue 277
Concurrency and the Java Library Collection Classes 282
7.5 Iterative Versus Recursive Method Implementations 443
Recursive Approach to the size Method 444
Iterative Approach to the size Method 446
Recursion or Iteration? 448
7.6 The Implementation Level: Remaining Observers 448
The contains and get Operations 449
The Traversals 452
7.7 The Implementation Level: Transformers 455
The add Operation 455
The remove Operation 460
7.8 Binary Search Tree Performance 466
Text Analysis Experiment Revisited 466
Insertion Order and Tree Shape 468
Balancing a Binary Search Tree 469
7.9 Application: Word Frequency Counter 471
The WordFreq Class 472
The Application 473
7.10 Tree Variations 479
Application-Specific Variations 479
Balanced Search Trees 482
Summary 485
Exercises 487
8 The Map ADT 499
8.1 The Map Interface 501
8.2 Map Implementations 506
Unsorted Array 506
Sorted Array 507
Unsorted Linked List 507
Sorted Linked List 508
Binary Search Tree 508
An ArrayList-Based Implementation 508
8.3 Application: String-to-String Map 512
8.4 Hashing 516
Collisions 518
8.5 Hash Functions 524
Array Size 524
The Hash Function 525
Java’s Support for Hashing 529
Complexity 530
8.6 A Hash-Based Map 530
The Implementation 531
Using the HMap class 538
8.7 Map Variations 539
A Hybrid Structure 540
Java Support for Maps 542
Summary 542 Exercises 543
9 The Priority Queue ADT 551
9.1 The Priority Queue Interface 552
Using Priority Queues 552
The Interface 553
9.2 Priority Queue Implementations 554
Unsorted Array 554
Sorted Array 554
Sorted Linked List 556
Binary Search Tree 556
9.3 The Heap 556
9.4 The Heap Implementation 562
A Nonlinked Representation of Binary Trees 562
Implementing a Heap 564
The enqueue Method 567
The dequeue Method 569
A Sample Use 574
Heaps Versus Other Representations of Priority Queues 575
Summary 576
Exercises 576
10 The Graph ADT 583
10.1 Introduction to Graphs 584
10.2 The Graph Interface 588
10.3 Implementations of Graphs 591
Array-Based Implementation 591
Linked Implementation 596
10.4 Application: Graph Traversals 597
Depth-First Searching 598
Breadth-First Searching 602
10.5 Application: The Single-Source Shortest-Paths Problem 605
Summary 611
Exercises 612
11 Sorting and Searching Algorithms 621
11.1 Sorting 622
A Test Harness 623
11.2 Simple Sorts 625
Selection Sort 625
Bubble Sort 631
Insertion Sort 635
11.3 O(N log2N) Sorts 638
Merge Sort 639
Quick Sort 646
Heap Sort 652
11.4 More Sorting Considerations 658
Testing 658
Efficiency 658
Objects and References 660
Comparing Objects 661
Stability 661
11.5 Searching 662
Sequential Searching 663
High-Probability Ordering 663
Sorted Collections 664
Hashing 665
Summary 666 Exercises 667
Appendix A: Java Reserved Words 673
Appendix B: Operator Precedence 674
Appendix C: Primitive Data Types 675
Appendix D: ASCII Subset of Unicode 676
Glossary 677
Index 683
CHAPTER
Getting Organized
Knowledge Goals
You should be able to describe some benefits of object-oriented programming describe the genesis of the Unified Method explain the relationships among classes, objects, and applications explain how method calls are bound to method implementations with respect to inheritance describe, at an abstract level, the following structures: array, linked list, stack, queue, list, tree, map, and graph identify which structures are implementation dependent and which are implementation independent describe the difference between direct addressing and indirect addressing explain the subtle ramifications of using references/pointers explain the use of O notation to describe the amount of work done by an algorithm describe the sequential search, binary search, and selection sort algorithms
Skill Goals
You should be able to interpret a basic UML class diagram design and implement a Java class create a Java application that uses the Java class use packages to organize Java compilation units create a Java exception class throw Java exceptions from within a class and catch them within an application that uses the class predict the output of short segments of Java code that exhibit aliasing declare, initialize, and use one- and two-dimensional arrays in Java, including both arrays of a primitive type and arrays of objects given an algorithm, identify an appropriate size representation and determine its order of growth given a section of code determine its order of growth
Before embarking on any new project, it is a good idea to prepare carefully—to “get organized.” In this irst chapter that is exactly what we do. A careful study of the topics of this chapter will prepare us for the material on data structures and algorithms, using the object-oriented approach, covered in the remainder of the book.
1.1 Classes, Objects, and Applications
Software design is an interesting, challenging, and rewarding task. As a beginning student of computer science, you wrote programs that solved relatively simple problems. Much of your effort went into learning the syntax of a programming language such as Java: the language’s reserved words, its data types, its constructs for selection and looping, and its input/output mechanisms.
As your programs and the problems they solve become more complex it is important to follow a software design approach that modularizes your solutions—breaks them into coherent manageable subunits. Software design was originally driven by an emphasis on actions. Programs were modularized by breaking them into subprograms or procedures/ functions. A subprogram performs some calculations and returns information to the calling program, but it does not “remember” anything. In the late 1960s, researchers argued that this approach was too limiting and did not allow us to successfully represent the constructs needed to build complex systems.
Two Norwegians, Kristen Nygaard and Ole-Johan Dahl, created Simula 67 in 1967. It was the irst language to support object-oriented programming. Object-oriented languages promote the object as the prime modularization mechanism. Objects represent both information and behavior and can “remember” internal information from one use to the next. This crucial difference allows them to be used in many versatile ways. In 2001, Nygaard and Dahl received the Turing Award, sometimes referred to as the “Nobel Prize of Computing,” for their work.
The capability of objects to represent both information (the objects have attributes) and behavior (the objects have responsibilities) allows them to be used to represent “realworld” entities as varied as bank accounts, genomes, and hobbits. The self-contained nature of objects makes them easy to implement, modify, and test for correctness.
Object orientation is centered on classes and objects. Objects are the basic run-time entities used by applications. An object is an instantiation of a class; alternatively, a class de ines the structure of its objects. In this section we review these object-oriented programming constructs that we use to organize our programs.
Classes
A class de ines the structure of an object or a set of objects. A class de inition includes variables (data) and methods (actions) that determine the behavior of an object. The following Java code de ines a Date class that can be used to create and manipulate Date objects—for example, within a school course-scheduling application. The Date class can be used to create Date objects and to learn about the year, month, or day of any particular
Date object.1 The class also provides methods that return the Lilian Day Number of the date (the code details have been omitted—see the feature section on Lilian Day Numbers for more information) and return a string representation of the date.
Authors’ Convention
Java-reserved words (when used as such), user-defined identifiers, class and file names, and so on, appear in this font throughout the entire text.
// Date.java by Dale/Joyce/Weems
//
// Defines date objects with year, month, and day attributes.
{ protected int year, month, day; public static final int MINYEAR = 1583;
// Constructor
public Date(int newMonth, int newDay, int newYear)
{ month = newMonth; day = newDay; year = newYear; }
// Observers
public int getYear() { return year; } public int getMonth() { return month; } public int getDay(){ return day; }
public int lilian()
{ // Returns the Lilian Day Number of this date.
// Algorithm goes here. Code is included with the program files.
// See Lilian Day Numbers feature section for details. }
@Override2 public String toString()
1 The Java library includes a Date class, java.util.Date. However, the familiar properties of dates make them a natural example to use in explaining object-oriented concepts. Here we ignore the existence of the library class, as if we must design our own Date class.
2 The purpose of @Override is discussed in Section 1.2 “Organizing Classes.”
// Returns this date as a String. { return(month + "/" + day + "/" + year); } }
The Date class demonstrates two kinds of variables: instance variables and class variables. The instance variables of this class are year, month, and day declared as
protected int year, month, day; Their values vary for each “instance” of an object of the class. Instance variables provide the internal representation of an object’s attributes.
The variable MINYEAR is declared as
public static final int MINYEAR = 1583; MINYEAR is de ined as being static, and thus it is a class variable. It is associated directly with the Date class, instead of with objects of the class. A single copy of a class variable is maintained for all objects of the class.
Remember that the final modi ier states that a variable is in its inal form and cannot be modi ied; thus MINYEAR is a constant. By convention, we use only capital letters when naming constants. It is standard procedure to declare constants as class variables. Because the value of the variable cannot change, there is no need to force every object of a class to carry around its own version of the value. In addition to holding shared constants, class variables can be used to maintain information that is common to an entire class. For example, a BankAccount class may have a class variable that holds the number of current accounts.
Authors’ Convention
We highlight important terms that might be unfamiliar to the student in green, the first time they are featured, to indicate that their definition can be found in the glossary in Appendix E.
In the Date class example, the MINYEAR constant represents the irst full year that the widely used Gregorian calendar was in effect. The idea here is that programmers should not use the class to represent dates that predate that year. We look at ways to enforce this rule in Section 1.3 “Exceptional Situations,” where we discuss handling exceptional situations.
The methods of the class are Date, getYear, getMonth, getDay, lilian, and toString. Note that the Date method has the same name as the class. Recall that this means it is a special type of method, called a class constructor. Constructors are used to create new instances of a class—that is, to instantiate objects of a class. The other methods are classi ied as observer methods, because they “observe” and return information based on the instance variable values. Other names for observer methods are “accessor” methods and “getters,” as in accessing or getting information. Methods that simply return the value of an instance variable, such as getYear() in our Date class, are very common and always follow the same code pattern consisting of a single return statement. For this reason we will format such methods as a single line of code. In addition to constructors
Table 1.1 Java Access Control Modifiers
Access Is Allowed
Within the Class Within the Package Within Subclasses Everywhere public XXXX protected XXX package XX private X
and observers, there is another general category of method, called a transformer. As you probably recall, transformers change the object in some way; for example, a method that changes the year of a Date object would be classi ied as a transformer.
You have undoubtedly noticed the use of the access modi iers protected and public within the Date class. Let us review the purpose and use of access modi iers. This discussion assumes you recall the basic ideas behind inheritance and packages. Inheritance supports the extension of one class, called the superclass, by another class, called the subclass. The subclass “inherits” properties (data and actions) from the superclass. We say that the subclass is derived from the superclass. Packages let us group related classes together into a single unit. Inheritance and packages are both discussed more extensively in the next section.
Java allows a wide spectrum of access control, as summarized in Table 1.1. The public access modi ier used with the methods of Date makes them “publicly” available; any code that can “see” an object of the class can use its public methods. We say that these methods are “exported” from the class. Additionally, any class that is derived from the Date class using inheritance inherits its public methods and variables.
Public access sits at one end of the access spectrum, allowing open access. At the other end of the spectrum is private access. When you declare a class’s variables and methods as private, they can be used only inside the class itself and are not inherited by subclasses. You should routinely use private (or protected) access within your classes to hide their data. You do not want the data values to be changed by code that is outside the class. For example, if the month instance variable in our Date class was declared to be public, then the application code could directly set the value of a Date object’s month to strange numbers such as 12 or 27.
An exception to this guideline of hiding data within a class is shown in the Date example. Notice that the MINYEAR constant is publicly accessible. It can be accessed directly by the application code. For example, an application could include the statement if (myYear < Date.MINYEAR) ...
Because MINYEAR is a inal constant, its value cannot be changed by the application. Thus, even though it is publicly accessible, no other code can change its value. It is not necessary
to hide it. The application code above also shows how to access a public class variable from outside the class. Because MINYEAR is a class variable, it is accessed through the class name, Date, rather than through an object of the class.
Private access affords the strongest protection. Access is allowed only within the class. However, if you plan to extend your classes using inheritance, you may want to use protected access instead.
Coding Convention
We use protected access extensively for instance variables within our classes in this text.
The protected access modi ier used in Date provides visibility similar to private access, only slightly less rigid. It “protects” its data from outside access, but allows the data to be accessed from within its own package or from any class derived from its class. Therefore, the methods within the Date class can access year, month, and day, and if, as we will show in Section 1.2 “Organizing Classes,” the Date class is extended, the methods in the extended class can also access those variables.
The remaining type of access is called package access. A variable or method of a class defaults to package access if none of the other three modi iers are used. Package access means that the variable or method is accessible to any other class in the same package.
Lilian Day Numbers
Various approaches to numbering days have been proposed. Most choose a particular day in history as day 1, and then number the actual sequence of days from that day forward with the numbers 2, 3, and so on. The Lilian Day Number (LDN) system uses October 15, 1582, as day 1, or LDN 1.
Our current calendar is called the Gregorian calendar. It was established in 1582 by Pope Gregory XIII. At that time 10 days were dropped from the month of October, to make up for small errors that had accumulated throughout the years. Thus, the day following October 4, 1582, in the Gregorian calendar is October 15, 1582, also known as LDN 1 in the Lilian day numbering scheme. The scheme is named after Aloysius Lilius, an advisor to Pope Gregory and one of the principal instigators of the calendar reform.
Originally, Catholic European countries adopted the Gregorian calendar. Many Protestant nations, such as England and its colonies, did not adopt the Gregorian calendar until 1752, at which
time they also “lost” 11 days. Today, most countries use the Gregorian calendar, at least for of cial international business. When comparing historical dates, one must be careful about which calendars are being used.
In our Date class implementation, MINYEAR is 1583, representing the rst full year during which the Gregorian calendar was in operation. We assume that programmers will not use the Date class to represent dates before that time, although this rule is not enforced by the class. This assumption simpli es calculation of day numbers, as we do not have to worry about the phantom 10 days of October 1582.
To calculate LDNs, one must understand how the Gregorian calendar works. Years are usually 365 days long. However, every year evenly divisible by 4 is a leap year, 366 days long. This aligns the calendar closer to astronomical reality. To ne-tune the adjustment, if a year is evenly divisible by 100, it is not a leap year but, if it is also evenly divisible by 400, it is a leap year. Thus 2000 was a leap year, but 1900 was not.
Given a date, the lilian method of the Date class counts the number of days between that date and the hypothetical date 1/1/0—that is, January 1 of the year 0. This count is made under the assumption that the Gregorian reforms were in place during that entire time period. In other words, it uses the rules described in the previous paragraph. Let us call this number the Relative Day Number (RDN). To transform a given RDN to its corresponding LDN, we just need to subtract the RDN of October 14, 1582, from it. For example, to calculate the LDN of July 4, 1776, the method rst calculates its RDN (648,856) and then subtracts from it the RDN of October 14, 1582 (578,100), giving the result of 70,756.
Code for the lilian method is included with the program code les.
The Unified Method
Number
The object-oriented approach to programming is based on implementing models of reality. But how do you go about this? Where do you start? How do you proceed? The best plan is to follow an organized approach called a methodology
In the late 1980s, many people proposed object-oriented methodologies. By the mid1990s, three proposals stood out: the Object Modeling Technique, the Objectory Process, and the Booch Method. Between 1994 and 1997, the primary authors of these proposals got together and consolidated their ideas. The resulting methodology was dubbed the Uni ied Method. It is now, by far, the most popular organized approach to creating objectoriented systems.
The Uni ied Method features three key elements:
1. It is use-case driven. A use-case is a description of a sequence of actions performed by a user within the system to accomplish some task. The term “user” here should be interpreted in a broad sense and could represent another system.
2. It is architecture-centric. The word “architecture” refers to the overall structure of the target system, the way in which its components interact.
Date
#year:int
#month:int
#day:int
+MINYEAR:int = 1583
+Date(newMonth:int,newDay:int,newYear:int)
+getYear():int
+getMonth():int
+getDay():int
+lilian():int
+toString():String
3. It is iterative and incremental. The Uni ied Method involves a series of development cycles, with each one building upon the foundation established by its predecessors. One of the main bene its of the Uni ied Method is improved communication among the people involved in the project. The Uni ied Method includes a set of diagrams for this purpose, called the Uni ied Modeling Language (UML). 3 UML diagrams have become a de facto industry standard for modeling software. They are used to specify, visualize, construct, and document the components of a software system. We use UML class diagrams throughout this text to model our classes and their interrelationships.
A diagram representing the Date class is shown in Figure 1.1. The diagram follows the standard UML class notation approach. The name of the class appears in the top section of the diagram, the variables (attributes) appear in the next section, and the methods (operations) appear in the inal section. The diagram includes information about the nature of the variables and method parameters; for example, we can see at a glance that year, month, and day are all of type int. Note that the variable MINYEAR is underlined; this indicates that it is a class variable rather than an instance variable. The diagram also indicates the visibility or protection associated with each part of the class (+ = public, # = protected).
Objects
Objects are created from classes at run time. They can contain and manipulate data. Multiple objects can be created from the same class de inition. Once a class such as Date has been de ined, a program can create and use objects of that class. The effect is similar to expanding the language’s set of standard types to include a Date type. To create an object in Java we use the new operator, along with the class constructor, as follows:
Date myDate = new Date(6, 24, 1951);
Date yourDate = new Date(10, 11, 1953);
Date ourDate = new Date(6, 15, 1985);
3 The official definition of the UML is maintained by the Object Management Group. Detailed information can be found at http://www.uml.org/.
Figure 1.1 UML class diagram for the Date class
Another random document with no related content on Scribd:
common to various butterflies in Java, and calls it "phaeism"; and Bates states that in the Amazon valley numerous species of butterflies vary in a similar manner, as regards colour, in a locality. This phenomenon is now called "homoeochromatism," and is supposed to be due to the effect of local conditions on a susceptible organisation, though there is no experimental evidence of this.
Mimicry.—There are many cases in Lepidoptera of species that depart more or less strongly in appearance from those forms to which they are considered to be allied, and at the same time resemble more or less closely species to which they are less allied. This phenomenon is called mimicry.[204] Usually the resembling forms are actually associated during life. Bates, who observed this phenomenon in the Amazon valley, thought that it might be accounted for by the advantage resulting to the exceptionally coloured forms from the resemblance;[205] it being assumed that these were unprotected, while the forms they resembled were believed to be specially protected by nauseous odours or taste. It was, in fact, thought that the destroying enemies were deceived by the resemblance into supposing that the forms that were in reality edible were inedible. This subject has been greatly discussed, and in the course of the discussion numerous cases that could not be accounted for by Bates's hypothesis have been revealed. One of these is the fact that resemblances of the kind alluded to very frequently occur amongst inedible forms. This also has been thought to be accounted for by a supposed advantage to the Insects; it being argued that a certain number of "protected" forms are destroyed by enemies the instincts of which are faulty, and which therefore always require to learn by individual experience that a certain sort of colour is associated with a nasty taste. The next step of the argument is that it will be an advantage to a protected butterfly to form part of a large association of forms having one coloration, because the ignorant enemies will more easily learn the association of a certain form of coloration with nastiness; moreover such destruction as does occur will be distributed over a larger number of species, so that each species of a large, similarly coloured, inedible association will have a less number of its individuals destroyed. It is scarcely a matter for surprise that many naturalists are very sceptical as to these explanations; especially as the phenomena are supposed to have occurred in the past, so that they
cannot be directly verified or disproved. It has not, however, been found, as a matter of fact, that even unprotected butterflies are much destroyed in the perfect state by birds. Moreover, in endeavouring to realise the steps of the process of development of the resemblance, we meet with the difficulty that the amount of resemblance to the model that is assumed to be efficient at one step of the development, and to bring safety, is at the next step supposed to be inefficient and to involve destruction. In other words, while analysis of the explanation shows that it postulates a peculiar and well-directed discriminative power, and a persistent selection on the part of the birds, observation leads to the belief that birds have been but little concerned in the matter. If we add to this that there is no sufficient evidence that the species now similar were ever dissimilar (as it is supposed they were by the advocates of the hypothesis), we think it is clear that the explanation from our point of view is of but little importance.[206] The comparatively simple, hypothetical explanation, originally promulgated by Bates, is sometimes called Batesian mimicry; while the "inedible association" hypothesis is termed Müllerian mimicry
There is one branch of the subject of mimicry that we think of great interest. This is the resemblance between Insects of different Orders; or between Insects of the same Order, but belonging to groups that are essentially different in form and appearance. It is not infrequent for beetles to resemble Hymenoptera, and it is still more frequent for Lepidoptera to resemble Hymenoptera, and that not only in colour and form, but also in movements and attitude. Druce says: "Many of the species of Zygaenidae are the most wonderful of all the moths; in some cases they so closely resemble Hymenoptera that at first sight it is almost impossible to determine to which Order they belong."[207] W. Müller says: "The little Lepidoptera of the family Glaucopides, that are so like certain wasps as to completely deceive us, have when alive exactly the same manner of holding their wings, the same restless movements, the same irregular flight as a wasp."[208] Seitz and others record a case in which a Brazilian Macroglossa exactly resembles a humming-bird, in company with which it flies; and the same naturalist also tells us[209] of a Skipper butterfly that greatly resembles a grasshopper of the genus Tettix, and that moreover makes movements
like the jumping of grasshoppers. In most of these cases the probabilities of either original similarity, arrested evolution, or the action of similar conditions are excluded: and the hypothesis of the influence, by some means or other, of one organism on another is strongly suggested.
The classification of Lepidoptera was said by Latreille a century ago to be a reproach to entomologists. Since that time an enormous number of new species and genera have been described, but only recently has much advance been made in the way of improvement of classification. The progress made has been limited to a better comprehension and definition of the families. The nervuration of the wings is the character most in vogue for this purpose. As regards the larger groups, and Phylogeny, there is a general opinion prevalent to the effect that Micropterygidae, Eriocephalidae and Hepialidae are in a comparatively primitive condition, but as to the relations of these families one with the other, or with other Lepidoptera, there is a wide difference of opinion.
Fig. 176 Clubs of butterflies' antennae. Terminal portions of antenna of, 1, Pieris brassicae; 2, Styx infernalis; 3, Hestia idea (sub-family Danaides); 4, Eudamus proteus, and 5, Limochores taumas (Hesperiidae) (After Schatz and Scudder )
The primary divisions of the family most often met with in literature are: —either Rhopalocera (= butterflies) and Heterocera (= moths); or Macrolepidoptera and Microlepidoptera; the Macrolepidoptera including the butterflies and large moths, the Microlepidoptera being limited to the families Tineidae (now itself in process of division into numerous families) and Tortricidae; some entomologists including also Pyralidae, Pterophoridae and Orneodidae in Microlepidoptera. The division of all Lepidoptera into two series is merely a temporary device necessitated by imperfect acquaintance with morphology. The division into Macroand Micro- lepidoptera is entirely unscientific.
Series 1. Rhopalocera or Butterflies.—Antennae knobbed at the tip or thickened a little before the tip, without pectinations, projecting processes, or conspicuous arrangements of cilia. Hind wings without a frenulum, but with the costal nervure strongly curved at the base (Fig. 161, II, B).
Series II. Heterocera or Moths.—Antennae various in form, only rarely knobbed at the tip, and in such cases a frenulum present. In the large majority a frenulum is present, and the costal nervure of the hind-wing is either but little arched at the base (as in Fig. 161, I, B) or it has a large area between it and the front margin; but in certain families the hind wing is formed much as in Rhopalocera.
It may be inferred from these definitions that the distinction between the two sub-Orders is neither sharply defined nor of great importance. The club of the antenna of the Rhopalocera exhibits considerable variety in form (Fig. 176).[210] Butterflies are as a rule diurnal in their activity and moths nocturnal; but in the tropics there are numerous Heterocera that are diurnal, and many of these resemble butterflies not only in colour but even in the shapes of their wings.
Series I. Rhopalocera. Butterflies.
Classification and Families of Butterflies. Although considerable unanimity exists as to the natural groups of butterflies, there is much diversity of opinion as to what divisions are of equivalent value—some treating as sub-families groups that others call families—and as to the way the families should be combined. There is, however, a general agreement that the Hesperiidae are the most distinct of the families, and E. Reuter considers them a distinct sub-Order with the name Grypocera.[211]
Four categories may be readily distinguished, as follows, viz:—
1. The majority of butterflies; having the first pair of legs more or less strikingly different from the other pairs; frequently very much smaller and not used as
legs; when not very small, then differing according to sex of the same species, being smaller in the male than in the female; the part most peculiar is the tarsus, which is modified in various manners, but in the males of this great series is always destitute of its natural form of a succession of simple joints five in number. There is no pad on the front tibia
Fam. Nymphalidae, Erycinidae, Lycaenidae. [The distinctions between these three families are found in the amount and kind of the abortion of the front legs; for definition refer to the heading of each of the families ]
2. The front legs are in general form like the other pairs; their tibiae have no pads; the claws of all the feet are bifid, and there is an empodium in connection with them
Fam. Pieridae.
3 The front legs are like the other pairs; their tibiae however possess pads; the claws are large, not bifid, and there is no empodium; the metanotum is completely exposed at the base of the abdomen.
Fam. Papilionidae.
4 The front legs are like the other pairs; their tibiae however possess pads; the claws are small, toothed at the base, and there is an empodium; the metanotum is concealed by the prolonged and overhanging mesonotum.
Fam Hesperiidae
The relations between the families Erycinidae, Lycaenidae, and Nymphalidae are very intimate. All these have the front legs more or less modified, and the distinctions between the families depend almost entirely on generalisations as to these modifications. These facts have led Scudder to associate the Lycaenidae and Erycinidae in one group, which he terms "Rurales." It is however difficult to go so far and no farther; for the relations between both divisions of Rurales and the Nymphalidae are considerable. We shall subsequently find that the genus Libythea is by many retained as a separate family, chiefly because it is difficult to decide whether it should be placed in Erycinidae or in Nymphalidae. Hence it is difficult to see in this enormous complex of seven or eight thousand species more than a single great NymphaloLycaenid alliance. The forms really cognate in the three families are however so few, and the number of species in the whole is so very large, that it is a matter of great convenience in practice to keep the
three families apart. It is sufficient for larger purposes to bear in mind their intimate connexions.
The Papilionidae and Pieridae are treated by many as two sub-divisions of one group. But we have not been able to find any justification for this in the existence of forms with connecting characters. Indeed it would, from this point of view, appear that the Pieridae are more closely connected with the Lycaenidae and Erycinidae than they are with Papilionidae; in one important character, the absence of the pad of the front tibia, the Nymphalo-Lycaenids and the Pierids agree. It has also been frequently suggested that the Papilionidae (in the larger sense just mentioned) might be associated with the Hesperiidae. But no satisfactory links have been brought to light; and if one of the more lowly Hesperiids, such as Thanaos, be compared with one of the lower Papilionidae, such as Parnassius, very little approximation can be perceived.
It appears, therefore, at present that Hesperiidae, Papilionidae, Pieridae, and the Nymphalo-Lycaenid complex are naturally distinct. But in the following review of the families and sub-families of butterflies, we shall, in accordance with the views of the majority of Lepidopterists, treat the Lycaenidae and Erycinidae as families distinct from both Nymphalidae and Pieridae.[212]
The number of described species of butterflies is probably about 13,000; but the list is at present far from complete; forms of the largest size and most striking appearance being still occasionally discovered. Forty years ago the number known was not more than one-third or onefourth of what it is at present, and a crowd of novelties of the less conspicuous kinds is brought to light every year. Hence it is not too much to anticipate that 30,000, or even 40,000 forms may be acquired if entomologists continue to seek them with the enthusiasm and industry that have been manifested of late. On the other hand, the species of Rhopalocera seem to be peculiarly liable to dimorphic, to seasonal and to local variation; so that it is possible that ultimately the number of true species—that is, forms that do not breed together
actually or by means of intermediates, morphological or chronological— may have to be considerably reduced.
In Britain we have a list of only sixty-eight native butterflies, and some even of these are things of the past, while others are only too certainly disappearing. New Zealand is still poorer, possessing only eighteen; and this number will probably be but little increased by future discoveries. South America is the richest part of the world, and Wallace informs us that 600 species of butterflies could, forty years ago, be found in the environs of the city of Pará.
Fam. 1. Nymphalidae.—The front pair of legs much reduced in size in each sex, their tarsi in the male with but one joint, though in the female there are usually five but without any claws. Pupa suspended by the tail so as to hang down freely. We include in this family several sub-families treated by some taxonomists as families; in this respect we follow Bates, whose arrangement[213] still remains the basis of butterfly classification. With this extension the Nymphalidae is the most important of the families of butterflies, and includes upwards of 250 genera, and between 4000 and 5000 species. There are eight subfamilies.
It is in Nymphalidae that the act of pupation reaches its acme of complication and perfection; the pupae hang suspended by the tail, and the cremaster, that is the process at the end of the body, bears highlydeveloped hooks (Fig. 177, C, D). The variety in form of the chrysalids is extraordinary; humps or processes often project from the body, making the Insect a fantastic object; the strange appearance is frequently increased by patches like gold or silver, placed on various parts of the body. It is believed that the term chrysalid was first suggested by these golden pupæ. The Purple Emperor, Apatura iris, differs strikingly in the pupa as well as in the larva-stage from all our other Nymphalids; it is of green colour, very broad along the sides, but narrow on the dorsal and ventral aspects (Fig. 177). The skin of this pupa is less hard than usual, and the pupa seems to be of a very delicate constitution. The Purple Emperor, like some of the Satyrides as well as some of its more immediate congeners, hibernates in our
climate as a partially grown larva and passes consequently only a very brief period of its existence in the form of a pupa.
Fig 177 Pupa of the Purple Emperor butterfly, Apatura iris New Forest
A, Lateral, B, dorsal aspect; C, enlarged view of cremaster with the suspensory hook; D, one hook still more enlarged.
Sub-Fam. 1. Danaides.—Front wing with inner-margin (submedian) nervure, with a short fork at the base. Cell of hind wing closed. Front foot of the female ending in a corrugate knob. Caterpillars smooth, provided with a few long fleshy processes. The claws are in a variable state, being sometimes simple, as in Papilionidae, sometimes with an empodium, apparently of an imperfect kind. The Danaides are usually large Insects with an imperfect style of ornament and colour; they have a great deal of black or very dark scaling, and in some Euploea this is agreeably relieved by a violet or purple suffusion, and these are really fine Insects. Usually there are large pale spaces, of some neutral indefinite tint, on which black blotches are distributed in a striking but inartistic manner. In many of the species the markings are almost spot for spot the same on the upper and under sides. About seven genera and 250 species are recognised. Danaides occur in all the warmer parts of the world, but are most numerous in the Eastern tropics. In Europe the family is represented only by an Asiatic and African species, Limnas chrysippus, that has extended its range to Greece. Besides this another species, Anosia erippus, Cr. (unfortunately also called Anosia menippe, Hb., and Danais archippus or even D. plexippus) has in the last two or three decades extended its range to various islands and distant localities, concomitantly, it is believed, with an extension of the distribution of its food-plant, Asclepias. This Insect has several times been taken in this country, and may probably be a natural immigrant. It is a common butterfly in North America, where it is called the Monarch. [214]
Some, at least, of the Danaides are unpleasant to birds in odour or in taste, or both. Among them there occur, according to Moore[215] and others, numerous cases of resemblance between forms that are thus protected. It is possible that the odour and taste are of some value to the Insects;[216] as, however, butterflies of any kind appear to be but rarely attacked in the imago-state by birds, and as their chief enemies are parasitic Insects that attack the larval instar, it is impossible to consider this protection of such prime importance to the species as many theorists assume it to be.
178 Ithomia pusio. Brazil.
Sub-Fam. 2. Ithomiides.—Differs from Danaides by the female front foot having a true, though somewhat abbreviate tarsus. The caterpillers have no long processes. There has been considerable difference of opinion as to this division of butterflies. It is the family Neotropidae of Schatz, the Mechanitidae of Berg; also the "Danaioid Heliconiidae" of several previous writers, except that Ituna and Lycorea do not belong here but to Danaides. Godman and Salvin treat it as a group of the Danaid sub-family. The Ithomiides are peculiar to tropical America, where some 20 or 30 genera and about 500 species have been discovered. There is considerable variety amongst them. Ithomia and Hymenitis are remarkable for the small area of their wings, which bear remarkably few scales, these ornaments being in many cases limited to narrow bands along the margins of the wings, and a mark extending along the discocellular nervule. Wallace says they prefer the shades of the forest and flit, almost invisible, among the dark foliage. Many of these species have the hind-wings differently veined in the two sexes on the anterior part, in connection with the existence in the male of peculiar fine hairs, placed near the costal and subcostal veins. Tithorea and other forms are, however, heavily scaled insects of stronger build, their colours usually being black, tawny-red or brown, yellow, and white. In the sub-fam. Danaides, according to Fritz Müller, the male has scenttufts at the extremity of the abdomen, whereas in Ithomiides analogous
Fig.
structures exist on the upper side of the hind-wing. Ithomiides have various colour-resemblances with members of the Heliconiides and Pieridae; Tithorea has colour analogues in Heliconius, and Ithomia in Dismorphia (formerly called Leptalis). Crowds of individuals of certain species of Ithomia are occasionally met with, and mixed with them there are found a small number of examples of Dismorphia coloured like themselves. They are placed by Haase in his category of secondary models. Belt states that some Ithomiides are distasteful to monkeys and spiders, but are destroyed by Fossorial Hymenoptera, which use the butterflies as food for their young; and he also says that they are very wary when the wasp is near, and rise off their perches into the air, as if aware that the wasp will not then endeavour to seize them. Much information is given about the habits by Bates in the paper in which he first propounded the "theory of mimicry."[217] The larvae are said to live on Solanaceae.
The genus Hamadryas is placed by some writers in Danaides, by others in Ithomiides; and Haase has proposed to make it the group "Palaeotropinae." The species are small, black and white Insects, somewhat like Pierids. They are apparently hardy Insects, and are abundant in certain parts of the Austro-Malay region.
Sub-Fam. 3. Satyrides.—Palpi strongly pressed together, set in front with long, stiff hairs. Front wings frequently with one or more of the nervures swollen or bladder-like at the base of the wing. Cells of both wings closed. Caterpillar thickest at the middle, the hind end of the body bifid. Pupa generally suspended by the cremaster, without girth: but sometimes terrestrial. This is a very extensive group, consisting of upwards of 1000 species. The Insects are usually of small size, of various shades of brown or greyish colours, with circular or ringed marks on the under sides of the wings. It is found all over the world, and is well represented in Europe; our Meadow-browns, Heaths, and Marbled-whites, as well as the great genus Erebia of the highlands and mountains belonging to it. Most of these Insects have but feeble powers of flight, and rise but little from the surface of the ground. The caterpillars live on various grasses. They are usually green or brown, destitute of armature, and a good deal like the caterpillars of Noctuid moths, but the hind end of the body is thinner and divided to form two
corners, while the head is more or less free, or outstanding. The pupae are of great interest, inasmuch as in a few cases they do not suspend themselves in any way, but lie on the ground; sometimes in a very feeble cocoon or cell. There are no cremasteral hooks. The pupae of the Grayling butterfly, Hipparchia semele, has been found in loose soil a quarter of an inch below the surface. The chrysalis of the Scotch Argus, Erebia aethiops, was found by Mr Buckler to be neither suspended nor attached, but placed in a perpendicular position, head upwards, amongst the grass. In the majority of cases the pupa is, however, suspended as is usual in Nymphalidae. Nothing is known as to the nature of the peculiar inflation of the bases of the nervures of the front wings; it is well shown in our common species of Coenonympha; this character is not, however, constant throughout the family. There is in South America a very remarkable group of Satyrides consisting of the genera Cithaerias and Haetera, in which the wings are very delicate and transparent, bearing on the greater part of their area remote fine hairs instead of scales; there are nevertheless some scaled patches about the margins, and one or more of the ringed marks characteristic of the Satyrides; while in some species the distal portions of the hind wings are tinted with carmine. The species of the genus Pierella connect these transparent Satyrids with the more ordinary forms. According to Wallace the habits of these fairy-like forms are those characteristic of the family in general. The genus Elymnias has been separated by some authorities as a sub-family, or even as a family, Elymniidae, chiefly on the ground of a slight peculiarity in the termination of the branches of the veins at the outer angle of the front wings. The Elymnias are said to be of a mimetic nature, having a greater or less resemblance to butterflies of various other divisions; there is also a considerable difference in appearance between their own sexes. The larva of E. undularis is known; it is of the form usual in Satyrides, and lives on the palm Corypha. About 50 species, ranging from India to Australia, with two in Africa, are known of this interesting group.
Sub-Fam. 4. Morphides. There is no cell on the hind wing, the discocellular nervule being absent (Fig. 161, II. B). Caterpillars smooth or spiny, with the extremity of the body divided; frequently gregarious. These Insects have become notorious from the extraordinary brilliancy
of blue colour exhibited by the upper surface of the wings of the typical genus Morpho. The species of Morpho are all Insects of large size, but with wings enormous in proportion to the body; this latter part is carried in a sort of cradle formed by the inner parts of the margins of the hind wings. Although an arrangement of this kind is seen in numerous other butterflies, yet there is perhaps none in which it is carried to quite such a pitch of perfection as it is in Morpho, where, on the under surface no part of the body behind the posterior legs can be seen. There are only about 100 species of Morphides, and 50 of these are included in Morpho, which is peculiar to tropical and sub-tropical America; the other half of the family is divided among ten or twelve genera, found in the Indo-Malay region; there being none in Africa. The eastern Morphides, though fine Insects, are not to be compared, either in size or brilliancy, with their American allies. The species of Morpho are apparently found only in the great forests of South America, where they are far from rare; some have a flapping and undulating flight, straight onwards along the alleys of the forest, and near the ground; others are never seen except steadily gliding with outstretched wings from 20 to 100 feet above the ground, where they move across sunny spaces between the crowns of the taller trees; the low-flyers settle frequently on the ground to suck the juices from fallen fruit, but the members of the other section never descend to the ground. As regards the caterpillars, W. Müller tells us[218] that the spines they are armed with break off, and enter the skin, if the creatures are carelessly handled. Four of the five species known to him are conspicuously coloured with black, red, yellow and white. The individuals are gregarious. The larvae of M. achilles sit in companies, often of more than 100 individuals, on trunks of trees, and so form a conspicuous patch. The caterpillars of M. epistrophis hang together as red clumps on the twigs of their food-plants. Hence it appears that in this genus we have an exception to the rule that nightfeeding caterpillars rest in a hidden manner during the day.
Sub-Fam. 5. Brassolides.—Large butterflies, with the cell of the hind wing closed, and usually with a small adjoining prediscoidal cell. Larva not very spiny; thinner at the two ends, the tail bifid, the head perpendicular and margined with spines. This small sub-family includes less than 100 species arranged in about eight genera, all South American. They have the very unusual habit of resting during the day
like moths, becoming active only late in the afternoon. They are truly noble Insects; although not possessed of the brilliant colours of Morpho, they are adorned, especially on the under surface, with intricate lines and shades most harmoniously combined, while the upper surface is frequently suffused with blue or purple. This sub-family attains its highest perfection in the genus Caligo; they are enormous Insects, and some of them not rare. The larva of C. eurylochus (Fig. 179) during early life is green, and sits on the leaf of a Musa, but after the third moult it becomes brown and hides itself among the dry leaves. It is common in the gardens of Rio de Janeiro, where its pupae are found on the walls, like those of our white butterflies here.
Sub-Fam. 6. Acraeides. Submedian nervure of fore wings not forked at the base; the median without spur. Cells closed. Palpi in section cylindric, sparingly set with hairs. Larva armed with branched spines. A somewhat monotonous and uninteresting division; the size is moderate or small, and the colours not artistic, but consisting of ill-arranged spots; the under side of the hind wings very frequently diversified by numerous line-like marks, radiately arranged, and giving place at the base to a few spots. There are about 200 species known, of which the majority are African; there are but few Oriental or South American species. Some authorities consider there is only one genus, but others prefer to adopt seven or eight divisions. Alaena is now placed in Lycaenidae, though until recently it was considered to belong here. The females of some species possess an abdominal pouch somewhat similar to that of Parnassius.
The members of this sub-family are considered to be of the protected kind.
Fig 179 Larva of Caligo (Pavonia) eurylochus Rio de Janeiro × 1 (After Burmeister.)
Sub-Fam. 7. Heliconiides.—Submedian nervure of front wing not forked; median with a short spur near the base. Cell of hind wing closed by a perfect nervule. Palpi compressed, with scales at the sides, in front covered with hairs. Male with an elongate unjointed, female with a fourjointed, front tarsus. Caterpillars set with branched spines. This family is peculiar to tropical America and consists of only two genera, Heliconius and Eueides, with about 150 species; but it is one of the most characteristic of the South American groups of Butterflies. It is very closely allied to the Nymphalides, especially to the genera Metamorpha and Colaenis, but is readily distinguished by the perfectly-formed nervules that close the wing-cells. The wings are longer and narrower than in Nymphalides, and the colour, though exhibiting much diversity, is on the whole similar to that of the heavily-scaled forms of Ithomiides of the genera Tithorea, Melinaea, Melanitis; there being in several cases a great resemblance between species of the two groups. A frequent feature in one group of Heliconius is that the hind wing bears a patch of red prolonged outwards by angular radiating marks. The individuals of certain species—H. melpomene and H. rhea—are known to execute concerted dances, rising and falling in the air like gnats; when some of them withdraw from the concert others fill their places. H. erato exhibits the very rare condition of trichroism, the hind wings being either red, blue, or green. Schatz states that the different forms have been reared from a single brood of larvae. The caterpillars of Heliconiides live on Passiflorae, and are said to be very similar to our European Argynnis-caterpillars. The chrysalids are very spinous. We may here remark that considerable confusion exists in entomological literature in consequence of Ithomiides having been formerly included in this sub-family; for remarks formerly made as to "Heliconiides," but that really referred only to Ithomiides, have been interpreted as referring to Heliconiides of the present system.
The Heliconiides seem remarkably plastic as regards colour, and are therefore exponents of "homoeochromatism." Bates says, as regards them: "In tropical South America a numerous series of gaily-coloured butterflies and moths, of very different families, which occur in abundance in almost every locality a naturalist may visit, are found all to change their hues and markings together, as if by the touch of an enchanter's wand, at every few hundred miles, the distances being
shorter near the eastern slopes of the Andes than nearer the Atlantic. So close is the accord of some half-dozen species (of widely different genera) in each change, that he had seen them in large collections classed and named respectively as one species."[219] Many of them are believed to be permeated by nauseous fluids, or to possess glands producing ill-smelling secretions.
Sub-Fam. 8. Nymphalides. Cells, of both front and hind wing, either closed only by imperfect transverse nervules or entirely open. Front tarsus of the male unjointed and without spines, of the female four- or five-jointed. Caterpillar either spined or smooth; in the latter case the head more or less strongly horned or spined, and the apex of the body bifid. This sub-family is specially characterised by the open cells of the wings; the discocellulars, even when present, being frequently so imperfect as to escape all but the most careful observation. The Nymphalides include upwards of 150 genera and 2000 species. The divisions having smooth larvae are separated by Kirby[220] and others as a distinct sub-family (Apaturides). In Britain, as in most other parts of the world, Nymphalides is the predominant group of butterflies. We have eighteen species, among which are included the Fritillaries, Admirals, Purple Emperor, and the various Vanessa—Peacock, Camberwell Beauty, Red Admiral, Tortoise-shells, and Painted Lady. All have spined caterpillars except the Emperor. In the temperate regions of the northern hemisphere Vanessa may be considered the dominant butterflies, they being very numerous in individuals, though not in species, and being, many of them, in no wise discomfited by the neighbourhood of our own species. Several of them are capable of prolonging and interrupting their lives in the winged condition to suit our climate; and this in a manner that can scarcely be called hibernation, for they frequently take up the position of repose when the weather is still warm, and on the other hand recommence their activity in the spring at a very early period. This phenomenon may frequently be noticed in the Tortoise-shell butterfly; it is as if the creature knew that however warm it may be in the autumn there will be no more growth of food for its young, and that in the spring vegetation is sure to be forthcoming and abundant before long, although there may be little or none at the time the creature resumes its activity. It is probable that the habit may be in some way connected with an imperfect activity of the
sexual organs. It should, however, be recollected that many larvae of butterflies hibernate as young larvae after hatching, and, sometimes, without taking any food. Pyrameis cardui, the Painted Lady, is, taking all into consideration, entitled to be considered the most ubiquitous of the butterfly tribe. Its distribution is very wide, and is probably still extending. The creature is found in enormous numbers in some localities, especially in Northern and Eastern Africa; and when its numbers increase greatly, migration takes place, and the Insect spreads even to localities where it cannot maintain itself permanently. In Britain it is probably during some years nearly or quite absent, but may suddenly appear in large numbers as an immigrant. The favourite food of the larva is thistles, but many other plants serve the Insect at times.
Vanessa, or Pyrameis, [221] atalanta, the Red Admiral, is common in the Palaearctic and Nearctic regions, and extends its range to various outlying spots. The most remarkable of these is the remote Hawaiian Islands, where the Insect appears really to be now at home, though it is associated with a larger and more powerful congener, P. tameamea. Another interesting Vanessid is Araschnia levana, which is peculiar to Europe, where it produces annually two generations so dissimilar to one another that they passed current as two species, V. levana and V. prorsa Although intermediate forms are rare in nature they can be induced by certain treatments applied to the larvae under human control.
The dead-leaf butterflies of the genus Kallima belong to Nymphalides. They are so shaped and coloured that when settled, with wings closed, on a twig, the appearance is exactly that of a dry leaf; the exposed surface is mottled with spots that look just like the patches of minute fungi, etc. that are so common on decaying vegetation. The colour and the spots on the under surface of this butterfly are very variable.
According to Mr. Skertchly,[222] we may presume that in the minute details of these resemblances we have a case of hypertely similar to that of the resemblance to Insects' minings exhibited by certain marks on the tegmina of Pterochroza (mentioned in Vol. V. p. 322).
In South America there is a somewhat peculiar genus of Nymphalides —Ageronia—that delights in settling on the trunks of trees rather than on flowers or leaves. It was long since noticed that the the species of Ageronia make a clicking noise; in some cases when on the wing, in other cases by moving the wings when the Insect is settled. The object of the noise is quite uncertain; it has been suggested that it is done in rivalry or courtship, or to frighten away enemies. Bigg-Wether found, however, that in South Brazil there is a lazy little bird to which this sound serves as a signal, inducing it to descend from its perch and eat the clicker. The mode in which the noise is produced is not quite clear. Sir George Hampson has pointed out[223] that the fore wing bears at the extreme base a small appendage bearing two hooks, and that two other processes on the thorax play on these when the wing moves. His suggestion that these hooks are the source of the sound seems highly probable.
There is a great variety in the larvae of Nymphalides. In the Vanessa group the body is armed with spines, each one of which bears shorter thorns, the head being unadorned. The Fritillaries (Argynnis, Melitaea) also have caterpillars of this kind. In many other forms the head itself is armed with horns or spines of diverse, and frequently remarkable, character. In Apatura and its allies the body is without armature, but the head is perpendicular, the vertex bifid and more or less prolonged. The caterpillar of our Purple Emperor, Apatura iris, is quite unlike any other British caterpillar; in colour it is like a Sphingid larva—green with oblique lateral stripes of yellow and red—but in form it is slug-like, pointed behind, and it has on the head two rather long tentacle-like horns. In the South American genus Prepona, the larva of which in general form resembles that of Apatura there are no anal claspers, but the extremity of the body is prolonged, forming a sort of tail.
Fam. 2. Erycinidae (Lemoniidae of some authors).—The female has six perfectly formed legs, though the front pair is smaller. The male has the coxae of the front legs forming a spine, and the tarsi unjointed, without claws. This family consists of about 1000 species, usually of rather small size, exhibiting a great variety of shape and coloration, some of them being remarkably similar to some of the gay, diurnal moths of South America. The palpi are usually small, but in Ourocnemis
they are large and porrect. The family is specially characteristic of tropical America, but there is one small group of 30 or 40 species, Nemeobiides, in the Eastern Hemisphere. We have one species in Britain, Nemeobius lucina, the Duke of Burgundy Fritillary. Neither the larvae nor the pupae of Erycinidae present any well-marked characteristic feature, but exhibit considerable variety. According to Bar, [224] some of the larvae are like those of moths; the caterpillar of Meliboeus is said to be like that of a Liparis: the chrysalis has the short, rounded form of that of the Lycaenidae, and is suspended with the head down, and without a band round the body. The larvae of Eurygona are gregarious. The pupae of some other forms adhere, heads downwards, to branches. Scudder considers that this family is not distinct from Lycaenidae, and that the Central American genus Eumaeus connects the two. Reuter also treats Erycinidae as a division of Lycaenidae.
Sub-Fam. 1. Erycinides.—[Characters of the family.] Palpi not unusually large. We place all the Erycinidae in this sub-family except the following—
Sub-Fam. 2. Libytheides.—Butterflies of average size, with the palpi large and porrect: the front legs of the male small, the tarsus reduced to one joint: the front leg of the female of the normal structure, and but little reduced in size. This division consists of the single genus Libythea, with only a score of species. They are Insects somewhat like Vanessa in appearance, but cannot fail to be recognised on account of the peculiar palpi. The genus is of very wide distribution, occurring in most parts of the warm and temperate continental regions, and it also occurs in Mauritius and the Antilles.
The Libytheides have given rise to much difference of opinion amongst systematists, some of whom assign them as a sub-family to the Erycinidae, some to the Nymphalidae; while others treat them as a family apart. The families Nymphalidae, Erycinidae and Lycaenidae are so intimately allied, that Scudder is probably correct in considering them to form really one huge family; if this view were adopted there would be no difficulty in locating Libythea therein. If they be kept apart, it is almost necessary to separate Libythea also; though possibly its
claims to be placed in Erycinidae slightly preponderate. The recently described genus Ourocnemis to some extent connects Erycinides with Libythaeides.[225]
Fam. 3. Lycaenidae. The front legs but little smaller than the others: in the male, however, the tarsus, though elongate, is only of one joint, and is terminated by a single claw No pad on the front tibia. Claws not toothed. The Lycaenidae, or Blues, are, as a rule, of small size, but in the tropics there are many that reach the average size of butterflies, i.e. something about the stature of the Tortoise-shell butterfly. The family is one of the larger of the divisions of butterflies, considerably more than 2000 species being at present known, and this number is still rapidly increasing. Although blue on a part of the upper surface is a very common feature in the group, it is by no means universal, for there are many "Coppers," as well as yellow and white Lycaenidae. Many species have delicate, flimsy appendages—tails—to the hind wings, but in many others these are quite absent; and there are even tailed and tailless forms of the same species. The members of the group Lipteninae (Liptena, Vanessula, Mimacraea, etc.) resemble members of other sub-families of Nymphalidae, and even of Pieridae. Lycaenidae are well represented wherever there are butterflies; in Britain we have 18 species.
The larvae of this family are very peculiar, being short, thicker in the middle, and destitute of the armature of spines so remarkable in many other caterpillars. It has of late years been frequently recorded that some of these larvae are attended by ants, which use their antennae to stroke the caterpillars and induce them to yield a fluid of which the ants are fond. Guénée had previously called attention[226] to the existence of peculiar structures contained in small cavities on the posterior part of the caterpillar of Lycaena baetica. These structures can be evaginated, and, it is believed, secrete a fluid; Edwards and M‘Cook are of opinion that they are the source of the matter coveted by the ants. The larvae are without spines.
The caterpillars of the Blues have some of them strange tastes; more than one has been recorded as habitually feeding on Aphidae and
scale-Insects. The pupae are, like the larvae, of short inflated form. By a remarkable coincidence, the pupae of two species bear a considerable resemblance to the heads of monkeys, or mummies. The Lycaenid pupa is usually extremely consolidated, destitute of movement, and is supported—in addition to the attachment by the cremaster—by a silk thread girdling the middle. There are exceptions to these rules, and according to Mr Robson the pupa of Tajuria diaeus hangs free, suspended from a leaf, and can move the body at the spot where the abdominal segments meet the wing-cases in the dorsal line. [227]
Fam. 4. Pieridae. The six legs well developed, and similar in the sexes; there is no pad on the front tibia. The claws of all the feet are bifid, or toothed, and there is an empodium. There are upwards of 1000 species of Pieridae already known. Although several taxonomists treat the Pieridae and Papilionidae as only subdivisions of one family, yet they appear to be quite distinct, and the relationships of the former to be rather with Lycaenidae. In Pieridae, white, yellow, and red are the predominant colours, though there is much black also. It has recently been ascertained that the yellow and red pigments, as well as the white, are uric acid or derivatives therefrom.[228] The physiology of this peculiarity has not yet been elucidated, so that we do not know whether it may be connected with some state of the Malpighian vessels during metamorphosis.
Our Garden-White, Brimstone, Clouded-yellows and Orange-tip butterflies belong to this family; as does also the South American genus formerly called Leptalis. This generic name, which is much mentioned in literature owing to the resemblance of the species of the genus to Heliconiides, has now disappeared; Leptalis having been divided into various genera, while the name itself is now considered merely a synonym of Dismorphia.
The African Insect, Pseudopontia paradoxa, has nearly transparent wings, no club to the antennae, a remarkably small cell on the wing, and an arrangement of the nervules not found in any other butterfly; there being only ten nervules at the periphery of the front wing, and