SlideShare a Scribd company logo
Objectoriented Programming And Java 2nd Ed Danny
C C Poo Derek Beng Kee Kiong Swarnalatha Ashok
download
https://ebookbell.com/product/objectoriented-programming-and-
java-2nd-ed-danny-c-c-poo-derek-beng-kee-kiong-swarnalatha-
ashok-4104850
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Objectoriented Programming And Java Second Edition 2nd Danny Poo
https://ebookbell.com/product/objectoriented-programming-and-java-
second-edition-2nd-danny-poo-2256754
Objectoriented Programming Using C And Java Anand Vasappanavara Gautam
Vasappanavara Ramesh Vasappanavara Anand Vasappanavara
https://ebookbell.com/product/objectoriented-programming-using-c-and-
java-anand-vasappanavara-gautam-vasappanavara-ramesh-vasappanavara-
anand-vasappanavara-7261816
Programming With Objects A Comparative Presentation Of Objectoriented
Programming With C And Java 1st Edition Avinash Kak
https://ebookbell.com/product/programming-with-objects-a-comparative-
presentation-of-objectoriented-programming-with-c-and-java-1st-
edition-avinash-kak-924368
The Java Workshop Learn Objectoriented Programming And Kickstart Your
Career In Software Development David Cuartielles
https://ebookbell.com/product/the-java-workshop-learn-objectoriented-
programming-and-kickstart-your-career-in-software-development-david-
cuartielles-46712648
Java Methods A Ab Objectoriented Programming And Data Structures
Student Maria Litvin
https://ebookbell.com/product/java-methods-a-ab-objectoriented-
programming-and-data-structures-student-maria-litvin-2393214
Java Methods Objectoriented Programming And Data Structures Third Ap
3rd Ap Maria Litvin
https://ebookbell.com/product/java-methods-objectoriented-programming-
and-data-structures-third-ap-3rd-ap-maria-litvin-59073076
Java Methods Objectoriented Programming And Data Structures 4th
Edition 4th Maria Litvin
https://ebookbell.com/product/java-methods-objectoriented-programming-
and-data-structures-4th-edition-4th-maria-litvin-60399372
The Essence Of Object Oriented Programming With Java And Uml Bruce E
Wampler
https://ebookbell.com/product/the-essence-of-object-oriented-
programming-with-java-and-uml-bruce-e-wampler-983966
Mastering Java An Effective Project Based Approach Including Web
Development Data Structures Gui Programming And Object Oriented
Programming Beginner To Advanced White
https://ebookbell.com/product/mastering-java-an-effective-project-
based-approach-including-web-development-data-structures-gui-
programming-and-object-oriented-programming-beginner-to-advanced-
white-11063222
Objectoriented Programming And Java 2nd Ed Danny C C Poo Derek Beng Kee Kiong Swarnalatha Ashok
Danny Poo Derek Kiong
Swarnalatha Ashok
Object-Oriented
Second edition
Programming
and Java
• •
School of Computing
National University of Singapore, Singapore
Institute of Systems Science
National University of Singapore, Singapore
Ms Swarnalatha Ashok
Institute of Systems Science
National University of Singapore, Singapore
British Library Cataloguing in Publication Data
A catalogue record for this book is available from the British Library
ISBN-13: 978-1-84628-962-0 e-ISBN-13: 978-1-84628-963-7
First edition © Springer Singapore 1998; 978-981-3083-96-7
Printed on acid-free paper
© Springer-Verlag London Limited 2008
Apart from any fair dealing for the purposes of research or private study, or criticism or review, as permitted
under the Copyright, Designs and Patents Act 1988, this publication may only be reproduced, stored or
transmitted, in any form or by any means, with the prior permission in writing of the publishers, or in the
case of reprographic reproduction in accordance with the terms of licences issued by the Copyright
Licensing Agency. Enquiries concerning reproduction outside those terms should be sent to the publishers.
The use of registered names, trademarks, etc. in this publication does not imply, even in the absence of a
specific statement, that such names are exempt from the relevant laws and regulations and therefore free for
general use.
The publisher makes no representation, express or implied, with regard to the accuracy of the information
contained in this book and cannot accept any legal responsibility or liability for any errors or omissions that
may be made.
9 8 7 6 5 4 3 2 1
Springer Science+Business Media
springer.com
Dr Danny Poo Dr Derek Kiong
Library of Congress Control Number: 2007934261
1 Introduction 1
1.1 Object-Oriented Programming 1
1.2 Objects and Their Interactions in the Real World 2
1.3 Objects and Their Interactions in Programming 3
1.4 Simulation 3
1.5 Java 4
1.6 Summary 4
1.7 Exercises 5
2 Object, Class, Message and Method 7
2.1 Objects and Class 7
2.2 Message and Method
2.2.1 Message Components 10
2.2.2 Method
2.2.3 Client and Server
2.3 Creating Objects 12
2.4 Summary 14
2.5 Exercises 14
3 A Quick Tour of Java 17
3.1 Primitive Types 17
3.2 Object Definition 18
3.2.1 Variable Definitions 18
3.2.2 Methods 19
3.3 Object Instantiation 20
3.4 Object Access and Message Passing 21
3.5 Representational Independence 21
3.6 Overloading 22
3.7 Initialization and Constructors 23
9
10
11
Preface to 1st Edition xiii
Preface to 2nd Edition
Overview xvii
Acknowledgement xix
Table of Contents
xv
vi Table of Contents
3.11 Arrays 34
3.12 Result Returned by Method 35
3.13 Summary 36
3.14 Exercises 36
4 Implementation in Java 39
4.1 Calculator 39
4.1.1 The clear() Method 40
4.1.2 The display() Method 41
4.1.3 The digit() Method 41
4.1.4 41
4.2 Code Execution 42
4.3 Simple User Interface 44
4.4 Another Interface for CalculatorEngine 46
4.5 Summary 49
4.6 Exercises 49
5 Classification, Generalization, and Specialization 51
5.1 Classification 51
5.2 Hierarchical Relationship of Classes 53
5.2.1 Superclass and Subclass 53
5.2.2 A Class Hierarchy Diagram 54
5.3 Generalization 55
5.4 Specialization 56
5.5 Organization of Class Hierarchy 56
5.6 Abstract and Concrete Classes 57
5.7 Summary 58
5.8 Exercises 58
6 Inheritance 61
6.1 Common Properties 61
6.2 Inheritance 62
6.3 Implementing Inheritance 64
6.4 Code Reuse 67
4.4.1
Operator Methods
Event-Driven Programming 48
3.8.2 Expression Statements 30
3.8.3 Control-flow Statements 30
3.9 Blocks 32
3.9.1 Local Declarations 32
3.10 More Control-flow Statements 33
3.8 Expressions, Statements, and Control-flow Mechanisms 24
3.8.1 Operators 24
Table of Contents vii
6.7 Inheritance Chain 75
6.7.1 Multiple Inheritance 76
6.7.2 Problems Associated with Multiple Inheritance 77
6.7.3 Contract and Implementation Parts 79
6.7.4 Contract and Implementation Inheritance 79
6.8 Interface 80
6.8.1 Multiple Inheritance Using Interface 80
6.8.2 Attributes in an Interface 83
6.8.3 Methods in an Interface 83
6.8.4 Abstract Class and Interface 83
6.8.5 Extending Interface 84
6.8.6 Limitations of Interface for
Multiple Inheritance 85
6.9 Summary 88
6.10 Exercises 89
7 Polymorphism 93
7.1 Static Binding 93
7.2 Dynamic Binding 96
7.3 Operation Overloading 97
7.3.1 Same Method Signature 97
7.3.2 Overloading Method Names 98
7.4 Polymorphism 100
7.4.1 Selection of Method 100
7.4.2 Incremental Development 101
7.4.3 Increased Code Readability 102
7.5 Summary 102
7.6 Exercises 102
8 Modularity 103
8.1 Methods and Classes as Program Units 103
8.2 Object and Class Properties 103
8.2.1 Counting Instances 104
8.2.2 Shared Attributes 106
8.2.3 Class Attributes 107
6.5.1 Change in Property Definition for
All Subclasses 67
6.5.2 Change in Property Definition for Some
Subclasses 68
6.5.3 Adding/Deleting a Class 72
6.6 Accessing Inherited Properties 75
6.5 Making Changes in Class Hierarchy 67
viii Table of Contents
8.5 Encapsulation 111
8.5.1 Bundling and Information Hiding 112
8.5.2 Enhanced Software Maintainability 112
8.5.3 Trade-Off 115
8.6 Summary 116
8.7 Exercises 117
9 Exception Handling 119
9.1 Using Exceptions 119
9.2 Exception Terminology 120
9.3 Constructs and Exception Semantics in Java 120
9.3.1 Defining Exception Objects 121
9.3.2 Defining Exception Handlers 121
9.3.3 Raising Exceptions 122
9.4 A Simple Example 123
9.5 Paradigms for Exception Handling 125
9.5.1 Multiple Handlers 125
9.5.2 Regular Exception Handling 127
9.5.3 Accessing Exception Objects 128
9.5.4 Subconditions 128
9.5.5 Nested Exception Handlers 129
9.5.6 Layered Condition Handling 130
9.6 Code Finalization and Cleaning Up 130
9.6.1 Object Finalization 131
9.6.2 Block Finalization 131
9.7 Summary 132
9.8 Exercises 133
10 Input and Output Operations 135
10.1 An Introduction to the Java API 135
10.2 Reading the Java API Documentation 136
10.3 Basic Input and Output 138
10.4 File Manipulation 141
10.4.1 File Input 142
10.4.2 File Output 143
8.2.4 Class Methods 107
8.2.5 Name Aliases
8.3 Controlling Visibility 108
8.4 Packages 110
8.4.1 The package Keyword 110
8.4.2 The import Keyword 110
108
10.4.3 Printing Using PrintStream 144
Table of Contents ix
10.9 Formatting the Output Using the Format String 151
10.10 The File Class 152
10.11 Random Access File Operations 152
10.12 Summary 153
10.13 Exercises 153
11 Networking and Multithreading 155
11.1 The Network Model 155
11.2 Sockets in Java 156
11.2.1 Example Client: Web Page Retriever 157
11.3 Listener Sockets in Java 161
11.3.1 Example Server: Simple Web Server 161
11.3.2 Running the Web Server 164
11.4 Considering Multiple Threads of Execution 165
11.5 Creating Multiple Threads of Execution 166
11.5.1 Thread Creation Using the Thread Class 166
11.5.2 Thread Creation Using the
Runnable Interface 168
11.6 Improvement of Web Server Example 168
11.7 Thread Synchronization and Shared Resources 169
11.8 Summary 175
11.9 Exercises 176
12 Generics and Collections Framework 179
12.1 Introduction 179
12.2 Rationale Behind Generics 179
12.2.1 The Problem 180
12.2.2 Run-time Type Identification (RTTI) 182
12.3 Java Generics 183
12.3.1 Generic Class 183
12.3.2 Generic Method 185
12.4 Collections Framework 186
12.4.1 Collections Interface
12.4.2 ArrayList Class 187
186
10.5 Framework for Code Reuse 145
10.6 DataInputStream and DataOutputStream Byte
Stream Class 147
10.7 Character Stream Classes 148
10.8 Tokenizing the Input Using the Scanner Class 150
12.4.3 HashSet Class 190
12.4.4 HashMap Class 194
12.5 Sorting Collections 196
x Table of Contents
12.6.2 binarySearch Method 198
12.7 Summary 199
12.8 Exercises 199
13 Graphical Interfaces and Windows 201
13.1 The AWT Model 201
13.2 Basic AWT Constituents 202
13.2.1 Frames 203
13.2.2 Components 204
13.2.3 Panels 205
13.2.4 Layout in Panels 206
13.2.5 Events 209
13.2.6 Events in JDK 1.1 (and later versions) 212
13.3 Basic Components 214
13.3.1 Label Component 214
13.3.2 Button Component 215
13.3.3 Checkbox Component 215
13.3.4 CheckboxGroup Component 215
13.3.5 TextArea Component 216
13.3.6 Choice Component 217
13.3.7 List Component 218
13.3.8 Menus and Menu Items 219
13.3.9 Dialog Frames 221
13.3.10 File Dialog Frames 223
13.4 Custom Components 224
13.5 Other Kinds of Class Definitions 226
13.5.1 Inner Classes 227
13.5.2 Anonymous Classes 227
13.5.3 Local Classes 228
13.6 Swing Components 230
13.6.1 Transiting from AWT to Swing 231
13.6.2 Model versus View 234
13.7 Summary 235
13.8 Exercises 236
12.5.1 Sort Algorithm
12.5.2 Comparator Interface
12.6 Searching Collections 198
12.6.1 indexOf and contains Methods 198
196
197
14 Applets and Loaders 237
14.1 Applet Characteristics 237
14.2 Applet Life Cycle 241
Table of Contents xi
14.6 Efficient Repainting 247
14.7 Applet Parameters 248
14.8 Loading Code Dynamically 250
14.9 Security Restrictions for Untrusted Code 253
14.9.1 Security Policy 255
14.9.2 Keys 256
14.9.3 Permissions 256
14.10 Summary 258
14.11 Exercises 258
15 Java Servlets 259
15.1 Dynamic Web Pages and Servlets 259
15.2 Tomcat Installation 260
15.2.1 Downloading and Installation 260
15.2.2 Configuration 261
15.2.3 Starting and Stopping Tomcat 262
15.3 Sample Servlet 263
15.4 Servlet Characteristics 266
15.5 Servlet Paramters and Headers 266
15.6 Servlet Output 271
15.7 Handling Sessions 271
15.7.1 Session Timeout 274
15.8 Concurrency 274
15.9 Customized Processors 274
15.10 Summary 276
15.11 Exercises 277
16 Object Serialization and Remote Method Invocation 279
16.1 Object Serialization 279
16.2 Components in Object Serialization 281
16.3 Custom Serialization 281
16.3.1 The Externalizable Interface 284
16.4 Distributed Computing with Java 284
16.4.1 RMI and CORBA 285
16.4.2 Java Limitations 285
16.5 An Overview of Java RMI 286
14.3 Custom Applets 242
14.4 Images and Audio 243
14.5 Animation in Applets 245
16.6 Using Java RMI 287
16.6.1 Setting Up the Environment on Your
Local Machine 287
xii Table of Contents
16.7 RMI System Architecture 289
16.8 Under the Hood 291
16.9 RMI Deployment 293
16.10 Summary 295
16.11 Exercises 295
17 Java Database Connectivity 297
17.1 Introduction 297
17.2 Java Database Connectivity 297
17.3 JDBC Architecture 298
17.4 JDBC Drivers
17.4.1 Types of Drivers
17.5 JDBC APIs 302
17.5.1 Establishing a Connection 302
17.5.2 Data Manipulation
17.6 Data Definition Language (DDL) with JDBC 305
17.6.1 Creating a Table 305
17.6.2 Dropping a Table 306
17.7 Data Manipulation Language (DML) with JDBC 307
17.7.1 Creating (Inserting) Records Using JDBC 307
17.7.2 Deleting Records Using JDBC 307
17.7.3 Retrieving Records Using JDBC 307
17.7.4 Updating Records Using JDBC 309
17.7.5 Updatable Result Sets 310
17.7.6 Prepared Statements 311
17.8 Summary 313
17.9 Exercises 313
298
299
303
Index 315
16.6.2 How RMI Works
16.6.3 An RMI Example 288
287
Preface to 1st Edition
Control abstraction was the message of the first programming revolution seen in
high-level programming languages such as Algol and Pascal. The focus of the next
revolution was data abstraction, which proposed languages such as Modula and Ada.
The object-oriented revolution began slowly in the 1960s with the programming
language Simula, but moved onto more languages such as Smalltalk, Objective-C
and C++. Java is almost a hybrid between Smalltalk and C++, and has gained
widespread acceptance due to its association with the Internet, its availability to a
large user base and reusable libraries for programming in a graphical environment.
Our programming lineage has passed through Pascal, C and C++. As with
many other programmers, good run-time checks with automatic memory manage-
ment and a reusable API made Java a very attractive option. After a half-day on the
original Java Whitepaper and the early Java online tutorial, we were sold on the Java
bandwagon and already writing code. In another two days’ time, we were using
the Abstract Windowing Toolkit (AWT) package for graphical applications. In
situations where there is no large investment into older languages, we are quite
happy to abandon them completely.
Effective programming in Java comes from understanding three key areas –
object-oriented concepts, the syntax and semantics of the Java programming language
and the Java Application Programming Interface (API). This is our emphasis when
we conduct professional courses, and in this book as well.
Much of the material in this book is based on previous courses which we
have conducted over the past two years to the industry and the National University
of Singapore (NUS). Courses conducted for the industry last about 5 to 7 days,
depending on the amount of coaching that participants require. In the Department of
Information Systems and Computer Science at NUS, a course on “Object-Oriented
Methods” runs over 13 weeks.
As you might have noticed, we have taken to Java as ducks to water. Java has
allowed us to think about and specify object behavior. This results in executable
code which is merely secondary. What is important is the clean specification of
object behavior. Similarly, in getting accustomed to working with objects, we
believe that you will enjoy it too.
Preface to 2nd Edition
Since publishing the first edition almost 10 years ago, we have seen Java being used
in many high school and university programming courses. Further, many projects
now use Java as the implementation language. Similarly, at the Institute of Systems
Science, we have seen professional developers warming up to Java for the first time
in 1998, to those who use Java in their daily work in 2007.
We have thus updated the material to cover J2EE topics such as JDBC, RMI,
Serialization and Java Servlets. We have also added a chapter on Generics as the
Java language evolved to allow this elegant feature.
For those who might be embarking on a Java journey now, we wish you a
pleasant journey and a well-used road map. Many have taken this journey before and
are enjoying the fruits of their learning investment.
Chapter 1 presents an introduction to the object-oriented world consisting of objects
and object communication via the exchange of messages. Object-oriented concepts
and terminology used in object-oriented methodology are discussed in chapter 2.
Chapter 3 shows how these concepts materialize in the form of Java code and
representations. It discusses the basic features and syntax of Java and builds upon the
concepts using an incremental Counter example.
Following on from language syntax, chapter 4 demonstrates the standard pro-
gramming environment using the Java Development Kit (JDK), and how a class
definition may be compiled and executed, integrated and reused within other code
fragments. The chapter also delves into using the Java Application Programming
Interface (API) to demonstrate the ease and productivity gains of code libraries.
Chapter 5 returns to the discussion of objects, in particular, the organization of
objects into manageable classes. The concept of class enables a developer to organize
a complex problem domain into more manageable components. Grouping objects into
classes is an act known as classification in object-oriented modeling. When classes
are formed, they can be further distinguished into superclasses or subclasses, accord-
ing to their similarities or differences in properties. Class hierarchies can then be
formed. The creation of superclasses and subclasses is achieved through abstracttion
mechanisms known as generalization and specialization respectively. Classification,
generalization and specialization are thus important abstraction mechanisms for
organizing objects and managing complexities.
Inheritance is discussed in chapter 6. Common properties of classes can be shared
with other classes of objects via the inheritance mechanism. It is through inheritance
that software component reuse is possible in object-oriented programming. Software
reusability is important because code need not be produced from scratch, thereby
increasing the productivity of developers.
Another topic close to the heart of object-oriented programming is polymorphism.
This topic is concerned with object messaging and how objects of different classes
respond to the same message. With polymorphism, objects of different class definition
can respond to the same message with the appropriate method. In this way, generic
software code can be produced, thus enhancing the maintainability of software systems.
Polymorphism is supported by dynamic binding and operation overloading, topics
that are central to the discussion in chapter 7.
Enhancing software maintainability is a significant software development
objective. A programming technique known as Structured Programming was intro-
Overview
for achieving maintainable software. Modularity is emphasized in object-oriented
duced in the 1980s, promoting modularity as a Software Engineering principle
programming in the form of method, object, and class definition. Encapsulation is
the manifestation of modularity in object-oriented programming to the fullest. As
will be made clear in chapter 8, encapsulation brings together related properties into
class definitions with the structural definition of classes hidden from their users. The
purpose of this approach is to hide the implementation detail of objects so that when
changes in implementation of objects are called for, users of the objects will not be
adversely affected.
Exception Handling is considered in chapter 9. This is especially important in
object-oriented programming, as the mechanism for the glue and safety net in code
integration and reuse.
The Java API is introduced in chapter 10 and continues with the core classes for
input/output, networking, graphical components and applets within Web browsers.
Input and output rely on InputStream and OutputStream classes, as well as Reader
and Writer classes in JDK 1.1.
Chapter 11 introduces network connections via TCP/IP using the Socket
class, similar to those for input and output in chapter 10, as they share behavior from
InputStream and OutputStream. As multi-processing is typically used with client/
server applications, we have also included the multi-threading API in this chapter,
together with a skeleton Web server as the working example.
Collection classes with Generics in chapter 12 show how the concepts of modu-
larity and encapsulation work to facilitate code reuse. This chapter not only gives an
overview of the classes in the Collections Framework, but this framework is an
excellent sample of how reusable code is written.
The AWT model is elaborated with descriptions of its constituents and example
usage for Graphical User Interfaces in chapter 13. There are sufficient code examples
to build interfaces for most simple applications. We have also incorporated Swing
classes for better interactivity.
Applet development relate to graphical interfaces and the issue of dynamic
loading of compiled Java bytecodes. This is discussed in chapter 14. Situations where
applet behavior differs from Java applications, security measures and implementing a
loader over the network are also considered.
Chapter 15 covers Java Servlets. It is related to dynamic code loading and
applets in chapter 14, but occurring on the server side. This forms the basis for Java-
based Web applications.
Chapter 16 examines Java Object Serialization and Remote Method Invocation.
The former may be viewed as a continuation of input and output facilities discussed
Remote Method Invocation (RMI) for distributed applications. A simple client/server
application framework using RMI is provided.
Chapter 17 provides an overview of the popular requirement of working with
databases – Java Database Connectivity. This topic warrants a whole book, but we
limit our discussion to the rationale, perspective and architecture of JDBC together
with necessary methods for working with real databases.
xviii
Overview
in chapter 10, but with the focus to implement object persistence. Object Serialization
is also used to move objects over a network and forms a key role in implementing
In revising the text, we are thankful to readers of the first edition who have given
encouraging feedback. If not for these folks, we would never have considered this
second round.
We also thank our colleagues and bosses at our respective work places who
have supported and encouraged this book revision. We also thank the folks at
Springer Verlag who felt that a second edition was worthy.
Special thanks are due to Derek’s former colleagues at the now defunct Centre
for Internet Research (CIR), National University of Singapore, who had worked to
use the Internet productively. The lineage of CIR may be traced back to the Technet
Unit in the Computer Centre of the National University of Singapore, which was first
to provide and promote Internet services in Singapore. The effort saw the spin-off
to PacNet in Singapore. In particular, Dr. Thio Hoe Tong, former Director of the
Computer Centre and Dr Tan Tin Wee, have supported the Java team even in the
early days when we played with the Alpha releases of Java.
Poo, Kiong & Ashok
National University of Singapore
August 2007
Acknowledgement
1
Introduction
Object-oriented programming has been in practice for many years now. While the
fundamental object-oriented concepts were first introduced via the class construct in
the Simula programming language in the 1960s, the programming technique was
only accepted with the advent of Smalltalk-80 more than a decade later.
Object-oriented programming has come a long way. More and more programs
are now designed and developed using this approach. What is object-oriented pro-
gramming? What makes it attractive as an alternative programming approach? How
does it differ from the traditional procedural programming approach? These ques-
tions will be discussed in this chapter.
1.1 Object-Oriented Programming
The procedural approach to programming was the de facto approach in the early
days of programming. Here, code is modularized based on a system’s processes.
For instance, in developing a library application system, we would have considered
processes such as the checking in an d out of books, making reservations of books,
cataloging of books, and so on. Problem solving would involve the analysis of
these processes in terms of the procedural tasks carried out and the production of a
system whose representation is based on the procedural flow of the processes.
Object-oriented programming, on the other hand, models objects and their in-
teractions in the problem space and the production of a system based on these objects
and their interactions.
Since the real-world problem domain is characterized by objects and their in-
teractions, a software application developed using the object-oriented programming
approach will result in the production of a computer system that has a closer repre-
sentation of the real-world problem domain than would be the case if the procedural
programming approach is used.
2 Object-Oriented Programming and Java
1.2 Objects and Their Interactions in the Real World
Let us consider a real-world situation. There are two persons, Benjamin and his wife,
Bambie. They are customers of HomeCare, a company dealing in luxurious furni-
ture. HomeCare sells a variety of sofa sets. Each sofa set is labeled with an identifi-
cation number and a price tag. After viewing the sofa sets for an hour, Benjamin and
Bambie decide to purchase a green leather 5-seater set. They approach Sean, a sales-
person, to place their order.
In making his request known to Sean, Benjamin sends a message to Sean, “I
would like to purchase this green leather, 5-seater set. Can you please have it sent to
me by next Wednesday?”
The message that Benjamin has sent to Sean is a takeOrder message. It con-
tains information such as the type of sofa set (a green leather, 5-seater set) and the
date of delivery (next Wednesday). This information is known as the parameters of
the takeOrder message.
In response to Benjamin’s message, Sean replies to Benjamin by returning the
result of his request. We can represent the interaction between Benjamin and Sean
graphically using Figure 1-1.
takeOrder
result
Benjamin Sean
Figure 1-1: Interaction between Benjamin and Sean.
Sean was able to respond to Benjamin’s takeOrder message because he under-
stood it and had the means to handle Benjamin’s request. Although Sean knew how
to satisfy Benjamin’s request, Benjamin did not. In fact, most of the time, customers
do not know how a salesperson has satisfied their orders. All they get from salesper-
sons are replies such as, “I am sorry, madam, we are unable to satisfy your request
because the sofa you wanted has been sold,” or “Sir, your request has been satisfied.
We will deliver the goods on Wednesday between 10 am to 11 am to the address
indicated. Thank you for your order.”
Sean, as a salesperson at HomeCare, has a responsibility towards Benjamin. He
maintains his responsibility by applying a set of operations:
1. He determines if there is sufficient stock to satisfy Benjamin’s request.
2. He determines if the requested date for delivery is a suitable date.
3. He instructs the warehouse staff to deliver the goods to Benjamin’s address
on the requested date, if the above conditions are satisfied.
4. Finally, he informs Benjamin the result of his request.
Introduction 3
1.3 Objects and Their Interactions in Programming
The interactions between Benjamin and Sean in the above real-world situation can be
represented in object-oriented programming terms. For instance, Benjamin and Sean
are objects that interact by sending messages. Benjamin is thus a message-sending
object, while Sean is a message-receiving object. Alternatively, we can label
Benjamin as a sender and Sean as a receiver.
The takeOrder request from Benjamin to Sean is an example of a message. It
may have additional, accompanying information known as parameters (or argu-
ments) of the message. The fact that Sean responded to Benjamin’s message indi-
cates that the message is a valid message. Each valid message corresponds to a
method that Sean uses to fulfill his responsibility to Benjamin.
An invalid message, on the other hand, is one that the receiver does not have
the capability to respond to, that is, the receiver does not have a corresponding
method to match the message. For example, if Benjamin had requested a discount on
the price, his request would have been rejected because Sean, being a salesperson,
would not have the capability (or a corresponding method) to respond to the
message.
A method contains a number of operations detailing how Sean is to satisfy the
demand Benjamin put on Sean through the request.
Figure 1-2 summarizes the relationships of these terms.
Benjamin Sean
takeOrder(sofa type, who,
address, delivery date)
result
Message
Object
Object
Method
Arguments
Figure 1-2: Object interactions in object-oriented programming terms.
While Benjamin may know what Sean can do through his methods, he may not
know how Sean does them. This is an important principle of object-oriented pro-
gramming known as information hiding: the sender of a message does not know how
a receiver is going to satisfy the request in the message.
1.4 Simulation
Based on the above example, it is clear that concepts in object-oriented programming
such as object, message and method, do provide a close representation of real-world
objects and their interactions. These concepts are thus suitable for simulating actual
object interactions in real-world situations.
4 Object-Oriented Programming and Java
It is this ability for modeling real-world problems that identified object-oriented
programming as being suitable for simulation. The Simula programming language
was designed in the early 1970s to provide simulation abilities using object-oriented
concepts.
1.5 Java
Java was first introduced in 1995 as a simple and secure object-oriented program-
ming language. It is a unique language in that, being a new language at that time, it
was able to attract a lot of interest from the computing community. Within two years
after Java was launched, there were an estimated 400,000 Java programmers and
over 100 books on Java programming.
There are a few possible reasons for the phenomenal interest in Java. The year
1995 saw a maturing of Web technologies, and Java’s multiplatform capability,
which enabled a Java program to execute on any computer, was exceedingly attrac-
tive, especially on an open network like the Internet. Java is implemented via part
compilation and subsequent execution on an interpreter implemented in software.
Java applications are therefore object code portable as long as a Java virtual machine
is implemented for the target machine.
The popularity of Java is also ironically due to its similarity with its close rival
C++. Java takes the pain out of learning a new language by reusing much of C and
C++. At the same time, safe programming practice in Java and language facilities for
automatic memory management were benefits that were attractive to programmers
on the verge of deserting their C/C++ camps.
In relation to the Internet, Java applets have given rise to a new generation of
distributed applications with low software distribution and maintenance costs. As
applets are embedded in an HTML document via <APPLET> tags, its transmission to
the client machine for execution is implicitly handled by the underlying network
protocols and thus makes the typical channels of distribution and installation
obsolete.
While the object-oriented programming framework promotes reusability of
software and code, this very practice has been demonstrated in the rich set of class
libraries seen in the Java language. The Java foundation class libraries provide for
windowing and graphical user interface programming, network communications, and
multimedia facilities. Together, they demonstrate the practical and productive work
done in Java.
1.6 Summary
In this chapter, we discussed:
• An overview of object-oriented programming concepts and their applicabi-
lity for modeling and representing real-world entities and their interactions
in the problem-solving process.
Introduction 5
• Object-oriented concepts of object, message, and method.
• An overview of the Java programming language and the potential of produc-
tive software development
1.7 Exercises
1. Distinguish the programming approach used in procedural programming
and object-oriented programming.
2. Discuss the validity of the following statement: The object-oriented pro-
gramming approach is ideal for simulating real-world problems.
3. Consider the following scenarios and outline the objects and their interac-
tions in terms of messages and arguments:
(a) a driver driving a car;
(b) a customer making a cash withdrawal from an automated teller
machine (ATM);
(c) a customer buying a compact disk player from a vendor;
(d) a traffic policeman directing traffic at a junction;
(e) a lecturer delivering his/her lecture to a class of students;
(f) a tutorial discussion between an instructor and students.
2
Object, Class, Message and Method
We had our first introduction to objects, message and method in Chapter 1. Another
concept closely associated with the concept of objects is class. In object-oriented
programming, a class is a definition template for structuring and creating objects.
In this chapter, we will discuss the concept of object, message, method and
class and how these concepts are used in a computer model.
2.1 Objects and Class
In Chapter 1, we introduced Benjamin. Now, meet Bernie, another customer at
HomeCare. As customers of HomeCare, Benjamin and Bernie share some similar
information. For example, both have a name, an address, and a budget—information
that is relevant when describing customers. This information is known as object
attributes.
An object attribute definition allows for objects to have independent attribute
values. For example, Benjamin may have a larger budget and thus a larger budget
value (say $2000) than Bernie whose budget may be $1000. Collectively, the values
of an object’s attributes represent the state of the object.
Besides attributes, Benjamin and Bernie also exhibit some behavior typical of a
customer. For instance, Benjamin and Bernie execute a method when making a
purchase. Let us call this method purchase(). The method purchase() is made up
of a set of operations that Benjamin and Bernie would use to send a purchase request
to a salesperson.
Structurally, Benjamin and Bernie can be represented as follows:
8 Object-Oriented Programming and Java
name, address and budget are attributes while purchase() and getBudget()
are methods of the two objects. Note that both objects share a common definition of
attributes and methods. In fact, all customers of HomeCare share the same set of
attribute and method definitions. They all have attributes name, address and budget,
and methods purchase() and getBudget(). In defining these objects, a common
definition known as class is used.
A class is a definition template for structuring and creating objects with the
same attributes and methods. Benjamin and Bernie, being customers of HomeCare,
can therefore be defined by a class called Customer as follows:
One major difference between objects and class is in the way attributes and
methods are treated in objects and classes. A class is a definition about objects; the
attributes and methods in a class are thus declarations that do not contain values.
However, objects are created instances of a class. Each has its own attributes and
methods. The values of the set of attributes describe the state of the objects.
Let us now examine the salespersons. Salespersons also have attributes and
methods. Sean and Sara are two salespersons at HomeCare. They are thus capable of
a behavior typical of a salesperson, for example, taking orders from customers. To
fulfill their role as salespersons in a purchase transaction, Sean and Sara perform a
method. We shall call this method takeOrder(), and represent Sean and Sara as
follows:
Benjamin as an Object
Attributes:
name = Benjamin
address = 1, Robinson Road
budget = 2000
Methods:
purchase() {send a purchase request to a salesperson}
getBudget() {return budget}
Bernie as an Object
Attributes:
name = Bernie
budget = 1000
Methods:
purchase() {send a purchase request to a salesperson}
getBudget() {return budget}
Class Customer
Attributes:
name
address
budget
Methods:
purchase() {send a purchase request to a salesperson}
getBudget() {return budget}
address = 18, Sophia Road"
"
"
"
"
" "
"
"
"
" "
Object, Class, Message and Method 9
Being salespersons, Sean and Sara share similar attributes and methods as
expected. Like the customers, their definition can be described by a class called
SalesPerson with the following representation:
Note that the definition of the SalesPerson class is different from the Customer
class since customers and salespersons behave differently—customers make orders
and salespersons take orders.
2.2 Message and Method
Objects communicate with one another by sending messages. A message is a method
call from a message-sending object to a message-receiving object. A message-
sending object is a sender while a message-receiving object is a receiver.
Sean as an Object
Attributes:
name = Sean
Methods:
takeOrder() {
check with warehouse on stock availability
check with warehouse on delivery schedule
if ok
then {instruct warehouse to deliver stock(address, date)
return ok}
else return not ok
}
Sara as an Object
Attributes:
name = Sara
Methods:
takeOrder() {
check with warehouse on stock availability
check with warehouse on delivery schedule
if ok
then {instruct warehouse to deliver stock(address, date)
return ok}
else return not ok
}
Class SalesPerson
Attributes:
name
Methods:
takeOrder() {
check with warehouse on stock availability
check with warehouse on delivery schedule
if ok
then {instruct warehouse to deliver stock(address, date)
return ok}
else return not ok
}
"
"
"
"
10 Object-Oriented Programming and Java
An object responds to a message by executing one of its methods. Additional
information, known as arguments, may accompany a method call. Such para-
meterization allows for added flexibility in message passing. The set of methods
collectively defines the dynamic behavior of an object. An object may have as many
methods as required.
2.2.1 Message Components
A message is composed of three components:
• an object identifier that indicates the message receiver,
• a method name (corresponding to a method of the receiver), and
• arguments (additional information required for the execution of the method).
Earlier we saw that Benjamin sent a message to Sean when Benjamin wanted to
buy a sofa set. The reasonable location for Benjamin to send the message to Sean is
in Benjamin’s purchase() method as shown below (indicated in bold):
The message Sean.takeOrder(who, stock, address, date) is interpreted as
follows:
• Sean is the receiver of the message;
• takeOrder is a method call on Sean;
2.2.2 Method
A message is valid if the receiver has a method that corresponds to the method
named in the message and the appropriate arguments, if any, are supplied with the
message. Only valid messages are executed by the receiver. The takeOrder()
message is valid because Sean has a corresponding method and the required
arguments (who, stock, address, date) are supplied with the message.
Sean’s takeOrder() method is made up of a set of operations (indicated in
bold below) as follows:
Benjamin as an Object
Attributes:
name = Benjamin
address = 1, Robinson Road
budget = 2000
Methods:
purchase() {
}
getBudget() {return budget}
"
"
" "
" "
• "Benjamin","stock","address","date" are arguments of the message.
Sean.takeOrder("Benjamin", "sofa", "1, Robinson Road",
"12 November")
Object, Class, Message and Method 11
In the above description, a message is sent from Sean to a Warehouse object to
inquire on the order and delivery schedule in Sean’s takeOrder() method. If both
conditions are satisfied, Sean will instruct the Warehouse object to arrange for
delivery.
How Sean carries out the method is known only to Sean. Neither Benjamin nor
the other customers know how Sean does it. For example, to check on the stock and
delivery schedule with the warehouse, Sean may have called the warehouse over the
phone or he may have checked the information against a list he had gotten from the
warehouse. What Benjamin knows of Sean is that Sean is capable of responding to
his request since his message to Sean is acceptable by Sean.
In object-oriented programming, Benjamin and Sean are said to have followed
the principle of information hiding—How Sean is going to satisfy Benjamin’s request
is hidden from Benjamin. In this way, Sean is free to select whatever way he chooses
to satisfy Benjamin’s request; he may phone the warehouse or look up the pre-
prepared list and vice versa.
2.2.3 Client and Server
By executing a method, a message-receiving object (such as Sean) is said to serve
the message-sending object (such as Benjamin). A message-receiving object is thus a
server to a message-sending object and the message-sending object is thus a client of
the server.
takeOrder
result
Benjamin Sean
yes/no
available?
send
ok
Figure 2-1: Object communication process.
In any object communication, there are at least a client and a server. The client
sends a message to request a server to perform a task. The task is fulfilled by a
Sean as an Object
Methods:
takeOrder(who,stock,address,date) {
check with warehouse on stock availability
check with warehouse on delivery schedule
if ok then {
instruct warehouse to deliver stock to address on date
} else return not ok
}
Attributes:
name = Sean
" "
return ok
12 Object-Oriented Programming and Java
message-corresponding method of the server. In sending a message to the ware-
house, Sean is said to be the client and the warehouse is said to be the server.
Benjamin, Sean, and the warehouse are three objects involved in a communi-
cation process. Benjamin is the initiator, with Sean and the warehouse as partners in
the communication process. Figure 2-1 depicts a typical communication process
amongst objects.
2.3 Creating Objects
In object-oriented programming, objects are created from classes. Instances of
Customer objects are created from a Customer class and SalesPerson objects from a
SalesPerson class.
Created object instances are individuals with their own state. To illustrate, let
us consider the example of counters. A counter is a device that keeps account of the
number of times an event has occurred. It has two buttons: an initialize button that
resets the counter to 0, and an add button that adds 1 to its present number. Figure 2-2
shows a counter with a number 10.
initialize add
10
Figure 2-2: A counter.
Structurally, the first counter object can be represented as follows:
Figure 2-3 shows two more counters.
initialize add
2
add
7
initialize
Figure 2-3: Two Additional Counters
Like the first counter, these two counters may be reset to zero and incremented
through the initialize and add buttons respectively, and represented as follows:
First Counter Object
Attributes:
number = 10
Methods:
add() {number = number + 1}
initialize() {number = 0}
getNumber() {return number}
Object, Class, Message and Method 13
All the three counters share the same definition of attributes and methods, and
like in the previous examples, they can be defined by a class as follows:
The Counter class has:
• an attribute, number;
• an initialize() method that causes a counter to reset its number to 0.
• an add() method that causes a counter to add 1 to its number; and
• a getNumber() method that returns the current value of the attribute
number.
Suppose a new object is created from the Counter class. Although the new
Counter object would have the same definition of attributes and methods as the
previous three counters, its attribute value may not be the same as the other counters.
This suggests that the state of the counters may be different from one another.
For the newly created fourth Counter object, it has a state represented by the
attribute number with a value of 0, the value at initialization:
Second Counter Object
Attributes:
number = 2
Methods:
add() {number = number + 1}
initialize() {number = 0}
getNumber() {return number}
Third Counter Object
Attributes:
number = 7
Methods:
add() {number = number + 1}
initialize() {number = 0}
getNumber() {return number}
Class Counter
Attributes:
number
Methods:
add() {number = number + 1}
initialize() {number = 0}
getNumber() {return number}
Fourth Counter Object
Attributes:
number = 0
Methods:
add() {number = number + 1}
initialize() {number = 0}
getNumber() {return number}
14 Object-Oriented Programming and Java
Note that the attribute value of the fourth Counter object is different from the
other three counters.
2.4 Summary
In this chapter, we discussed:
• Objects are defined by classes.
• Objects from the same class share the same definition of attributes and
methods.
• Objects from the same class may not have the same attribute values.
• Objects from different classes do not share the same definition of attributes
or methods.
• Objects created from the same class share the same definition of attributes
and methods but their state may differ.
• A method is a set of operations executed by an object upon the receipt of a
message.
• A message has three components: an object identifier, a method name and
arguments.
• A message-receiving object is a server to a message-sending object known
as a client.
2.5 Exercises
1. Distinguish the terms “Object” and “Class”.
2. Consider the scenario of buying flowers from a florist. Outline the
objects in such a transaction together with the messages exchanged.
3. Given a class definition Rectangle below, describe the structure of
any 3 instances of Rectangle.
4. How would you implement the concept of class and method in a
non-object-oriented programming language such as COBOL,
Pascal or C?
5. Define using the following structure a class definition for cars. A
car generally has abilities to start, move forward, move backward,
class Rectangle {
Attributes:
length
width
Methods:
getLength() { return length }
getWidth() { return width }
draw() { ... }
}
Object, Class, Message and Method 15
stop and off. A car can also return to its relative location. The
starting location is a value 0.
6. Distinguish between a client and a server.
7. A client communicates with a server by sending a ___________ to
the server. The ___________ is a call on a ___________ of the
server.
class Car {
Attributes:
...
Methods:
...
}
3
A Quick Tour of Java
Earlier, we introduced key object-oriented concepts such as objects, methods and
classes and how these may be ultimately used in a computer model. In this chapter,
we see how the Java programming language is used to construct our object model of
the problem domain. This approach is advantageous in that it allows our model to
operate or “come alive” under computer control.
3.1 Primitive Types
The Java programming language allows the creation of objects that will ultimately
participate in message communication. We have seen that objects may have diverse
behavior and that it is more convenient to specify objects via classification, that is,
class constructs.
Before examining class definitions for user-specified objects, we should be
mindful that Java also provides primitive values from which other (bigger) objects
may be described in terms of and constructed from. For example, a complex number
may be seen as being comprised of two numbers representing the real and imaginary
parts.
The primitive types byte, short, int and long defined in the Java language
allow for the representation of discrete integer values of widths 8, 16, 32, and 64
bits, respectively. These in turn correspond to the representation of numeric
The primitive types float and double allow for the representation of single
and double precision floating-point real values with representational widths of 32
and 64 bits, respectively. The adopted IEEE 754 standard includes both positive and
negative sign-magnitude numbers, both positive and negative zeros and infinities,
and unique not-a-number representations.
ranges –128 to 127, –32768 to 32767, –2147483648 to 2147483647, and
–9223372036854775808 to 9223372036854775807, respectively.
18 Object-Oriented Programming and Java
Values of type float are of the form s·m·2e
, where s is either +1 or –1, m is a
positive integer less than 224
, and e is an integer between –149 and 104. Similarly,
values of type double have the similar form s·m·2e
, but m is a positive integer less
than 253
, and e is an integer between –1075 and 970.
Finally, the primitive types char and boolean allow for 16-bit multi-byte
characters and false/true boolean values, respectively.
3.2 Object Definition
Building upon the primitive values supported by the language proper, other entities
to be manipulated are user-designed objects which are defined via class constructs. A
class construct in Java consists of the class keyword followed by the class name
and braces { } which delimit the declaration of attributes and methods for its in-
stances. The Counter class introduced in Chapter 2 would have the following form
in Java:
Object attributes are, in turn, either nested component objects or primitive types
used to represent the object. An instance method manipulates the object by altering
its attribute values. The number attribute and add() method in the Counter class
below are representative of an object’s state and operation, respectively:
The number attribute is also known as an instance variable because it occurs in
every object or instance of the Counter class. This further implies that an attribute in
one instance is independent from that in another instance. In the same vein, a method
manipulates object attributes in the same instance. This occurs when a method is
invoked and the corresponding code in its body is executed. In our recent example,
invoking the add() method of an object will increment the corresponding number
attribute.
3.2.1 Variable Definitions
Variable definitions in Java take the form below, where the type name T precedes the
variable name v:
T v;
class Counter {
attribute and method declarations
}
class Counter {
int number;
void add() {
number = number +1;
}
}
A Quick Tour of Java 19
Typing in a programming language allows the values for a variable to be
anticipated. As such, appropriate storage may be set aside for these values.
There is another subtle advantage of typing in programming languages: the val-
ues associated with the variable also imply what operations are valid and applicable.
For example, multiplication and division applies to numeric values but not to charac-
ter values. Thus, the language compiler may flag multiplication and division of char-
acter values as erroneous.
All variables in Java are typed, allowing the compiler to verify during compila-
tion that operations on the object associated with the variable are legitimate.
3.2.2 Methods
A method definition that occurs in a class construct is made up of two distinct por-
tions: the method signature header and its implementation code body surrounded by
the braces { ... }.
The method signature portion, such as void add() in the Counter example, has
the generic form below, where m is the method name, T its return type, with Rn and
pn being parameter types and names, respectively (n being the number of parame-
ters):
T m(R1 p1, R2 p2, ... Rn pn)
We have seen that a method named m() is invoked to correspond to a message
m sent to the object. Consequently, the object may return a result to the message
sender. The type of this value is denoted by T. If no result needs be returned, the
keyword void is used instead.
The formal parameters p1, p2…pn contain the additional values sent together
with the message. They have corresponding types R1, R2…Rn, and are used by the
compiler to verify that the correct parameters are supplied for each method invoca-
tion. Any number of formal parameters may be specified, but the number of actual
parameters in a message must match those originally specified in the method signa-
ture.
The implementation of a method consists of a block of statements surrounded
by { }. Often, such methods would modify the object’s attributes. In the case of the
add() method of our Counter example, it increments the variable number. A block
consists of declarations of any local variable, expressions and control-flow con-
structs. These will be discussed in detail in following sections.
class Counter {
int number;
void add() {
number = number+1;
}
IntheslightlyexpandedversionoftheCounterclassbelow,anextrainitialize()
method has been added to re-initialize the Counter value so that counting can be
easily restarted. This allows instances to respond to the additional initialize message.
20 Object-Oriented Programming and Java
If the number of times a counter is restarted is significant, we can introduce
another attribute reused to maintain this information. Correspondingly, this attribute
is incremented in the block of the initialize() method:
The previous example of the class Counter definition shows that an object may
have as many attributes and methods as required to effectively model the object. In
the most recent definition, objects of the class Counter have two attributes (number
and reused, both with an initial value of 0 when created) and two methods (add()
and initialize()).
3.3 Object Instantiation
except by calling the object allocator function new(). The expression new Counter()
returns a newly created instance of the Counter class. However, in order that this
new object may be referred to, it is assigned to an appropriate variable. Assuming the
variable carpark in the fragment below, a new Counter object may be created via
new Counter(), and then assigned to the former:
Counter carpark;
...
carpark = new Counter();
Henceforth, the newly created object may be referred to via the variable
carpark. Where more Counter objects are needed, the object allocator function
new() may be repeatedly invoked, and the resultant objects assigned to other vari-
ables such as entrance and exitDoor:
Counter entrance, exitDoor;
...
entrance = new Counter();
exitDoor = new Counter();
class Counter {
int number = 0;
int reused = 0;
void add(){
number = number+1;
}
void initialize(){
number = 0;
reused = reused+1;
}
}
void initialize() {
number = 0;
}
}
template for objects to be created. However, no instances of the class is crested,
A class construct provides a description for objects of that class, and serves as a
A Quick Tour of Java 21
3.4 Object Access and Message Passing
Since the attributes and methods of an object are considered its characteristics, these
are accessed via the qualification operator “.” with respect to an object proper. Thus,
the counts of the various Counters carpark, entrance and exitDoor are
carpark.number, entrance.number and exitDoor.number, respectively. The
total number from these counters is:
carpark.number + entrance.number + exitDoor.number
Similarly, the initialize() method of Counters carpark, entrance and
exitDoor may be invoked via:
carpark.initialize();
entrance.initialize();
exitDoor.initialize();
3.5 Representational Independence
While accessing object attributes directly is permissible, it is not ideal because it
couples implementation code to the current object representation. As such, any
changes in object representation propagates to dependent code, resulting in high
software maintenance cost.
A common object-oriented programming practice is information hiding—to
make object representations inaccessible to clients so that modifications in (server)
object representations do not propagate excessively. This decoupling of dependen-
cies reduces software maintenance cost.
Limiting access to object representations in Java is mainly achieved by the two
main constraint specifiers private and public. The former limits access of the
following entity to within the class construct, while the latter makes it accessible to
any client code.
Since constraint specifiers in the above class definition hides the internal repre-
sentation of Counter objects, the resultant attributes are no longer accessible, and
useless for interrogation. In this case, accessor methods getNumber() and
getReused() are required, as outlined in the following code fragment. They provide
class Counter {
private int number = 0;
private int reused = 0;
public void add() {
number = number+1;
}
public void initialize() {
number = 0;
reused = reused+1;
}
}
22 Object-Oriented Programming and Java
access to internal details, but without dependency overheads. Representation inde-
pendence is maintained by confining access to private attributes to within the class
construct. This topic is further discussed in Chapter 8.
3.6 Overloading
Attribute names of a class may be the same as those in another class since they are
accessed independently. An attribute x in a class does not necessarily have any se-
mantic bearing with another as they have different scopes, and does not preclude
using the same attribute there.
Within a Java class construct, methods may share the same name as long as
they may be distinguished either by:
• the number of parameters, or
• different parameter types.
This criterion requires a message with associated parameters to be uniquely
matched with the intended method definition.
If we had wanted a Counter to be incremented other than by 1, we could define
another add() method that takes an integer parameter instead:
class Counter {
private int number = 0;
private int reused = 0;
public void add() {
number = number+1;
}
public void initialize() {
number = 0;
reused = reused+1;
}
public int getNumber() { return number; }
public int getReused() { return reused; }
}
class Counter {
private int number = 0;
private int reused = 0;
public void add() {
number = number+1;
}
public void add(int x) {
number = number+x;
}
public void initialize() {
number = 0;
reused = reused+1;
}
public int getNumber() { return number; }
public int getReused() { return reused; }
}
A Quick Tour of Java 23
If carpark had been assigned an instance of Counter, carpark.add() would
invoke the first method to increment by 1, while carpark.add(2) would invoke the
new one just defined.
3.7 Initialization and Constructors
Currently, object creation and initialization are seen as distinct operations. The
abstraction in object-oriented programming languages often allows these two opera-
tions to be combined implicitly. As such, constructors may be seen as unique
methods invoked implicitly when an object instance is created. Implicit initialization
relieves the programmer from performing this important function, but more impor-
tantly prevents uninitialized objects as a result of absent-minded programmers. Care-
fully designed constructors allow for object invariants to be maintained regardless of
how they were created.
Apart from having the same name as the class, and not having a return result
type, a constructor is not different from a method. It has similar syntax for its
parameters and implementation body.
In place of attribute initialization, our next Counter example uses a constructor
method. This offers additional functionality compared with the former approach.
While this change is not significant in our trivial example, constructors allow
more flexibility such as the execution of arbitrary expressions and statements when
compared with static attribute initializers. As with methods, constructors may also be
overloaded. This provides for varied ways for objects to be created and initialized.
The additional new overloaded constructors in the new class definition below
allows for various initial values for number and reused other than just 0:
class Counter {
private int number, reused;
public void add() {
number = number+1;
}
public void initialize() {
number = 0;
reused = reused+1;
}
public int getNumber() { return number; }
public int getReused() { return reused; }
Counter() { number = 0; reused = 0; }
}
class Counter {
private int number, reused;
public void add() {
number = number+1;
}
public void initialize() {
number = 0;
reused = reused+1;
}
24 Object-Oriented Programming and Java
3.8 Expressions, Statements, and Control-flow Mechanisms
We saw earlier that a method definition consists of the method signature and its
implementation body. As an object responds to messages by executing code in the
method body to affect changes in its state, assignment is a very common operation.
v = E;
Assignment consists of a left-hand variable that will contains or “holds” the
value specified via the right-hand expression. It may be a literal value such as 3, a
variable that holds the intended value such as number, or an operator with appropri-
ate operands, such as x+4, or even r.f or y*p(5). In the same way that + is an opera-
tor, . and () are also operators. The last expression involves nested expressions: the
result of p(5) is used in multiplication.
3.8.1 Operators
We first examine the operators in Java.
(a) Arithmetic Operators
The arithmetic operators in Java include the common addition “+”, subtraction
“-”, multiplication “*” and division “/” operations.
int a = 13;
int v = 7;
a+v // returns result 20
a-v // returns result 6
a*v // returns result 91
a/v // returns result 1
These operators apply to numeric operands, and return the type of operands.
When operands are mixed, the widest is used to prevent unexpected truncation.
float b = 13;
int w = 7;
b+w // returns result 20.0
b-w // returns result 6.0
public int getNumber() { return number; }
public int getReused() { return reused; }
Counter() { number = 0; reused = 0; }
Counter(int x) { number = x; reused = 0; }
Counter(int x, int y) { number = x; reused = y; }
Counter(float z) { number = (int) z; reused = 0; }
}
A Quick Tour of Java 25
b*w // returns result 91.0
b/w // returns result 1.8571428
The “%” operator returns the remainder of integer division.
int a = 13;
int v = 3;
a/v // returns result 4
a%v // returns result 1
When used as a unary operator, “-” negates the numeric operand.
int a = 13;
-a // returns result -13
(b) Logical Operators
The logical operators in Java include the standard and “&&”, or “||” and not
“!”. Each operator returns a boolean result:
&& returns true if both operands are true.
x y x && y
false false false
false true false
true false false
true true true
|| returns true if at least one operand is true.
x y x || y
false false false
false true true
true false true
true true true
! returns true if the single operand is false.
x ! x
false true
true false
26 Object-Oriented Programming and Java
(c) Relational Operators
The equality “==” and inequality “!=” operators in Java operate on all values
and objects to return a boolean result.
The following relational operators in Java operate on numeric values.
< less than
> greater than
<= less than or equal
>= greater than or equal
(d) Bitwise Operators
The following bitwise operators in Java operate on corresponding bits of byte,
short, int and long values.
& bitwise “and”
^ bitwise exclusive “or”
| bitwise inclusive “or”
~ bitwise one’s complement
int h = 4;
int j = 4;
int k = 6;
Counter m = new Counter();
Counter n = new Counter();
h == j // returns true, h and j have the same value
h == k // returns false
k == k // returns true
m == n // false, m and n are different objects even if they have the
// same constituents
n == n // true
int h = 4;
int j = 4;
int k = 6;
h < k // returns true
h < j // returns false
h <= j // returns true
>> << right and left bitwise shift
>>> right bitwise unsigned shift
A Quick Tour of Java 27
(e) Assignment
Having seen the basic means of providing new values to variables, assignment
“=” is more correctly viewed as an operator rather than a statement. In addition to
assigning the right-side value to the left-side variable, it also returns the value
assigned. As such, the assignment expression may appear in the context of an enclos-
ing expression. (In the example below, the result of the assignment operator to vari-
able a is not used.)
int a, b;
a = b = 2;
int a, b;
a = (b = 2);
The code fragments above assign 2 to b and the result of 2 is assigned to a. This
is because unlike the common arithmetic operators which associates from left-to-
right, the assignment operator associates from right-to-left. This is highlighted in the
next section on operator precedence.
In general, an assignment operator results in a side-effect since it changes the
value of the variable being assigned. Other related assignment operators have the
special form “op=”, where op is a typical operator.
x op= f; x = x op f;
implies
has the same meaning as
int a = 15; // binary 000001111
int v = 34; // binary 000100010
a & v // returns result 2 000000010
a ^ v // returns result 45 000101101
a | v // returns result 47 000101111
~a // returns result -16
// 11111111111111111111111111110000
v >> 3 // returns result 4 000000100
v << 3 // returns result 272 100010000
~a >> 3 // returns -2
// 11111111111111111111111111111110
~a >>> 3 // returns 536870910
// 01111111111111111111111111111110
28 Object-Oriented Programming and Java
In the above equivalent form, op may be operators such as +, -, *, /, %, >>, <<,
&, ^ or |. Thus +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, and |= are also valid assign-
ment operators.1
The other two operators related to assignment are auto-increment “++” and
auto-decrement “––”. Since they are used in either postfix and prefix forms, four
scenarios are as illustrated in the code fragments below.
The postfix form (such as f++) returns the result before the incre-
ment/decrement operation, whereas the prefix form (such as ++f) returns the results
after the increment/decrement operation. In the code fragments below, f is either
incremented or decremented. However, g is either assigned a “pre” or a “post” value
depending on whether the prefix or postfix forms are used, respctively.
int f, g;
f = 6;
g = f++;
// g has 6
// f has 7
int f, g;
f = 6;
g = ++f;
// g has 7
// f has 7
int f, g;
f = 6;
g = f--;
// g has 6
// f has 5
int f, g;
f = 6;
g = --f;
// g has 5
// f has 5
(f) Conditional Expression
The conditional expression operator ? : returns one of two values depending
on the boolean condition. For example, the expression A?B:C returns the value of B
if A is true, else the value of C is returned.
(g) Typecast
The typecast operator (type)E performs 2 basic functions at run-time depend-
ing on the source expression E. For a numeric type (such as int, float, or double),
it converts the value to another of the specified type.
1
There is a subtle difference between x[i++] += 4 and x[i++] = x[i++] + 4, in that i++
is evaluated once in the former but twice in the latter.
A Quick Tour of Java 29
int k = 5;
double d = 4.16;
k = (int) d*k;
The resultant expression of d*k is double value, and the typecast operation
converts it to an integer. For variable, the operator confirms that the object refer-
enced is compatible with the specified class.
(h) Precedence and Associativity
Since most operators have operands that can be (nested) expressions, operator
precedence and associativity rules are necessary to define the evaluation order. For
example in evaluating “a+b*c”, “b*c” is evaluated before its result is added to a
because multiplication “*” has higher precedence than addition “+”.
The operators at the top of the table have higher precedence than those at the
bottom. It is as though precedence pulls operands, so that operators with a higher
precedence are evaluated before those with lower precedence. All binary operations
are left-associative, except assignment operators which associate right-to-left.
Table 3-1: Operator precedence.
Operator
[] . (params) E++ E--
unary operators: -E !E ~E ++E --E
new (type)E
* / %
+ -
>> << >>>
< > <= >=
== !=
&
^
|
&&
||
? :
= += -= *= /= %= >>= <<= &= ^= |=
Object x = new Counter();
Counter c;
c = x; //illegalsincenotallObjectsareCounters
c = (Counter) x; //legitimatebecausexisatrun-time
// verifiedtoreferenceaCounter
Table 3.1 summarizes the operators discussed so far.
30 Object-Oriented Programming and Java
Precedence allows the expression “a>>b+c” to be unambiguously interpreted as
“a>>(b+c)”, and not “(a>>b)+c”. Similarly, “!m&&n” is interpreted as “(!m)&&n”
and not “!(m&&n)”.
Associativity rules come into effect when equal precedence levels do not help
in resolving evaluation order. Due to associativity rules (which is left-to-right for “/”
and “*”, that is, evaluating the left operator and then right), “a/b*c” is interpreted as
“(a/b)*c” and not “a/(b*c)”.
Similarly, due to right-to-left associativity, “~y++” is interpreted as “~(y++)”
instead of “(~y)++”.
3.8.2 Expression Statements
The simplest and most common statements in Java are expression statements, which
consist of an assignment expression, method invocation or instance creation followed
by a semicolon. The following are expression statements:
3.8.3 Control-flow Statements
Apart from the simple statements, there are control-flow statements that affect the
execution order of statements. These statements are commonly grouped under condi-
tional and iterative statements.
(a) Conditional Statements
Conditional statements allow for conditions to be attached to a statement as to
whether it will be executed. The most basic form is the if statement. In the code
fragment below, the statement S is executed only if the boolean condition E evalu-
ates to true:
A slight variation is the if-else statement which allows for an either-or
choice. If the boolean condition E evaluates to is true and S is executed, then R
would not. If S is not executed, then R would be:
int a, b;
T c;
a = 1; // assignment expressions
a++;
c = new T();
new T(); // instance creation
c.m(); // method invocation
if (E)
S;
A Quick Tour of Java 31
Apart from one-way and two-way branches in flow-control, the switch state-
ment allows for multi-way selection:
Generally, the switch statement allows for the execution of a choice of state-
ments depending on the expression E: S1 when E evaluates to the constant c1, S2
when c2, …, etc., the mappings given by each switch limb. The break statement
causes flow-control to leave the switch statement immediately.
In the case of the execution of statement S3 when E evaluates to c3, the absence
of a break statement causes execution to continue to S4 instead. The default limb
is used when the evaluated value of E does not match any constant values in the
limbs.
(b) Iterative Statements
Iterative statements allow for constituent statements to be executed repeatedly.
In the most basic way, the body of the while-statement below is repeatedly executed
when the boolean condition E is true. The loop terminates when E is false, after
which execution proceeds to the next statement:
The while-statement is known as a pretest loop since the constituent S is only
executed if the condition E evaluates to is true. Thus, if E was false in the first
instance, the statement S is never executed.
On the other hand, the do-while statement is a posttest loop. R is first executed
and subsequently while the boolean expression F evaluates to true, R is executed
again. Again, the loop terminates when F evaluates to false. Thus, this control flow
construct will execute R at least once.
if (E)
S;
else
R;
switch (E) {
c1: S1;
break;
c2: S2;
break;
c3: S3;
c4: S4;
break;
default: Sd;
}
while (E)
S;
do {
R;
} while (F);
32 Object-Oriented Programming and Java
3.9 Blocks
A block, indicated by { }, may occur at any location where a statement is valid. It is
considered the sequential construct as the group of statements it surrounds is treated
as a single statement or processing unit.
Thus, while the various control-flow constructs merely show a single statement
as the constituent body, a block may be used where such constructs should contain
more than one statement. For example, factorial may be computed by the following
while-statement:
Blocks allow for control-flow constructs to be nested within bigger constructs.
In the code fragment below, the nested if-else statement allows for the number of
even numbers and sum of odd numbers in the range to be computed.
3.9.1 Local Declarations
In treating a statement sequence as a single statement, a block may also be thought of
as a sub-machine which fulfills a specific task. As such, the scope of local variable
declarations is the rest of the block in which the declaration occurs. This allows
declarations and associated references to be localized, thereby aiding maintainability.
f = 1;
while (k > 1) {
f = f*k;
k--;
}
even = 0; sumOfOdd = 0;
f = 1;
while (k > 1) {
f = f*k;
if (k % 2 == 0)
even++;
else
sumOfOdd = sumOfOdd + k;
k--;
}
while (k > 1) {
f = f*k;
if (k % 2 == 0) {
double d = 4.5;
....
even++;
} else {
long d = 23546;
...
sumOfOdd = sumOfOdd + k;
}
k--;
}
A Quick Tour of Java 33
The code fragment above is legitimate because both local declarations of d
have been confined to their respective nested blocks – d is a double in the first block,
while d is a long in the second.
With instance variables, a local declaration has the same form below, where T
is the declared type of variable v.
T v;
For notational convenience, declarations may have two variations:
• a list of variables with the same type separated by commas; and
• an initial value may be provided via an expression following an
assignment operator
T v, w = n(), z;
3.10 More Control-flow Statements
Three other control-flow statements are commonly used: for-statement, break and
continue. The for-statement is often used as a counter-controlled loop to iterate
through a loop a fixed number of times, even though it does not have explicit
mechanisms for counter control. For example, the earlier factorial example could be
re-coded as follows:
The generic form of the for-statement
is often easier thought of as a transformed while-statement, where Q, T, and S are
the initializer, conditional and re-initializer expressions:
The break-statement was encountered when the switch-statement was dis-
cussed. Its more generic function is to transfer control out of the innermost switch,
while, do or for-statement. This is why using the break-statement ensures that only
the statements associated with the case-limb are executed.
for (f = 1; k > 1; k--)
f = f*k;
for (Q; R; S)
T;
Q;
while (R) {
T;
S;
}
34 Object-Oriented Programming and Java
For the situation with the while, do or for-statements, the break-statement
allows for a quick exit from the iteration. In many situations, its use can result in a
simpler program structure. For example, the following two code fragments have
similar effects.
Finally, the continue-statement transfers control to the beginning of the inner-
most iterative loop so as to reevaluate the boolean condition for the next iteration.
Unlike, the break-statement, control-flow does not exit from the loop. As such, the
following two code fragments have similar effects.
While the differences between program structures in the above examples may
seem mild for the break and continue statements to be useful, it is more pro-
nounced for program structures that are deeply nested.
3.11 Arrays
Just as objects are created dynamically (i.e., it happens at run-time during program
execution), arrays in Java are similarly created. The size of an array need not be
specified or computed during compilation.
An array is thus declared using the subscript operator, but without indication of
the upper bound:
Counter gates[];
An array is created via the new operator, but with the array size within square
brackets:
finished = false;
while (E && !finished) {
S;
if (F) {
U;
finished = true;
}
if (!finished)
T;
}
while (E) {
S;
if (F) {
U;
break;
}
T;
}
while (E) {
S;
if (F) {
U;
continue;
}
T;
}
skip = false;
while (E) {
S;
if (F) {
U;
skip = true;
}
if (!skip)
T;
else
skip = false;
}
A Quick Tour of Java 35
gates = new Counter[8];
The array size associated with gates is 8, but this does not imply eight Counter
objects. Instead, it is important to understand a Counter array as being similar with
multiple variables, that is, it is an object that does not further contain Counter objects
but merely references eight potential Counter objects.
Thus, individual array elements must be created explicitly:
3.12 Result Returned by Method
Now that we have examined the statement constructs in Java, we return to see how a
method may return a result to its sender. A method in a class definition has the fol-
lowing general form, with the return-statement returning control-flow back to the
message sender:
The value returned v, must be of the type T as indicated in the method signa-
ture. If the sender does not require any results, the keyword void should be used as
the return type. In this case, the returning expression v would be omitted in the
return statement. The return-statement need not be the last statement in the block
as implied in the previous example. In a non-trivial structure, multiple return-
statements might be used as in the next example, but the programmer must evaluate
if the situation improves program structure and readability.
Counter gates[];
gates = new Counter[8];
for (int i=0; i<8; i++);
gates[i] = new Counter();
T foo(gT g, hT h ...)
{
// local definitions
// statements
return v;
}
T foo(gT g, hT h ...)
{
for (E; F; G)
if (H)
return v;
else if (J) {
b;
return w;
}
return x;
}
36 Object-Oriented Programming and Java
3.13 Summary
In this chapter, we discussed:
• Primitive types in Java.
• class constructs.
• Definition of instance variables and methods.
• Object instantiation.
• Message passing and expressions.
• Statements and control-flow mechanisms.
Generally, these constructs are representative of what Java offers. The class
construct is key in Java because it allows for objects to be defined to model the prob-
lem domain. Below that, variables and methods are defined, which correspond to
data and code. Code abstraction result in hierarchical statement blocks (with optional
local variables) and control flow mechanisms. Figure 3-1 illustrates this hierarchy.
Java application
primitive values objects
class definitions
consists of
defined by
instance variables instance methods
consists of
local variables statements
assignment control flow
message
passing
Figure 3-1: Hierarchical relationships of Java constructs.
3.14 Exercises
1. Which of the following are valid variable names in Java?
_object
object–oriented
A Quick Tour of Java 37
object_oriented
object.oriented
$java
java
integer
string
Int
933
fm90.5
1fm
2. Define a Square class with the length of its side as an instance vari-
able. Include an appropriate constructor method and methods to
enlarge an instance as well as compute its area.
3. Using the Square class in Question 2, create ten randomly sized
squares and find the sum of their areas. (The method Math.random()
returns a random number between 0.0 and 1.0 each time it is invoked.)
4. Add the functionality for a Square object to draw itself via ASCII
characters. For example, a Square of length 4 can be drawn as:
or:
5. Find a number with nine digits d1d2d3,…, d9 such that the sub-string
number d1, …, dn is divisible by n, 1<=n<=9. Note that each of the
digits may be used once.
The System.out.print() and System.out.println() methods
may be useful.
XXXX
X++X
X++X
XXXX
* *
* *
****
****
Another Random Scribd Document
with Unrelated Content
Plantaginaceæ, 408, 424
Plantago, 408
Plants, classification, 343, 347
Plate-gilled Molluscs, 191
Pleuronectes, 326
Pleuronectidæ, 324
Plocamium, 61, 366
Plumbaginaceæ, 408, 424
Poa, 396
Podded Sea-oak, 388
Podophthalmata, 266, 269, 304
Pogge, 335
Pollack, 327
Polybius, 293
Polycarpon, 413
Polychæta, 177
Polygala, 416
Polygalaceæ, 416, 426
Polygonaceæ, 404, 424
Polygonum, 404
Polypetalæ, 403
Polypogon, 397
Polysiphonia, 372
Polystomata, 115
Polyzoa, 188
Porcelain Crab, 280
Porcellana, 280
Porifera, 115
Porphyra, 355
Porpoise, 339
Portland Spurge, 403
Portunus, 292
Prawn, 44, 278
Preservation of marine objects, 71
Preservatives, 72
Prickly Cockle, 215
Prickly Salt-wort, 407
Primulaceæ, 424
Prosobranchiata, 232, 236
Protophyta, 343, 347
Protoplasm, 102
Protoplasta, 104, 110
Protozoa, 102
— classification, 104
Psammobia, 208
Pteropoda, 230, 255
Pulmonifera, 255
Punctaria, 383
Puncturella, 241
Purple Spurge, 403
Purple-tipped Urchin, 168
Purpura, 249
Pycnogonum, 293
Pyramidellidæ, 246, 255
Radiata, 140
Radiolaria, 104, 110
Ragworm, 40, 179
Raiidæ, 318
Ranunculaceæ, 422, 426
Raphanus, 420
Rays, 318
Red Mullets, 338
Red-specked Pimplet, 150
Reptilia, 307
Reseda, 417
Resedaceæ, 417, 426
Rhizocarpeæ, 345, 348
Rhizopods, 104
Rhizostoma, 136
Rhodomela, 372
Rhodomelaceæ, 372, 390
Rhodophyllis, 61
Rhodospermeæ, 350, 355, 389
Rhodymenia, 61, 365, 367
Rhodymeniaceæ, 365, 389
Rhombus, 326
Rhynchota, 297, 305
Rissoa, 244
Rock-fishes, 46
Rocklings, 328
Rock-pools, 6, 31
Rosy Anemone, 149
Rosy Feather Star, 160
Rotifers, 189
Rushes, 400
Rytiphlæa, 375
Sabella, 184
Saddle Oyster, 222
Sagartia, 146
Sagina, 416
Salicornia, 407
Salmo, 321
Salmon, 321
Salmon Dace, 339
Salmonidæ, 321
Salsola, 407
Salt-wort, 407
Sand Eels, 326
Sandhoppers, 268
— preserving, 81
Sand Smelts, 332
Sandworm, 178
Saxicava, 203
Scalaria, 244
Scallops, 222
Scentless Mayweed, 411
Schizopoda, 304
Schizymenia, 61, 364
Scirpus, 399
Scomber, 337
Scomberidæ, 337
Scorpionidæ, 304
Scorpion Spider-crab, 289
Scurvy Grass, 419
Scylliidæ, 319
Scyllium, 319
Sea angling, 34
— Aster, 410
— Buckthorn, 403
— Bullheads, 335
— Bream, 338
— Campion, 415
— Carrot, 411
— Cat, 334
— Cat’s-tail Grass, 397
— Cucumbers, 169
— Devil, 336
— Eggs, 165
— — preserving, 79
— Girdles, 384
— Grass, 61, 353, 400
— Hard-grass, 395
— Holly, 412
— Kale, 420
— Lavender, 409
— Lemons, 233
— Lettuce, 61
— Loach, 328
— Lyme-grass, 395
— Mallow, 415
— Mat, 188
— Meadow Grass, 396
— Mouse, 179
— Pearl-wort, 416
— Perch, 338
— Pill-ball, 268
— Pink, 408
— Purslane, 406, 416
— Radish, 420
— Reed, 396
— Rocket, 420
— Rushes, 400
— Salt, 17, 59
— Saltness of, 17
— Samphire, 411
— Sand-wort, 415
— Sedge, 398
— Slater, 268
— Slugs, 233
— Snails, 331
— Spurge, 403
— Squirts, 188
— Stock, 418
— Stork’s-bill, 414
— Urchins, 157, 165
— — preserving, 79
— — shell of, 166
— teeth, 167
— water, artificial, 59
— composition, 59
— weeds, 343
— — classification, 389
— — preserving, 86
— Wormwood, 410
Seaside Arrow Grass, 401
— Bindweed, 409
— Cottonweed, 410
— Feverfew, 411
— Grasses, 392
— Knot Grass, 404
— Plantain, 408
— plants, 391
— classification, 423
Section cutting, 96
Sedges, 398
Selaginellales, 345, 348
Sepia, 253
Sepiadæ, 253, 255
Sepiola, 252
Serpula, 185
Serranidæ, 338
Serrated Pill-ball, 268
Serrated Wrack, 386
Sertularia, 128
Sessile-eyed crustaceans, 266
Shanny, 333
Sharks, 318
Shells, preserving, 83
Shore Crab, 261, 291
— Spider, 293
Shrimps, 278
— preserving, 81
Shrubby Mignonette, 417
Silene, 415
Silicia, 122
Siphonaceæ, 358, 389
Siphonida, 198, 255
Siphonostomata, 236, 247, 255
Six-rayed Sponges, 119
Skates, 318
Slender-beaked Crab, 289
Sloke, 61, 355
Smelt, 321
Smooth Hound, 320
Snoods, 37
Solanaceæ, 409, 424
Solanum, 409
Soldier Crab, 280
Sole, 326
Solea, 326
Solecurtus, 207
Solenidæ, 255
Sparidæ, 338
Spartina, 397
Sparus, 338
Spergularia, 415
Sphacelaria, 279
Sphærococcoideæ, 366, 390
Sphærococcus, 366
Sphæroma, 268
Spicules, 118
Spider Crabs, 288
Spike Rush, 399
Spiny-finned fishes, 329
Spirorbis, 187
Sponges, 115
Spongiocarpeæ, 390
Spoon Worms, 176
Sporochnaceæ, 385, 390
Sporochnus, 385
Spotted Dogfish, 320
Spotted Hog-louse, 268
Spout Shell, 245
Sprats, 323
Spring-tails, 299
Spurges, 403
Spyridia, 363
Spyridiaceæ, 368, 389
Squamariæ, 390
Squid, 252
Squirt Worms, 176
Stalk-eyed crustaceans, 266, 269
Starfishes, 157
— preserving, 79
Stargazers, 336
Statice, 408
Stenorhynchus, 289
Sticklebacks, 331
Stilophora, 383
Sting Bull, 337
Sting Fish, 335
Stock, 418
Stomopoda, 269, 304
Stone Crab, 280
Strawberry Beadlet, 142
Sucker Fishes, 330
Sweet Alyssum, 419
Swimming Crab, 293
Sycon, 121
Syngnathidæ, 328
Syngnathus, 329
Tamariscaceæ, 413, 425
Tamarisk, 413
Tangles, 384
Tapes, 211
Tealia, 143
Tectibranchiata, 238, 255
Tectibranchs, 236
Teleostomi, 318, 320
Tellina, 208
Tellinidæ, 207, 255
Terebella, 181
Terebratulina, 225
Teredo, 201
Tetrabranchiata, 255
Thalictrum, 421
Thallophytes, 343, 344, 347
Trichoptera, 305
Thornback Crab, 289
Thracia, 204
Thrift, 408
Thuiaria, 132
Thysanoptera, 298, 305
Tides, 9
Tooth shells, 238
Top shells, 243
Trachinidæ, 336
Trachinus, 337
Treacle Mustard, 418
Tree Mallow, 415
Trefoil, 413
Trifolium, 413
Triglochin, 401
Triopa, 235
Tritonia, 235
Tritoniadæ, 235
Trivia, 248
Trochus, 243
Trumpet Anemone, 141
Tubularia, 132
Tunicates, 188
Turbellaria, 175
Turbinidæ, 243, 255
Turbot, 326
Turkey-feather Laver, 382
Turret shells, 245
Turritella, 244
Turritellidæ, 244, 255
Twin-bladder Wrack, 387
Two-spotted Sucker, 331
Ulva, 61, 354
Ulvaceæ, 389, 354
Umbelliferæ, 411, 425
Umbilicus, 226
Umbo, 193
Vascular cryptogams, 345
Velutina, 247
Velvet Crab, 292
Veneridæ, 210, 255
Venus, 210
Vermes, 172
Vertebrates, 306
Vetch, 413
Vicia, 413
Viola, 417
Violaceæ, 417, 426
Violet Fiddler, 292
Water Ferns, 345
Weavers, 336
Wedge shells, 208
Whales, 340
Wheel animals, 189
Whelks, 248
Whirl Worms, 175
Whistle Fish, 328
Whitebait, 323
White Salmon, 339
Whiting, 327
Wild Cabbage, 418
Wild Celery, 412
Wing shells, 219
Wolf Fish, 334
Woody Nightshade, 409
Worms, 172
— parasitic, 174
Worm Pipe-fish, 329
Wrangeliaceæ, 389
Wrasses, 329
Xantho, 292
Xylophaga, 201
Yellow Poppy, 420
Zeus, 338
Zoantharia, 138
Zoarces, 333
Zonaria, 382
Zostera, 353, 400
Printed in England at The Ballantyne Press
Spottiswoode, Ballantyne & Co. Ltd.
Colchester, London & Eton
Transcriber’s Note
Minor inconsistencies in punctuation of tables or captions are silently corrected.
Hyphenation is variable. Those compound words which are hyphenated only on line
breaks are rendered using modern usage.
The word ‘movable’ appears only once as ‘moveable’ (165), which is retained.
The index entry for 'Œpophilus' is considered to be an error. All instances of the word
appear in the text as 'Æpophilus'. This has been corrected and moved to the appropriate
alphabetic position.
The following corrections were made to obvious printer’s errors: devel[e/o]ped (336);
co[n/m]posed (364).
The following list contains punctuation corrections made:
p. 65 one of them[.] Added.
p. 255 [Class] LAMELLIBRANCHIATA
Added to match other
entries.
p. 257 their tendencies[,/.] Corrected.
p. 292 low-water[-]mark
Unhyphenated
elsewhere.
p. 340 [(]Cetacea) Added.
p. 390 in firm gelatine[,/.] Corrected.
p. 403 by its stipuled leaves[.] Added.
p. 434 Rhodospermeæ, 350, 355, 38[9] Added.
*** END OF THE PROJECT GUTENBERG EBOOK THE SEA SHORE
***
Updated editions will replace the previous one—the old editions
will be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.
START: FULL LICENSE
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the
free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.
Section 1. General Terms of Use and
Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only
be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E. Unless you have removed all references to Project
Gutenberg:
1.E.1. The following sentence, with active links to, or other
immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.
1.E.2. If an individual Project Gutenberg™ electronic work is
derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.
1.E.3. If an individual Project Gutenberg™ electronic work is
posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.
1.E.4. Do not unlink or detach or remove the full Project
Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute
this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
1.E.7. Do not charge a fee for access to, viewing, displaying,
performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.
1.E.8. You may charge a reasonable fee for copies of or
providing access to or distributing Project Gutenberg™
electronic works provided that:
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You provide a full refund of any money paid by a user who
notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.
• You provide, in accordance with paragraph 1.F.3, a full refund of
any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.E.9. If you wish to charge a fee or distribute a Project
Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.
1.F.
1.F.1. Project Gutenberg volunteers and employees expend
considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.
1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except
for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.
1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you
discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.
1.F.4. Except for the limited right of replacement or refund set
forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
1.F.5. Some states do not allow disclaimers of certain implied
warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.
1.F.6. INDEMNITY - You agree to indemnify and hold the
Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.
Section 2. Information about the Mission
of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.
Volunteers and financial support to provide volunteers with the
assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.
Section 3. Information about the Project
Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.
The Foundation’s business office is located at 809 North 1500
West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

Similar to Objectoriented Programming And Java 2nd Ed Danny C C Poo Derek Beng Kee Kiong Swarnalatha Ashok (20)

PDF
The Complete Internet and World Wide Web Cyber Classroom 2nd ed Edition Deitel
phakgaliwall
 
PDF
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
nwangayonjan
 
PDF
Download full ebook of Zero To Production In Rust Luca Palmieri instant downl...
gruddylleung
 
PDF
A Comprehensive Introduction To Objectoriented Programming With Java C Thomas Wu
yajishatte
 
PDF
C How To Program.pdf
Temesgen Molla
 
PDF
Javatech An Introduction To Scientific And Technical Computing With Java Clar...
papaivierkiy
 
PDF
(eTextbook PDF) for Starting Out with Java: From Control Structures through O...
gandheassoah
 
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
crancegaisie
 
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
anryabrica
 
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
moldtkhanizw
 
PDF
(Ebook) TinyOS programming by Philip Levis, David Gay ISBN 9780521896061, 052...
bojtiaslo
 
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
vetrfzp2311
 
PDF
Java How To Program Fourth Edition Harvey M. Deitel
timerokhobor
 
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
hejwiaz3980
 
PDF
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
xltatno
 
PDF
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
limos9telmaum
 
PDF
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
jxlhbjl0240
 
PDF
The New And Improved Flask Mega-Tutorial Miguel Grinberg
bumpbgsyyy017
 
PDF
A Comprehensive Introduction to Object-Oriented Programming with Java.pdf
Yasmine Anino
 
PDF
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
reknesluima
 
The Complete Internet and World Wide Web Cyber Classroom 2nd ed Edition Deitel
phakgaliwall
 
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
nwangayonjan
 
Download full ebook of Zero To Production In Rust Luca Palmieri instant downl...
gruddylleung
 
A Comprehensive Introduction To Objectoriented Programming With Java C Thomas Wu
yajishatte
 
C How To Program.pdf
Temesgen Molla
 
Javatech An Introduction To Scientific And Technical Computing With Java Clar...
papaivierkiy
 
(eTextbook PDF) for Starting Out with Java: From Control Structures through O...
gandheassoah
 
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
crancegaisie
 
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
anryabrica
 
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
moldtkhanizw
 
(Ebook) TinyOS programming by Philip Levis, David Gay ISBN 9780521896061, 052...
bojtiaslo
 
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
vetrfzp2311
 
Java How To Program Fourth Edition Harvey M. Deitel
timerokhobor
 
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
hejwiaz3980
 
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
xltatno
 
(Ebook) Android Cookbook by Ian F. Darwin ISBN 9781449374457, 144937445X
limos9telmaum
 
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
jxlhbjl0240
 
The New And Improved Flask Mega-Tutorial Miguel Grinberg
bumpbgsyyy017
 
A Comprehensive Introduction to Object-Oriented Programming with Java.pdf
Yasmine Anino
 
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
reknesluima
 

Recently uploaded (20)

PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Ad

Objectoriented Programming And Java 2nd Ed Danny C C Poo Derek Beng Kee Kiong Swarnalatha Ashok

  • 1. Objectoriented Programming And Java 2nd Ed Danny C C Poo Derek Beng Kee Kiong Swarnalatha Ashok download https://ebookbell.com/product/objectoriented-programming-and- java-2nd-ed-danny-c-c-poo-derek-beng-kee-kiong-swarnalatha- ashok-4104850 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Objectoriented Programming And Java Second Edition 2nd Danny Poo https://ebookbell.com/product/objectoriented-programming-and-java- second-edition-2nd-danny-poo-2256754 Objectoriented Programming Using C And Java Anand Vasappanavara Gautam Vasappanavara Ramesh Vasappanavara Anand Vasappanavara https://ebookbell.com/product/objectoriented-programming-using-c-and- java-anand-vasappanavara-gautam-vasappanavara-ramesh-vasappanavara- anand-vasappanavara-7261816 Programming With Objects A Comparative Presentation Of Objectoriented Programming With C And Java 1st Edition Avinash Kak https://ebookbell.com/product/programming-with-objects-a-comparative- presentation-of-objectoriented-programming-with-c-and-java-1st- edition-avinash-kak-924368 The Java Workshop Learn Objectoriented Programming And Kickstart Your Career In Software Development David Cuartielles https://ebookbell.com/product/the-java-workshop-learn-objectoriented- programming-and-kickstart-your-career-in-software-development-david- cuartielles-46712648
  • 3. Java Methods A Ab Objectoriented Programming And Data Structures Student Maria Litvin https://ebookbell.com/product/java-methods-a-ab-objectoriented- programming-and-data-structures-student-maria-litvin-2393214 Java Methods Objectoriented Programming And Data Structures Third Ap 3rd Ap Maria Litvin https://ebookbell.com/product/java-methods-objectoriented-programming- and-data-structures-third-ap-3rd-ap-maria-litvin-59073076 Java Methods Objectoriented Programming And Data Structures 4th Edition 4th Maria Litvin https://ebookbell.com/product/java-methods-objectoriented-programming- and-data-structures-4th-edition-4th-maria-litvin-60399372 The Essence Of Object Oriented Programming With Java And Uml Bruce E Wampler https://ebookbell.com/product/the-essence-of-object-oriented- programming-with-java-and-uml-bruce-e-wampler-983966 Mastering Java An Effective Project Based Approach Including Web Development Data Structures Gui Programming And Object Oriented Programming Beginner To Advanced White https://ebookbell.com/product/mastering-java-an-effective-project- based-approach-including-web-development-data-structures-gui- programming-and-object-oriented-programming-beginner-to-advanced- white-11063222
  • 5. Danny Poo Derek Kiong Swarnalatha Ashok Object-Oriented Second edition Programming and Java • •
  • 6. School of Computing National University of Singapore, Singapore Institute of Systems Science National University of Singapore, Singapore Ms Swarnalatha Ashok Institute of Systems Science National University of Singapore, Singapore British Library Cataloguing in Publication Data A catalogue record for this book is available from the British Library ISBN-13: 978-1-84628-962-0 e-ISBN-13: 978-1-84628-963-7 First edition © Springer Singapore 1998; 978-981-3083-96-7 Printed on acid-free paper © Springer-Verlag London Limited 2008 Apart from any fair dealing for the purposes of research or private study, or criticism or review, as permitted under the Copyright, Designs and Patents Act 1988, this publication may only be reproduced, stored or transmitted, in any form or by any means, with the prior permission in writing of the publishers, or in the case of reprographic reproduction in accordance with the terms of licences issued by the Copyright Licensing Agency. Enquiries concerning reproduction outside those terms should be sent to the publishers. The use of registered names, trademarks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant laws and regulations and therefore free for general use. The publisher makes no representation, express or implied, with regard to the accuracy of the information contained in this book and cannot accept any legal responsibility or liability for any errors or omissions that may be made. 9 8 7 6 5 4 3 2 1 Springer Science+Business Media springer.com Dr Danny Poo Dr Derek Kiong Library of Congress Control Number: 2007934261
  • 7. 1 Introduction 1 1.1 Object-Oriented Programming 1 1.2 Objects and Their Interactions in the Real World 2 1.3 Objects and Their Interactions in Programming 3 1.4 Simulation 3 1.5 Java 4 1.6 Summary 4 1.7 Exercises 5 2 Object, Class, Message and Method 7 2.1 Objects and Class 7 2.2 Message and Method 2.2.1 Message Components 10 2.2.2 Method 2.2.3 Client and Server 2.3 Creating Objects 12 2.4 Summary 14 2.5 Exercises 14 3 A Quick Tour of Java 17 3.1 Primitive Types 17 3.2 Object Definition 18 3.2.1 Variable Definitions 18 3.2.2 Methods 19 3.3 Object Instantiation 20 3.4 Object Access and Message Passing 21 3.5 Representational Independence 21 3.6 Overloading 22 3.7 Initialization and Constructors 23 9 10 11 Preface to 1st Edition xiii Preface to 2nd Edition Overview xvii Acknowledgement xix Table of Contents xv
  • 8. vi Table of Contents 3.11 Arrays 34 3.12 Result Returned by Method 35 3.13 Summary 36 3.14 Exercises 36 4 Implementation in Java 39 4.1 Calculator 39 4.1.1 The clear() Method 40 4.1.2 The display() Method 41 4.1.3 The digit() Method 41 4.1.4 41 4.2 Code Execution 42 4.3 Simple User Interface 44 4.4 Another Interface for CalculatorEngine 46 4.5 Summary 49 4.6 Exercises 49 5 Classification, Generalization, and Specialization 51 5.1 Classification 51 5.2 Hierarchical Relationship of Classes 53 5.2.1 Superclass and Subclass 53 5.2.2 A Class Hierarchy Diagram 54 5.3 Generalization 55 5.4 Specialization 56 5.5 Organization of Class Hierarchy 56 5.6 Abstract and Concrete Classes 57 5.7 Summary 58 5.8 Exercises 58 6 Inheritance 61 6.1 Common Properties 61 6.2 Inheritance 62 6.3 Implementing Inheritance 64 6.4 Code Reuse 67 4.4.1 Operator Methods Event-Driven Programming 48 3.8.2 Expression Statements 30 3.8.3 Control-flow Statements 30 3.9 Blocks 32 3.9.1 Local Declarations 32 3.10 More Control-flow Statements 33 3.8 Expressions, Statements, and Control-flow Mechanisms 24 3.8.1 Operators 24
  • 9. Table of Contents vii 6.7 Inheritance Chain 75 6.7.1 Multiple Inheritance 76 6.7.2 Problems Associated with Multiple Inheritance 77 6.7.3 Contract and Implementation Parts 79 6.7.4 Contract and Implementation Inheritance 79 6.8 Interface 80 6.8.1 Multiple Inheritance Using Interface 80 6.8.2 Attributes in an Interface 83 6.8.3 Methods in an Interface 83 6.8.4 Abstract Class and Interface 83 6.8.5 Extending Interface 84 6.8.6 Limitations of Interface for Multiple Inheritance 85 6.9 Summary 88 6.10 Exercises 89 7 Polymorphism 93 7.1 Static Binding 93 7.2 Dynamic Binding 96 7.3 Operation Overloading 97 7.3.1 Same Method Signature 97 7.3.2 Overloading Method Names 98 7.4 Polymorphism 100 7.4.1 Selection of Method 100 7.4.2 Incremental Development 101 7.4.3 Increased Code Readability 102 7.5 Summary 102 7.6 Exercises 102 8 Modularity 103 8.1 Methods and Classes as Program Units 103 8.2 Object and Class Properties 103 8.2.1 Counting Instances 104 8.2.2 Shared Attributes 106 8.2.3 Class Attributes 107 6.5.1 Change in Property Definition for All Subclasses 67 6.5.2 Change in Property Definition for Some Subclasses 68 6.5.3 Adding/Deleting a Class 72 6.6 Accessing Inherited Properties 75 6.5 Making Changes in Class Hierarchy 67
  • 10. viii Table of Contents 8.5 Encapsulation 111 8.5.1 Bundling and Information Hiding 112 8.5.2 Enhanced Software Maintainability 112 8.5.3 Trade-Off 115 8.6 Summary 116 8.7 Exercises 117 9 Exception Handling 119 9.1 Using Exceptions 119 9.2 Exception Terminology 120 9.3 Constructs and Exception Semantics in Java 120 9.3.1 Defining Exception Objects 121 9.3.2 Defining Exception Handlers 121 9.3.3 Raising Exceptions 122 9.4 A Simple Example 123 9.5 Paradigms for Exception Handling 125 9.5.1 Multiple Handlers 125 9.5.2 Regular Exception Handling 127 9.5.3 Accessing Exception Objects 128 9.5.4 Subconditions 128 9.5.5 Nested Exception Handlers 129 9.5.6 Layered Condition Handling 130 9.6 Code Finalization and Cleaning Up 130 9.6.1 Object Finalization 131 9.6.2 Block Finalization 131 9.7 Summary 132 9.8 Exercises 133 10 Input and Output Operations 135 10.1 An Introduction to the Java API 135 10.2 Reading the Java API Documentation 136 10.3 Basic Input and Output 138 10.4 File Manipulation 141 10.4.1 File Input 142 10.4.2 File Output 143 8.2.4 Class Methods 107 8.2.5 Name Aliases 8.3 Controlling Visibility 108 8.4 Packages 110 8.4.1 The package Keyword 110 8.4.2 The import Keyword 110 108 10.4.3 Printing Using PrintStream 144
  • 11. Table of Contents ix 10.9 Formatting the Output Using the Format String 151 10.10 The File Class 152 10.11 Random Access File Operations 152 10.12 Summary 153 10.13 Exercises 153 11 Networking and Multithreading 155 11.1 The Network Model 155 11.2 Sockets in Java 156 11.2.1 Example Client: Web Page Retriever 157 11.3 Listener Sockets in Java 161 11.3.1 Example Server: Simple Web Server 161 11.3.2 Running the Web Server 164 11.4 Considering Multiple Threads of Execution 165 11.5 Creating Multiple Threads of Execution 166 11.5.1 Thread Creation Using the Thread Class 166 11.5.2 Thread Creation Using the Runnable Interface 168 11.6 Improvement of Web Server Example 168 11.7 Thread Synchronization and Shared Resources 169 11.8 Summary 175 11.9 Exercises 176 12 Generics and Collections Framework 179 12.1 Introduction 179 12.2 Rationale Behind Generics 179 12.2.1 The Problem 180 12.2.2 Run-time Type Identification (RTTI) 182 12.3 Java Generics 183 12.3.1 Generic Class 183 12.3.2 Generic Method 185 12.4 Collections Framework 186 12.4.1 Collections Interface 12.4.2 ArrayList Class 187 186 10.5 Framework for Code Reuse 145 10.6 DataInputStream and DataOutputStream Byte Stream Class 147 10.7 Character Stream Classes 148 10.8 Tokenizing the Input Using the Scanner Class 150 12.4.3 HashSet Class 190 12.4.4 HashMap Class 194 12.5 Sorting Collections 196
  • 12. x Table of Contents 12.6.2 binarySearch Method 198 12.7 Summary 199 12.8 Exercises 199 13 Graphical Interfaces and Windows 201 13.1 The AWT Model 201 13.2 Basic AWT Constituents 202 13.2.1 Frames 203 13.2.2 Components 204 13.2.3 Panels 205 13.2.4 Layout in Panels 206 13.2.5 Events 209 13.2.6 Events in JDK 1.1 (and later versions) 212 13.3 Basic Components 214 13.3.1 Label Component 214 13.3.2 Button Component 215 13.3.3 Checkbox Component 215 13.3.4 CheckboxGroup Component 215 13.3.5 TextArea Component 216 13.3.6 Choice Component 217 13.3.7 List Component 218 13.3.8 Menus and Menu Items 219 13.3.9 Dialog Frames 221 13.3.10 File Dialog Frames 223 13.4 Custom Components 224 13.5 Other Kinds of Class Definitions 226 13.5.1 Inner Classes 227 13.5.2 Anonymous Classes 227 13.5.3 Local Classes 228 13.6 Swing Components 230 13.6.1 Transiting from AWT to Swing 231 13.6.2 Model versus View 234 13.7 Summary 235 13.8 Exercises 236 12.5.1 Sort Algorithm 12.5.2 Comparator Interface 12.6 Searching Collections 198 12.6.1 indexOf and contains Methods 198 196 197 14 Applets and Loaders 237 14.1 Applet Characteristics 237 14.2 Applet Life Cycle 241
  • 13. Table of Contents xi 14.6 Efficient Repainting 247 14.7 Applet Parameters 248 14.8 Loading Code Dynamically 250 14.9 Security Restrictions for Untrusted Code 253 14.9.1 Security Policy 255 14.9.2 Keys 256 14.9.3 Permissions 256 14.10 Summary 258 14.11 Exercises 258 15 Java Servlets 259 15.1 Dynamic Web Pages and Servlets 259 15.2 Tomcat Installation 260 15.2.1 Downloading and Installation 260 15.2.2 Configuration 261 15.2.3 Starting and Stopping Tomcat 262 15.3 Sample Servlet 263 15.4 Servlet Characteristics 266 15.5 Servlet Paramters and Headers 266 15.6 Servlet Output 271 15.7 Handling Sessions 271 15.7.1 Session Timeout 274 15.8 Concurrency 274 15.9 Customized Processors 274 15.10 Summary 276 15.11 Exercises 277 16 Object Serialization and Remote Method Invocation 279 16.1 Object Serialization 279 16.2 Components in Object Serialization 281 16.3 Custom Serialization 281 16.3.1 The Externalizable Interface 284 16.4 Distributed Computing with Java 284 16.4.1 RMI and CORBA 285 16.4.2 Java Limitations 285 16.5 An Overview of Java RMI 286 14.3 Custom Applets 242 14.4 Images and Audio 243 14.5 Animation in Applets 245 16.6 Using Java RMI 287 16.6.1 Setting Up the Environment on Your Local Machine 287
  • 14. xii Table of Contents 16.7 RMI System Architecture 289 16.8 Under the Hood 291 16.9 RMI Deployment 293 16.10 Summary 295 16.11 Exercises 295 17 Java Database Connectivity 297 17.1 Introduction 297 17.2 Java Database Connectivity 297 17.3 JDBC Architecture 298 17.4 JDBC Drivers 17.4.1 Types of Drivers 17.5 JDBC APIs 302 17.5.1 Establishing a Connection 302 17.5.2 Data Manipulation 17.6 Data Definition Language (DDL) with JDBC 305 17.6.1 Creating a Table 305 17.6.2 Dropping a Table 306 17.7 Data Manipulation Language (DML) with JDBC 307 17.7.1 Creating (Inserting) Records Using JDBC 307 17.7.2 Deleting Records Using JDBC 307 17.7.3 Retrieving Records Using JDBC 307 17.7.4 Updating Records Using JDBC 309 17.7.5 Updatable Result Sets 310 17.7.6 Prepared Statements 311 17.8 Summary 313 17.9 Exercises 313 298 299 303 Index 315 16.6.2 How RMI Works 16.6.3 An RMI Example 288 287
  • 15. Preface to 1st Edition Control abstraction was the message of the first programming revolution seen in high-level programming languages such as Algol and Pascal. The focus of the next revolution was data abstraction, which proposed languages such as Modula and Ada. The object-oriented revolution began slowly in the 1960s with the programming language Simula, but moved onto more languages such as Smalltalk, Objective-C and C++. Java is almost a hybrid between Smalltalk and C++, and has gained widespread acceptance due to its association with the Internet, its availability to a large user base and reusable libraries for programming in a graphical environment. Our programming lineage has passed through Pascal, C and C++. As with many other programmers, good run-time checks with automatic memory manage- ment and a reusable API made Java a very attractive option. After a half-day on the original Java Whitepaper and the early Java online tutorial, we were sold on the Java bandwagon and already writing code. In another two days’ time, we were using the Abstract Windowing Toolkit (AWT) package for graphical applications. In situations where there is no large investment into older languages, we are quite happy to abandon them completely. Effective programming in Java comes from understanding three key areas – object-oriented concepts, the syntax and semantics of the Java programming language and the Java Application Programming Interface (API). This is our emphasis when we conduct professional courses, and in this book as well. Much of the material in this book is based on previous courses which we have conducted over the past two years to the industry and the National University of Singapore (NUS). Courses conducted for the industry last about 5 to 7 days, depending on the amount of coaching that participants require. In the Department of Information Systems and Computer Science at NUS, a course on “Object-Oriented Methods” runs over 13 weeks. As you might have noticed, we have taken to Java as ducks to water. Java has allowed us to think about and specify object behavior. This results in executable code which is merely secondary. What is important is the clean specification of object behavior. Similarly, in getting accustomed to working with objects, we believe that you will enjoy it too.
  • 16. Preface to 2nd Edition Since publishing the first edition almost 10 years ago, we have seen Java being used in many high school and university programming courses. Further, many projects now use Java as the implementation language. Similarly, at the Institute of Systems Science, we have seen professional developers warming up to Java for the first time in 1998, to those who use Java in their daily work in 2007. We have thus updated the material to cover J2EE topics such as JDBC, RMI, Serialization and Java Servlets. We have also added a chapter on Generics as the Java language evolved to allow this elegant feature. For those who might be embarking on a Java journey now, we wish you a pleasant journey and a well-used road map. Many have taken this journey before and are enjoying the fruits of their learning investment.
  • 17. Chapter 1 presents an introduction to the object-oriented world consisting of objects and object communication via the exchange of messages. Object-oriented concepts and terminology used in object-oriented methodology are discussed in chapter 2. Chapter 3 shows how these concepts materialize in the form of Java code and representations. It discusses the basic features and syntax of Java and builds upon the concepts using an incremental Counter example. Following on from language syntax, chapter 4 demonstrates the standard pro- gramming environment using the Java Development Kit (JDK), and how a class definition may be compiled and executed, integrated and reused within other code fragments. The chapter also delves into using the Java Application Programming Interface (API) to demonstrate the ease and productivity gains of code libraries. Chapter 5 returns to the discussion of objects, in particular, the organization of objects into manageable classes. The concept of class enables a developer to organize a complex problem domain into more manageable components. Grouping objects into classes is an act known as classification in object-oriented modeling. When classes are formed, they can be further distinguished into superclasses or subclasses, accord- ing to their similarities or differences in properties. Class hierarchies can then be formed. The creation of superclasses and subclasses is achieved through abstracttion mechanisms known as generalization and specialization respectively. Classification, generalization and specialization are thus important abstraction mechanisms for organizing objects and managing complexities. Inheritance is discussed in chapter 6. Common properties of classes can be shared with other classes of objects via the inheritance mechanism. It is through inheritance that software component reuse is possible in object-oriented programming. Software reusability is important because code need not be produced from scratch, thereby increasing the productivity of developers. Another topic close to the heart of object-oriented programming is polymorphism. This topic is concerned with object messaging and how objects of different classes respond to the same message. With polymorphism, objects of different class definition can respond to the same message with the appropriate method. In this way, generic software code can be produced, thus enhancing the maintainability of software systems. Polymorphism is supported by dynamic binding and operation overloading, topics that are central to the discussion in chapter 7. Enhancing software maintainability is a significant software development objective. A programming technique known as Structured Programming was intro- Overview for achieving maintainable software. Modularity is emphasized in object-oriented duced in the 1980s, promoting modularity as a Software Engineering principle
  • 18. programming in the form of method, object, and class definition. Encapsulation is the manifestation of modularity in object-oriented programming to the fullest. As will be made clear in chapter 8, encapsulation brings together related properties into class definitions with the structural definition of classes hidden from their users. The purpose of this approach is to hide the implementation detail of objects so that when changes in implementation of objects are called for, users of the objects will not be adversely affected. Exception Handling is considered in chapter 9. This is especially important in object-oriented programming, as the mechanism for the glue and safety net in code integration and reuse. The Java API is introduced in chapter 10 and continues with the core classes for input/output, networking, graphical components and applets within Web browsers. Input and output rely on InputStream and OutputStream classes, as well as Reader and Writer classes in JDK 1.1. Chapter 11 introduces network connections via TCP/IP using the Socket class, similar to those for input and output in chapter 10, as they share behavior from InputStream and OutputStream. As multi-processing is typically used with client/ server applications, we have also included the multi-threading API in this chapter, together with a skeleton Web server as the working example. Collection classes with Generics in chapter 12 show how the concepts of modu- larity and encapsulation work to facilitate code reuse. This chapter not only gives an overview of the classes in the Collections Framework, but this framework is an excellent sample of how reusable code is written. The AWT model is elaborated with descriptions of its constituents and example usage for Graphical User Interfaces in chapter 13. There are sufficient code examples to build interfaces for most simple applications. We have also incorporated Swing classes for better interactivity. Applet development relate to graphical interfaces and the issue of dynamic loading of compiled Java bytecodes. This is discussed in chapter 14. Situations where applet behavior differs from Java applications, security measures and implementing a loader over the network are also considered. Chapter 15 covers Java Servlets. It is related to dynamic code loading and applets in chapter 14, but occurring on the server side. This forms the basis for Java- based Web applications. Chapter 16 examines Java Object Serialization and Remote Method Invocation. The former may be viewed as a continuation of input and output facilities discussed Remote Method Invocation (RMI) for distributed applications. A simple client/server application framework using RMI is provided. Chapter 17 provides an overview of the popular requirement of working with databases – Java Database Connectivity. This topic warrants a whole book, but we limit our discussion to the rationale, perspective and architecture of JDBC together with necessary methods for working with real databases. xviii Overview in chapter 10, but with the focus to implement object persistence. Object Serialization is also used to move objects over a network and forms a key role in implementing
  • 19. In revising the text, we are thankful to readers of the first edition who have given encouraging feedback. If not for these folks, we would never have considered this second round. We also thank our colleagues and bosses at our respective work places who have supported and encouraged this book revision. We also thank the folks at Springer Verlag who felt that a second edition was worthy. Special thanks are due to Derek’s former colleagues at the now defunct Centre for Internet Research (CIR), National University of Singapore, who had worked to use the Internet productively. The lineage of CIR may be traced back to the Technet Unit in the Computer Centre of the National University of Singapore, which was first to provide and promote Internet services in Singapore. The effort saw the spin-off to PacNet in Singapore. In particular, Dr. Thio Hoe Tong, former Director of the Computer Centre and Dr Tan Tin Wee, have supported the Java team even in the early days when we played with the Alpha releases of Java. Poo, Kiong & Ashok National University of Singapore August 2007 Acknowledgement
  • 20. 1 Introduction Object-oriented programming has been in practice for many years now. While the fundamental object-oriented concepts were first introduced via the class construct in the Simula programming language in the 1960s, the programming technique was only accepted with the advent of Smalltalk-80 more than a decade later. Object-oriented programming has come a long way. More and more programs are now designed and developed using this approach. What is object-oriented pro- gramming? What makes it attractive as an alternative programming approach? How does it differ from the traditional procedural programming approach? These ques- tions will be discussed in this chapter. 1.1 Object-Oriented Programming The procedural approach to programming was the de facto approach in the early days of programming. Here, code is modularized based on a system’s processes. For instance, in developing a library application system, we would have considered processes such as the checking in an d out of books, making reservations of books, cataloging of books, and so on. Problem solving would involve the analysis of these processes in terms of the procedural tasks carried out and the production of a system whose representation is based on the procedural flow of the processes. Object-oriented programming, on the other hand, models objects and their in- teractions in the problem space and the production of a system based on these objects and their interactions. Since the real-world problem domain is characterized by objects and their in- teractions, a software application developed using the object-oriented programming approach will result in the production of a computer system that has a closer repre- sentation of the real-world problem domain than would be the case if the procedural programming approach is used.
  • 21. 2 Object-Oriented Programming and Java 1.2 Objects and Their Interactions in the Real World Let us consider a real-world situation. There are two persons, Benjamin and his wife, Bambie. They are customers of HomeCare, a company dealing in luxurious furni- ture. HomeCare sells a variety of sofa sets. Each sofa set is labeled with an identifi- cation number and a price tag. After viewing the sofa sets for an hour, Benjamin and Bambie decide to purchase a green leather 5-seater set. They approach Sean, a sales- person, to place their order. In making his request known to Sean, Benjamin sends a message to Sean, “I would like to purchase this green leather, 5-seater set. Can you please have it sent to me by next Wednesday?” The message that Benjamin has sent to Sean is a takeOrder message. It con- tains information such as the type of sofa set (a green leather, 5-seater set) and the date of delivery (next Wednesday). This information is known as the parameters of the takeOrder message. In response to Benjamin’s message, Sean replies to Benjamin by returning the result of his request. We can represent the interaction between Benjamin and Sean graphically using Figure 1-1. takeOrder result Benjamin Sean Figure 1-1: Interaction between Benjamin and Sean. Sean was able to respond to Benjamin’s takeOrder message because he under- stood it and had the means to handle Benjamin’s request. Although Sean knew how to satisfy Benjamin’s request, Benjamin did not. In fact, most of the time, customers do not know how a salesperson has satisfied their orders. All they get from salesper- sons are replies such as, “I am sorry, madam, we are unable to satisfy your request because the sofa you wanted has been sold,” or “Sir, your request has been satisfied. We will deliver the goods on Wednesday between 10 am to 11 am to the address indicated. Thank you for your order.” Sean, as a salesperson at HomeCare, has a responsibility towards Benjamin. He maintains his responsibility by applying a set of operations: 1. He determines if there is sufficient stock to satisfy Benjamin’s request. 2. He determines if the requested date for delivery is a suitable date. 3. He instructs the warehouse staff to deliver the goods to Benjamin’s address on the requested date, if the above conditions are satisfied. 4. Finally, he informs Benjamin the result of his request.
  • 22. Introduction 3 1.3 Objects and Their Interactions in Programming The interactions between Benjamin and Sean in the above real-world situation can be represented in object-oriented programming terms. For instance, Benjamin and Sean are objects that interact by sending messages. Benjamin is thus a message-sending object, while Sean is a message-receiving object. Alternatively, we can label Benjamin as a sender and Sean as a receiver. The takeOrder request from Benjamin to Sean is an example of a message. It may have additional, accompanying information known as parameters (or argu- ments) of the message. The fact that Sean responded to Benjamin’s message indi- cates that the message is a valid message. Each valid message corresponds to a method that Sean uses to fulfill his responsibility to Benjamin. An invalid message, on the other hand, is one that the receiver does not have the capability to respond to, that is, the receiver does not have a corresponding method to match the message. For example, if Benjamin had requested a discount on the price, his request would have been rejected because Sean, being a salesperson, would not have the capability (or a corresponding method) to respond to the message. A method contains a number of operations detailing how Sean is to satisfy the demand Benjamin put on Sean through the request. Figure 1-2 summarizes the relationships of these terms. Benjamin Sean takeOrder(sofa type, who, address, delivery date) result Message Object Object Method Arguments Figure 1-2: Object interactions in object-oriented programming terms. While Benjamin may know what Sean can do through his methods, he may not know how Sean does them. This is an important principle of object-oriented pro- gramming known as information hiding: the sender of a message does not know how a receiver is going to satisfy the request in the message. 1.4 Simulation Based on the above example, it is clear that concepts in object-oriented programming such as object, message and method, do provide a close representation of real-world objects and their interactions. These concepts are thus suitable for simulating actual object interactions in real-world situations.
  • 23. 4 Object-Oriented Programming and Java It is this ability for modeling real-world problems that identified object-oriented programming as being suitable for simulation. The Simula programming language was designed in the early 1970s to provide simulation abilities using object-oriented concepts. 1.5 Java Java was first introduced in 1995 as a simple and secure object-oriented program- ming language. It is a unique language in that, being a new language at that time, it was able to attract a lot of interest from the computing community. Within two years after Java was launched, there were an estimated 400,000 Java programmers and over 100 books on Java programming. There are a few possible reasons for the phenomenal interest in Java. The year 1995 saw a maturing of Web technologies, and Java’s multiplatform capability, which enabled a Java program to execute on any computer, was exceedingly attrac- tive, especially on an open network like the Internet. Java is implemented via part compilation and subsequent execution on an interpreter implemented in software. Java applications are therefore object code portable as long as a Java virtual machine is implemented for the target machine. The popularity of Java is also ironically due to its similarity with its close rival C++. Java takes the pain out of learning a new language by reusing much of C and C++. At the same time, safe programming practice in Java and language facilities for automatic memory management were benefits that were attractive to programmers on the verge of deserting their C/C++ camps. In relation to the Internet, Java applets have given rise to a new generation of distributed applications with low software distribution and maintenance costs. As applets are embedded in an HTML document via <APPLET> tags, its transmission to the client machine for execution is implicitly handled by the underlying network protocols and thus makes the typical channels of distribution and installation obsolete. While the object-oriented programming framework promotes reusability of software and code, this very practice has been demonstrated in the rich set of class libraries seen in the Java language. The Java foundation class libraries provide for windowing and graphical user interface programming, network communications, and multimedia facilities. Together, they demonstrate the practical and productive work done in Java. 1.6 Summary In this chapter, we discussed: • An overview of object-oriented programming concepts and their applicabi- lity for modeling and representing real-world entities and their interactions in the problem-solving process.
  • 24. Introduction 5 • Object-oriented concepts of object, message, and method. • An overview of the Java programming language and the potential of produc- tive software development 1.7 Exercises 1. Distinguish the programming approach used in procedural programming and object-oriented programming. 2. Discuss the validity of the following statement: The object-oriented pro- gramming approach is ideal for simulating real-world problems. 3. Consider the following scenarios and outline the objects and their interac- tions in terms of messages and arguments: (a) a driver driving a car; (b) a customer making a cash withdrawal from an automated teller machine (ATM); (c) a customer buying a compact disk player from a vendor; (d) a traffic policeman directing traffic at a junction; (e) a lecturer delivering his/her lecture to a class of students; (f) a tutorial discussion between an instructor and students.
  • 25. 2 Object, Class, Message and Method We had our first introduction to objects, message and method in Chapter 1. Another concept closely associated with the concept of objects is class. In object-oriented programming, a class is a definition template for structuring and creating objects. In this chapter, we will discuss the concept of object, message, method and class and how these concepts are used in a computer model. 2.1 Objects and Class In Chapter 1, we introduced Benjamin. Now, meet Bernie, another customer at HomeCare. As customers of HomeCare, Benjamin and Bernie share some similar information. For example, both have a name, an address, and a budget—information that is relevant when describing customers. This information is known as object attributes. An object attribute definition allows for objects to have independent attribute values. For example, Benjamin may have a larger budget and thus a larger budget value (say $2000) than Bernie whose budget may be $1000. Collectively, the values of an object’s attributes represent the state of the object. Besides attributes, Benjamin and Bernie also exhibit some behavior typical of a customer. For instance, Benjamin and Bernie execute a method when making a purchase. Let us call this method purchase(). The method purchase() is made up of a set of operations that Benjamin and Bernie would use to send a purchase request to a salesperson. Structurally, Benjamin and Bernie can be represented as follows:
  • 26. 8 Object-Oriented Programming and Java name, address and budget are attributes while purchase() and getBudget() are methods of the two objects. Note that both objects share a common definition of attributes and methods. In fact, all customers of HomeCare share the same set of attribute and method definitions. They all have attributes name, address and budget, and methods purchase() and getBudget(). In defining these objects, a common definition known as class is used. A class is a definition template for structuring and creating objects with the same attributes and methods. Benjamin and Bernie, being customers of HomeCare, can therefore be defined by a class called Customer as follows: One major difference between objects and class is in the way attributes and methods are treated in objects and classes. A class is a definition about objects; the attributes and methods in a class are thus declarations that do not contain values. However, objects are created instances of a class. Each has its own attributes and methods. The values of the set of attributes describe the state of the objects. Let us now examine the salespersons. Salespersons also have attributes and methods. Sean and Sara are two salespersons at HomeCare. They are thus capable of a behavior typical of a salesperson, for example, taking orders from customers. To fulfill their role as salespersons in a purchase transaction, Sean and Sara perform a method. We shall call this method takeOrder(), and represent Sean and Sara as follows: Benjamin as an Object Attributes: name = Benjamin address = 1, Robinson Road budget = 2000 Methods: purchase() {send a purchase request to a salesperson} getBudget() {return budget} Bernie as an Object Attributes: name = Bernie budget = 1000 Methods: purchase() {send a purchase request to a salesperson} getBudget() {return budget} Class Customer Attributes: name address budget Methods: purchase() {send a purchase request to a salesperson} getBudget() {return budget} address = 18, Sophia Road" " " " " " " " " " " "
  • 27. Object, Class, Message and Method 9 Being salespersons, Sean and Sara share similar attributes and methods as expected. Like the customers, their definition can be described by a class called SalesPerson with the following representation: Note that the definition of the SalesPerson class is different from the Customer class since customers and salespersons behave differently—customers make orders and salespersons take orders. 2.2 Message and Method Objects communicate with one another by sending messages. A message is a method call from a message-sending object to a message-receiving object. A message- sending object is a sender while a message-receiving object is a receiver. Sean as an Object Attributes: name = Sean Methods: takeOrder() { check with warehouse on stock availability check with warehouse on delivery schedule if ok then {instruct warehouse to deliver stock(address, date) return ok} else return not ok } Sara as an Object Attributes: name = Sara Methods: takeOrder() { check with warehouse on stock availability check with warehouse on delivery schedule if ok then {instruct warehouse to deliver stock(address, date) return ok} else return not ok } Class SalesPerson Attributes: name Methods: takeOrder() { check with warehouse on stock availability check with warehouse on delivery schedule if ok then {instruct warehouse to deliver stock(address, date) return ok} else return not ok } " " " "
  • 28. 10 Object-Oriented Programming and Java An object responds to a message by executing one of its methods. Additional information, known as arguments, may accompany a method call. Such para- meterization allows for added flexibility in message passing. The set of methods collectively defines the dynamic behavior of an object. An object may have as many methods as required. 2.2.1 Message Components A message is composed of three components: • an object identifier that indicates the message receiver, • a method name (corresponding to a method of the receiver), and • arguments (additional information required for the execution of the method). Earlier we saw that Benjamin sent a message to Sean when Benjamin wanted to buy a sofa set. The reasonable location for Benjamin to send the message to Sean is in Benjamin’s purchase() method as shown below (indicated in bold): The message Sean.takeOrder(who, stock, address, date) is interpreted as follows: • Sean is the receiver of the message; • takeOrder is a method call on Sean; 2.2.2 Method A message is valid if the receiver has a method that corresponds to the method named in the message and the appropriate arguments, if any, are supplied with the message. Only valid messages are executed by the receiver. The takeOrder() message is valid because Sean has a corresponding method and the required arguments (who, stock, address, date) are supplied with the message. Sean’s takeOrder() method is made up of a set of operations (indicated in bold below) as follows: Benjamin as an Object Attributes: name = Benjamin address = 1, Robinson Road budget = 2000 Methods: purchase() { } getBudget() {return budget} " " " " " " • "Benjamin","stock","address","date" are arguments of the message. Sean.takeOrder("Benjamin", "sofa", "1, Robinson Road", "12 November")
  • 29. Object, Class, Message and Method 11 In the above description, a message is sent from Sean to a Warehouse object to inquire on the order and delivery schedule in Sean’s takeOrder() method. If both conditions are satisfied, Sean will instruct the Warehouse object to arrange for delivery. How Sean carries out the method is known only to Sean. Neither Benjamin nor the other customers know how Sean does it. For example, to check on the stock and delivery schedule with the warehouse, Sean may have called the warehouse over the phone or he may have checked the information against a list he had gotten from the warehouse. What Benjamin knows of Sean is that Sean is capable of responding to his request since his message to Sean is acceptable by Sean. In object-oriented programming, Benjamin and Sean are said to have followed the principle of information hiding—How Sean is going to satisfy Benjamin’s request is hidden from Benjamin. In this way, Sean is free to select whatever way he chooses to satisfy Benjamin’s request; he may phone the warehouse or look up the pre- prepared list and vice versa. 2.2.3 Client and Server By executing a method, a message-receiving object (such as Sean) is said to serve the message-sending object (such as Benjamin). A message-receiving object is thus a server to a message-sending object and the message-sending object is thus a client of the server. takeOrder result Benjamin Sean yes/no available? send ok Figure 2-1: Object communication process. In any object communication, there are at least a client and a server. The client sends a message to request a server to perform a task. The task is fulfilled by a Sean as an Object Methods: takeOrder(who,stock,address,date) { check with warehouse on stock availability check with warehouse on delivery schedule if ok then { instruct warehouse to deliver stock to address on date } else return not ok } Attributes: name = Sean " " return ok
  • 30. 12 Object-Oriented Programming and Java message-corresponding method of the server. In sending a message to the ware- house, Sean is said to be the client and the warehouse is said to be the server. Benjamin, Sean, and the warehouse are three objects involved in a communi- cation process. Benjamin is the initiator, with Sean and the warehouse as partners in the communication process. Figure 2-1 depicts a typical communication process amongst objects. 2.3 Creating Objects In object-oriented programming, objects are created from classes. Instances of Customer objects are created from a Customer class and SalesPerson objects from a SalesPerson class. Created object instances are individuals with their own state. To illustrate, let us consider the example of counters. A counter is a device that keeps account of the number of times an event has occurred. It has two buttons: an initialize button that resets the counter to 0, and an add button that adds 1 to its present number. Figure 2-2 shows a counter with a number 10. initialize add 10 Figure 2-2: A counter. Structurally, the first counter object can be represented as follows: Figure 2-3 shows two more counters. initialize add 2 add 7 initialize Figure 2-3: Two Additional Counters Like the first counter, these two counters may be reset to zero and incremented through the initialize and add buttons respectively, and represented as follows: First Counter Object Attributes: number = 10 Methods: add() {number = number + 1} initialize() {number = 0} getNumber() {return number}
  • 31. Object, Class, Message and Method 13 All the three counters share the same definition of attributes and methods, and like in the previous examples, they can be defined by a class as follows: The Counter class has: • an attribute, number; • an initialize() method that causes a counter to reset its number to 0. • an add() method that causes a counter to add 1 to its number; and • a getNumber() method that returns the current value of the attribute number. Suppose a new object is created from the Counter class. Although the new Counter object would have the same definition of attributes and methods as the previous three counters, its attribute value may not be the same as the other counters. This suggests that the state of the counters may be different from one another. For the newly created fourth Counter object, it has a state represented by the attribute number with a value of 0, the value at initialization: Second Counter Object Attributes: number = 2 Methods: add() {number = number + 1} initialize() {number = 0} getNumber() {return number} Third Counter Object Attributes: number = 7 Methods: add() {number = number + 1} initialize() {number = 0} getNumber() {return number} Class Counter Attributes: number Methods: add() {number = number + 1} initialize() {number = 0} getNumber() {return number} Fourth Counter Object Attributes: number = 0 Methods: add() {number = number + 1} initialize() {number = 0} getNumber() {return number}
  • 32. 14 Object-Oriented Programming and Java Note that the attribute value of the fourth Counter object is different from the other three counters. 2.4 Summary In this chapter, we discussed: • Objects are defined by classes. • Objects from the same class share the same definition of attributes and methods. • Objects from the same class may not have the same attribute values. • Objects from different classes do not share the same definition of attributes or methods. • Objects created from the same class share the same definition of attributes and methods but their state may differ. • A method is a set of operations executed by an object upon the receipt of a message. • A message has three components: an object identifier, a method name and arguments. • A message-receiving object is a server to a message-sending object known as a client. 2.5 Exercises 1. Distinguish the terms “Object” and “Class”. 2. Consider the scenario of buying flowers from a florist. Outline the objects in such a transaction together with the messages exchanged. 3. Given a class definition Rectangle below, describe the structure of any 3 instances of Rectangle. 4. How would you implement the concept of class and method in a non-object-oriented programming language such as COBOL, Pascal or C? 5. Define using the following structure a class definition for cars. A car generally has abilities to start, move forward, move backward, class Rectangle { Attributes: length width Methods: getLength() { return length } getWidth() { return width } draw() { ... } }
  • 33. Object, Class, Message and Method 15 stop and off. A car can also return to its relative location. The starting location is a value 0. 6. Distinguish between a client and a server. 7. A client communicates with a server by sending a ___________ to the server. The ___________ is a call on a ___________ of the server. class Car { Attributes: ... Methods: ... }
  • 34. 3 A Quick Tour of Java Earlier, we introduced key object-oriented concepts such as objects, methods and classes and how these may be ultimately used in a computer model. In this chapter, we see how the Java programming language is used to construct our object model of the problem domain. This approach is advantageous in that it allows our model to operate or “come alive” under computer control. 3.1 Primitive Types The Java programming language allows the creation of objects that will ultimately participate in message communication. We have seen that objects may have diverse behavior and that it is more convenient to specify objects via classification, that is, class constructs. Before examining class definitions for user-specified objects, we should be mindful that Java also provides primitive values from which other (bigger) objects may be described in terms of and constructed from. For example, a complex number may be seen as being comprised of two numbers representing the real and imaginary parts. The primitive types byte, short, int and long defined in the Java language allow for the representation of discrete integer values of widths 8, 16, 32, and 64 bits, respectively. These in turn correspond to the representation of numeric The primitive types float and double allow for the representation of single and double precision floating-point real values with representational widths of 32 and 64 bits, respectively. The adopted IEEE 754 standard includes both positive and negative sign-magnitude numbers, both positive and negative zeros and infinities, and unique not-a-number representations. ranges –128 to 127, –32768 to 32767, –2147483648 to 2147483647, and –9223372036854775808 to 9223372036854775807, respectively.
  • 35. 18 Object-Oriented Programming and Java Values of type float are of the form s·m·2e , where s is either +1 or –1, m is a positive integer less than 224 , and e is an integer between –149 and 104. Similarly, values of type double have the similar form s·m·2e , but m is a positive integer less than 253 , and e is an integer between –1075 and 970. Finally, the primitive types char and boolean allow for 16-bit multi-byte characters and false/true boolean values, respectively. 3.2 Object Definition Building upon the primitive values supported by the language proper, other entities to be manipulated are user-designed objects which are defined via class constructs. A class construct in Java consists of the class keyword followed by the class name and braces { } which delimit the declaration of attributes and methods for its in- stances. The Counter class introduced in Chapter 2 would have the following form in Java: Object attributes are, in turn, either nested component objects or primitive types used to represent the object. An instance method manipulates the object by altering its attribute values. The number attribute and add() method in the Counter class below are representative of an object’s state and operation, respectively: The number attribute is also known as an instance variable because it occurs in every object or instance of the Counter class. This further implies that an attribute in one instance is independent from that in another instance. In the same vein, a method manipulates object attributes in the same instance. This occurs when a method is invoked and the corresponding code in its body is executed. In our recent example, invoking the add() method of an object will increment the corresponding number attribute. 3.2.1 Variable Definitions Variable definitions in Java take the form below, where the type name T precedes the variable name v: T v; class Counter { attribute and method declarations } class Counter { int number; void add() { number = number +1; } }
  • 36. A Quick Tour of Java 19 Typing in a programming language allows the values for a variable to be anticipated. As such, appropriate storage may be set aside for these values. There is another subtle advantage of typing in programming languages: the val- ues associated with the variable also imply what operations are valid and applicable. For example, multiplication and division applies to numeric values but not to charac- ter values. Thus, the language compiler may flag multiplication and division of char- acter values as erroneous. All variables in Java are typed, allowing the compiler to verify during compila- tion that operations on the object associated with the variable are legitimate. 3.2.2 Methods A method definition that occurs in a class construct is made up of two distinct por- tions: the method signature header and its implementation code body surrounded by the braces { ... }. The method signature portion, such as void add() in the Counter example, has the generic form below, where m is the method name, T its return type, with Rn and pn being parameter types and names, respectively (n being the number of parame- ters): T m(R1 p1, R2 p2, ... Rn pn) We have seen that a method named m() is invoked to correspond to a message m sent to the object. Consequently, the object may return a result to the message sender. The type of this value is denoted by T. If no result needs be returned, the keyword void is used instead. The formal parameters p1, p2…pn contain the additional values sent together with the message. They have corresponding types R1, R2…Rn, and are used by the compiler to verify that the correct parameters are supplied for each method invoca- tion. Any number of formal parameters may be specified, but the number of actual parameters in a message must match those originally specified in the method signa- ture. The implementation of a method consists of a block of statements surrounded by { }. Often, such methods would modify the object’s attributes. In the case of the add() method of our Counter example, it increments the variable number. A block consists of declarations of any local variable, expressions and control-flow con- structs. These will be discussed in detail in following sections. class Counter { int number; void add() { number = number+1; } IntheslightlyexpandedversionoftheCounterclassbelow,anextrainitialize() method has been added to re-initialize the Counter value so that counting can be easily restarted. This allows instances to respond to the additional initialize message.
  • 37. 20 Object-Oriented Programming and Java If the number of times a counter is restarted is significant, we can introduce another attribute reused to maintain this information. Correspondingly, this attribute is incremented in the block of the initialize() method: The previous example of the class Counter definition shows that an object may have as many attributes and methods as required to effectively model the object. In the most recent definition, objects of the class Counter have two attributes (number and reused, both with an initial value of 0 when created) and two methods (add() and initialize()). 3.3 Object Instantiation except by calling the object allocator function new(). The expression new Counter() returns a newly created instance of the Counter class. However, in order that this new object may be referred to, it is assigned to an appropriate variable. Assuming the variable carpark in the fragment below, a new Counter object may be created via new Counter(), and then assigned to the former: Counter carpark; ... carpark = new Counter(); Henceforth, the newly created object may be referred to via the variable carpark. Where more Counter objects are needed, the object allocator function new() may be repeatedly invoked, and the resultant objects assigned to other vari- ables such as entrance and exitDoor: Counter entrance, exitDoor; ... entrance = new Counter(); exitDoor = new Counter(); class Counter { int number = 0; int reused = 0; void add(){ number = number+1; } void initialize(){ number = 0; reused = reused+1; } } void initialize() { number = 0; } } template for objects to be created. However, no instances of the class is crested, A class construct provides a description for objects of that class, and serves as a
  • 38. A Quick Tour of Java 21 3.4 Object Access and Message Passing Since the attributes and methods of an object are considered its characteristics, these are accessed via the qualification operator “.” with respect to an object proper. Thus, the counts of the various Counters carpark, entrance and exitDoor are carpark.number, entrance.number and exitDoor.number, respectively. The total number from these counters is: carpark.number + entrance.number + exitDoor.number Similarly, the initialize() method of Counters carpark, entrance and exitDoor may be invoked via: carpark.initialize(); entrance.initialize(); exitDoor.initialize(); 3.5 Representational Independence While accessing object attributes directly is permissible, it is not ideal because it couples implementation code to the current object representation. As such, any changes in object representation propagates to dependent code, resulting in high software maintenance cost. A common object-oriented programming practice is information hiding—to make object representations inaccessible to clients so that modifications in (server) object representations do not propagate excessively. This decoupling of dependen- cies reduces software maintenance cost. Limiting access to object representations in Java is mainly achieved by the two main constraint specifiers private and public. The former limits access of the following entity to within the class construct, while the latter makes it accessible to any client code. Since constraint specifiers in the above class definition hides the internal repre- sentation of Counter objects, the resultant attributes are no longer accessible, and useless for interrogation. In this case, accessor methods getNumber() and getReused() are required, as outlined in the following code fragment. They provide class Counter { private int number = 0; private int reused = 0; public void add() { number = number+1; } public void initialize() { number = 0; reused = reused+1; } }
  • 39. 22 Object-Oriented Programming and Java access to internal details, but without dependency overheads. Representation inde- pendence is maintained by confining access to private attributes to within the class construct. This topic is further discussed in Chapter 8. 3.6 Overloading Attribute names of a class may be the same as those in another class since they are accessed independently. An attribute x in a class does not necessarily have any se- mantic bearing with another as they have different scopes, and does not preclude using the same attribute there. Within a Java class construct, methods may share the same name as long as they may be distinguished either by: • the number of parameters, or • different parameter types. This criterion requires a message with associated parameters to be uniquely matched with the intended method definition. If we had wanted a Counter to be incremented other than by 1, we could define another add() method that takes an integer parameter instead: class Counter { private int number = 0; private int reused = 0; public void add() { number = number+1; } public void initialize() { number = 0; reused = reused+1; } public int getNumber() { return number; } public int getReused() { return reused; } } class Counter { private int number = 0; private int reused = 0; public void add() { number = number+1; } public void add(int x) { number = number+x; } public void initialize() { number = 0; reused = reused+1; } public int getNumber() { return number; } public int getReused() { return reused; } }
  • 40. A Quick Tour of Java 23 If carpark had been assigned an instance of Counter, carpark.add() would invoke the first method to increment by 1, while carpark.add(2) would invoke the new one just defined. 3.7 Initialization and Constructors Currently, object creation and initialization are seen as distinct operations. The abstraction in object-oriented programming languages often allows these two opera- tions to be combined implicitly. As such, constructors may be seen as unique methods invoked implicitly when an object instance is created. Implicit initialization relieves the programmer from performing this important function, but more impor- tantly prevents uninitialized objects as a result of absent-minded programmers. Care- fully designed constructors allow for object invariants to be maintained regardless of how they were created. Apart from having the same name as the class, and not having a return result type, a constructor is not different from a method. It has similar syntax for its parameters and implementation body. In place of attribute initialization, our next Counter example uses a constructor method. This offers additional functionality compared with the former approach. While this change is not significant in our trivial example, constructors allow more flexibility such as the execution of arbitrary expressions and statements when compared with static attribute initializers. As with methods, constructors may also be overloaded. This provides for varied ways for objects to be created and initialized. The additional new overloaded constructors in the new class definition below allows for various initial values for number and reused other than just 0: class Counter { private int number, reused; public void add() { number = number+1; } public void initialize() { number = 0; reused = reused+1; } public int getNumber() { return number; } public int getReused() { return reused; } Counter() { number = 0; reused = 0; } } class Counter { private int number, reused; public void add() { number = number+1; } public void initialize() { number = 0; reused = reused+1; }
  • 41. 24 Object-Oriented Programming and Java 3.8 Expressions, Statements, and Control-flow Mechanisms We saw earlier that a method definition consists of the method signature and its implementation body. As an object responds to messages by executing code in the method body to affect changes in its state, assignment is a very common operation. v = E; Assignment consists of a left-hand variable that will contains or “holds” the value specified via the right-hand expression. It may be a literal value such as 3, a variable that holds the intended value such as number, or an operator with appropri- ate operands, such as x+4, or even r.f or y*p(5). In the same way that + is an opera- tor, . and () are also operators. The last expression involves nested expressions: the result of p(5) is used in multiplication. 3.8.1 Operators We first examine the operators in Java. (a) Arithmetic Operators The arithmetic operators in Java include the common addition “+”, subtraction “-”, multiplication “*” and division “/” operations. int a = 13; int v = 7; a+v // returns result 20 a-v // returns result 6 a*v // returns result 91 a/v // returns result 1 These operators apply to numeric operands, and return the type of operands. When operands are mixed, the widest is used to prevent unexpected truncation. float b = 13; int w = 7; b+w // returns result 20.0 b-w // returns result 6.0 public int getNumber() { return number; } public int getReused() { return reused; } Counter() { number = 0; reused = 0; } Counter(int x) { number = x; reused = 0; } Counter(int x, int y) { number = x; reused = y; } Counter(float z) { number = (int) z; reused = 0; } }
  • 42. A Quick Tour of Java 25 b*w // returns result 91.0 b/w // returns result 1.8571428 The “%” operator returns the remainder of integer division. int a = 13; int v = 3; a/v // returns result 4 a%v // returns result 1 When used as a unary operator, “-” negates the numeric operand. int a = 13; -a // returns result -13 (b) Logical Operators The logical operators in Java include the standard and “&&”, or “||” and not “!”. Each operator returns a boolean result: && returns true if both operands are true. x y x && y false false false false true false true false false true true true || returns true if at least one operand is true. x y x || y false false false false true true true false true true true true ! returns true if the single operand is false. x ! x false true true false
  • 43. 26 Object-Oriented Programming and Java (c) Relational Operators The equality “==” and inequality “!=” operators in Java operate on all values and objects to return a boolean result. The following relational operators in Java operate on numeric values. < less than > greater than <= less than or equal >= greater than or equal (d) Bitwise Operators The following bitwise operators in Java operate on corresponding bits of byte, short, int and long values. & bitwise “and” ^ bitwise exclusive “or” | bitwise inclusive “or” ~ bitwise one’s complement int h = 4; int j = 4; int k = 6; Counter m = new Counter(); Counter n = new Counter(); h == j // returns true, h and j have the same value h == k // returns false k == k // returns true m == n // false, m and n are different objects even if they have the // same constituents n == n // true int h = 4; int j = 4; int k = 6; h < k // returns true h < j // returns false h <= j // returns true >> << right and left bitwise shift >>> right bitwise unsigned shift
  • 44. A Quick Tour of Java 27 (e) Assignment Having seen the basic means of providing new values to variables, assignment “=” is more correctly viewed as an operator rather than a statement. In addition to assigning the right-side value to the left-side variable, it also returns the value assigned. As such, the assignment expression may appear in the context of an enclos- ing expression. (In the example below, the result of the assignment operator to vari- able a is not used.) int a, b; a = b = 2; int a, b; a = (b = 2); The code fragments above assign 2 to b and the result of 2 is assigned to a. This is because unlike the common arithmetic operators which associates from left-to- right, the assignment operator associates from right-to-left. This is highlighted in the next section on operator precedence. In general, an assignment operator results in a side-effect since it changes the value of the variable being assigned. Other related assignment operators have the special form “op=”, where op is a typical operator. x op= f; x = x op f; implies has the same meaning as int a = 15; // binary 000001111 int v = 34; // binary 000100010 a & v // returns result 2 000000010 a ^ v // returns result 45 000101101 a | v // returns result 47 000101111 ~a // returns result -16 // 11111111111111111111111111110000 v >> 3 // returns result 4 000000100 v << 3 // returns result 272 100010000 ~a >> 3 // returns -2 // 11111111111111111111111111111110 ~a >>> 3 // returns 536870910 // 01111111111111111111111111111110
  • 45. 28 Object-Oriented Programming and Java In the above equivalent form, op may be operators such as +, -, *, /, %, >>, <<, &, ^ or |. Thus +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, and |= are also valid assign- ment operators.1 The other two operators related to assignment are auto-increment “++” and auto-decrement “––”. Since they are used in either postfix and prefix forms, four scenarios are as illustrated in the code fragments below. The postfix form (such as f++) returns the result before the incre- ment/decrement operation, whereas the prefix form (such as ++f) returns the results after the increment/decrement operation. In the code fragments below, f is either incremented or decremented. However, g is either assigned a “pre” or a “post” value depending on whether the prefix or postfix forms are used, respctively. int f, g; f = 6; g = f++; // g has 6 // f has 7 int f, g; f = 6; g = ++f; // g has 7 // f has 7 int f, g; f = 6; g = f--; // g has 6 // f has 5 int f, g; f = 6; g = --f; // g has 5 // f has 5 (f) Conditional Expression The conditional expression operator ? : returns one of two values depending on the boolean condition. For example, the expression A?B:C returns the value of B if A is true, else the value of C is returned. (g) Typecast The typecast operator (type)E performs 2 basic functions at run-time depend- ing on the source expression E. For a numeric type (such as int, float, or double), it converts the value to another of the specified type. 1 There is a subtle difference between x[i++] += 4 and x[i++] = x[i++] + 4, in that i++ is evaluated once in the former but twice in the latter.
  • 46. A Quick Tour of Java 29 int k = 5; double d = 4.16; k = (int) d*k; The resultant expression of d*k is double value, and the typecast operation converts it to an integer. For variable, the operator confirms that the object refer- enced is compatible with the specified class. (h) Precedence and Associativity Since most operators have operands that can be (nested) expressions, operator precedence and associativity rules are necessary to define the evaluation order. For example in evaluating “a+b*c”, “b*c” is evaluated before its result is added to a because multiplication “*” has higher precedence than addition “+”. The operators at the top of the table have higher precedence than those at the bottom. It is as though precedence pulls operands, so that operators with a higher precedence are evaluated before those with lower precedence. All binary operations are left-associative, except assignment operators which associate right-to-left. Table 3-1: Operator precedence. Operator [] . (params) E++ E-- unary operators: -E !E ~E ++E --E new (type)E * / % + - >> << >>> < > <= >= == != & ^ | && || ? : = += -= *= /= %= >>= <<= &= ^= |= Object x = new Counter(); Counter c; c = x; //illegalsincenotallObjectsareCounters c = (Counter) x; //legitimatebecausexisatrun-time // verifiedtoreferenceaCounter Table 3.1 summarizes the operators discussed so far.
  • 47. 30 Object-Oriented Programming and Java Precedence allows the expression “a>>b+c” to be unambiguously interpreted as “a>>(b+c)”, and not “(a>>b)+c”. Similarly, “!m&&n” is interpreted as “(!m)&&n” and not “!(m&&n)”. Associativity rules come into effect when equal precedence levels do not help in resolving evaluation order. Due to associativity rules (which is left-to-right for “/” and “*”, that is, evaluating the left operator and then right), “a/b*c” is interpreted as “(a/b)*c” and not “a/(b*c)”. Similarly, due to right-to-left associativity, “~y++” is interpreted as “~(y++)” instead of “(~y)++”. 3.8.2 Expression Statements The simplest and most common statements in Java are expression statements, which consist of an assignment expression, method invocation or instance creation followed by a semicolon. The following are expression statements: 3.8.3 Control-flow Statements Apart from the simple statements, there are control-flow statements that affect the execution order of statements. These statements are commonly grouped under condi- tional and iterative statements. (a) Conditional Statements Conditional statements allow for conditions to be attached to a statement as to whether it will be executed. The most basic form is the if statement. In the code fragment below, the statement S is executed only if the boolean condition E evalu- ates to true: A slight variation is the if-else statement which allows for an either-or choice. If the boolean condition E evaluates to is true and S is executed, then R would not. If S is not executed, then R would be: int a, b; T c; a = 1; // assignment expressions a++; c = new T(); new T(); // instance creation c.m(); // method invocation if (E) S;
  • 48. A Quick Tour of Java 31 Apart from one-way and two-way branches in flow-control, the switch state- ment allows for multi-way selection: Generally, the switch statement allows for the execution of a choice of state- ments depending on the expression E: S1 when E evaluates to the constant c1, S2 when c2, …, etc., the mappings given by each switch limb. The break statement causes flow-control to leave the switch statement immediately. In the case of the execution of statement S3 when E evaluates to c3, the absence of a break statement causes execution to continue to S4 instead. The default limb is used when the evaluated value of E does not match any constant values in the limbs. (b) Iterative Statements Iterative statements allow for constituent statements to be executed repeatedly. In the most basic way, the body of the while-statement below is repeatedly executed when the boolean condition E is true. The loop terminates when E is false, after which execution proceeds to the next statement: The while-statement is known as a pretest loop since the constituent S is only executed if the condition E evaluates to is true. Thus, if E was false in the first instance, the statement S is never executed. On the other hand, the do-while statement is a posttest loop. R is first executed and subsequently while the boolean expression F evaluates to true, R is executed again. Again, the loop terminates when F evaluates to false. Thus, this control flow construct will execute R at least once. if (E) S; else R; switch (E) { c1: S1; break; c2: S2; break; c3: S3; c4: S4; break; default: Sd; } while (E) S; do { R; } while (F);
  • 49. 32 Object-Oriented Programming and Java 3.9 Blocks A block, indicated by { }, may occur at any location where a statement is valid. It is considered the sequential construct as the group of statements it surrounds is treated as a single statement or processing unit. Thus, while the various control-flow constructs merely show a single statement as the constituent body, a block may be used where such constructs should contain more than one statement. For example, factorial may be computed by the following while-statement: Blocks allow for control-flow constructs to be nested within bigger constructs. In the code fragment below, the nested if-else statement allows for the number of even numbers and sum of odd numbers in the range to be computed. 3.9.1 Local Declarations In treating a statement sequence as a single statement, a block may also be thought of as a sub-machine which fulfills a specific task. As such, the scope of local variable declarations is the rest of the block in which the declaration occurs. This allows declarations and associated references to be localized, thereby aiding maintainability. f = 1; while (k > 1) { f = f*k; k--; } even = 0; sumOfOdd = 0; f = 1; while (k > 1) { f = f*k; if (k % 2 == 0) even++; else sumOfOdd = sumOfOdd + k; k--; } while (k > 1) { f = f*k; if (k % 2 == 0) { double d = 4.5; .... even++; } else { long d = 23546; ... sumOfOdd = sumOfOdd + k; } k--; }
  • 50. A Quick Tour of Java 33 The code fragment above is legitimate because both local declarations of d have been confined to their respective nested blocks – d is a double in the first block, while d is a long in the second. With instance variables, a local declaration has the same form below, where T is the declared type of variable v. T v; For notational convenience, declarations may have two variations: • a list of variables with the same type separated by commas; and • an initial value may be provided via an expression following an assignment operator T v, w = n(), z; 3.10 More Control-flow Statements Three other control-flow statements are commonly used: for-statement, break and continue. The for-statement is often used as a counter-controlled loop to iterate through a loop a fixed number of times, even though it does not have explicit mechanisms for counter control. For example, the earlier factorial example could be re-coded as follows: The generic form of the for-statement is often easier thought of as a transformed while-statement, where Q, T, and S are the initializer, conditional and re-initializer expressions: The break-statement was encountered when the switch-statement was dis- cussed. Its more generic function is to transfer control out of the innermost switch, while, do or for-statement. This is why using the break-statement ensures that only the statements associated with the case-limb are executed. for (f = 1; k > 1; k--) f = f*k; for (Q; R; S) T; Q; while (R) { T; S; }
  • 51. 34 Object-Oriented Programming and Java For the situation with the while, do or for-statements, the break-statement allows for a quick exit from the iteration. In many situations, its use can result in a simpler program structure. For example, the following two code fragments have similar effects. Finally, the continue-statement transfers control to the beginning of the inner- most iterative loop so as to reevaluate the boolean condition for the next iteration. Unlike, the break-statement, control-flow does not exit from the loop. As such, the following two code fragments have similar effects. While the differences between program structures in the above examples may seem mild for the break and continue statements to be useful, it is more pro- nounced for program structures that are deeply nested. 3.11 Arrays Just as objects are created dynamically (i.e., it happens at run-time during program execution), arrays in Java are similarly created. The size of an array need not be specified or computed during compilation. An array is thus declared using the subscript operator, but without indication of the upper bound: Counter gates[]; An array is created via the new operator, but with the array size within square brackets: finished = false; while (E && !finished) { S; if (F) { U; finished = true; } if (!finished) T; } while (E) { S; if (F) { U; break; } T; } while (E) { S; if (F) { U; continue; } T; } skip = false; while (E) { S; if (F) { U; skip = true; } if (!skip) T; else skip = false; }
  • 52. A Quick Tour of Java 35 gates = new Counter[8]; The array size associated with gates is 8, but this does not imply eight Counter objects. Instead, it is important to understand a Counter array as being similar with multiple variables, that is, it is an object that does not further contain Counter objects but merely references eight potential Counter objects. Thus, individual array elements must be created explicitly: 3.12 Result Returned by Method Now that we have examined the statement constructs in Java, we return to see how a method may return a result to its sender. A method in a class definition has the fol- lowing general form, with the return-statement returning control-flow back to the message sender: The value returned v, must be of the type T as indicated in the method signa- ture. If the sender does not require any results, the keyword void should be used as the return type. In this case, the returning expression v would be omitted in the return statement. The return-statement need not be the last statement in the block as implied in the previous example. In a non-trivial structure, multiple return- statements might be used as in the next example, but the programmer must evaluate if the situation improves program structure and readability. Counter gates[]; gates = new Counter[8]; for (int i=0; i<8; i++); gates[i] = new Counter(); T foo(gT g, hT h ...) { // local definitions // statements return v; } T foo(gT g, hT h ...) { for (E; F; G) if (H) return v; else if (J) { b; return w; } return x; }
  • 53. 36 Object-Oriented Programming and Java 3.13 Summary In this chapter, we discussed: • Primitive types in Java. • class constructs. • Definition of instance variables and methods. • Object instantiation. • Message passing and expressions. • Statements and control-flow mechanisms. Generally, these constructs are representative of what Java offers. The class construct is key in Java because it allows for objects to be defined to model the prob- lem domain. Below that, variables and methods are defined, which correspond to data and code. Code abstraction result in hierarchical statement blocks (with optional local variables) and control flow mechanisms. Figure 3-1 illustrates this hierarchy. Java application primitive values objects class definitions consists of defined by instance variables instance methods consists of local variables statements assignment control flow message passing Figure 3-1: Hierarchical relationships of Java constructs. 3.14 Exercises 1. Which of the following are valid variable names in Java? _object object–oriented
  • 54. A Quick Tour of Java 37 object_oriented object.oriented $java java integer string Int 933 fm90.5 1fm 2. Define a Square class with the length of its side as an instance vari- able. Include an appropriate constructor method and methods to enlarge an instance as well as compute its area. 3. Using the Square class in Question 2, create ten randomly sized squares and find the sum of their areas. (The method Math.random() returns a random number between 0.0 and 1.0 each time it is invoked.) 4. Add the functionality for a Square object to draw itself via ASCII characters. For example, a Square of length 4 can be drawn as: or: 5. Find a number with nine digits d1d2d3,…, d9 such that the sub-string number d1, …, dn is divisible by n, 1<=n<=9. Note that each of the digits may be used once. The System.out.print() and System.out.println() methods may be useful. XXXX X++X X++X XXXX * * * * **** ****
  • 55. Another Random Scribd Document with Unrelated Content
  • 56. Plantaginaceæ, 408, 424 Plantago, 408 Plants, classification, 343, 347 Plate-gilled Molluscs, 191 Pleuronectes, 326 Pleuronectidæ, 324 Plocamium, 61, 366 Plumbaginaceæ, 408, 424 Poa, 396 Podded Sea-oak, 388 Podophthalmata, 266, 269, 304 Pogge, 335 Pollack, 327 Polybius, 293 Polycarpon, 413 Polychæta, 177 Polygala, 416 Polygalaceæ, 416, 426 Polygonaceæ, 404, 424 Polygonum, 404 Polypetalæ, 403 Polypogon, 397 Polysiphonia, 372 Polystomata, 115 Polyzoa, 188 Porcelain Crab, 280 Porcellana, 280 Porifera, 115 Porphyra, 355 Porpoise, 339 Portland Spurge, 403 Portunus, 292 Prawn, 44, 278 Preservation of marine objects, 71 Preservatives, 72 Prickly Cockle, 215 Prickly Salt-wort, 407 Primulaceæ, 424 Prosobranchiata, 232, 236 Protophyta, 343, 347 Protoplasm, 102 Protoplasta, 104, 110 Protozoa, 102
  • 57. — classification, 104 Psammobia, 208 Pteropoda, 230, 255 Pulmonifera, 255 Punctaria, 383 Puncturella, 241 Purple Spurge, 403 Purple-tipped Urchin, 168 Purpura, 249 Pycnogonum, 293 Pyramidellidæ, 246, 255 Radiata, 140 Radiolaria, 104, 110 Ragworm, 40, 179 Raiidæ, 318 Ranunculaceæ, 422, 426 Raphanus, 420 Rays, 318 Red Mullets, 338 Red-specked Pimplet, 150 Reptilia, 307 Reseda, 417 Resedaceæ, 417, 426 Rhizocarpeæ, 345, 348 Rhizopods, 104 Rhizostoma, 136 Rhodomela, 372 Rhodomelaceæ, 372, 390 Rhodophyllis, 61 Rhodospermeæ, 350, 355, 389 Rhodymenia, 61, 365, 367 Rhodymeniaceæ, 365, 389 Rhombus, 326 Rhynchota, 297, 305 Rissoa, 244 Rock-fishes, 46 Rocklings, 328 Rock-pools, 6, 31 Rosy Anemone, 149 Rosy Feather Star, 160 Rotifers, 189
  • 58. Rushes, 400 Rytiphlæa, 375 Sabella, 184 Saddle Oyster, 222 Sagartia, 146 Sagina, 416 Salicornia, 407 Salmo, 321 Salmon, 321 Salmon Dace, 339 Salmonidæ, 321 Salsola, 407 Salt-wort, 407 Sand Eels, 326 Sandhoppers, 268 — preserving, 81 Sand Smelts, 332 Sandworm, 178 Saxicava, 203 Scalaria, 244 Scallops, 222 Scentless Mayweed, 411 Schizopoda, 304 Schizymenia, 61, 364 Scirpus, 399 Scomber, 337 Scomberidæ, 337 Scorpionidæ, 304 Scorpion Spider-crab, 289 Scurvy Grass, 419 Scylliidæ, 319 Scyllium, 319 Sea angling, 34 — Aster, 410 — Buckthorn, 403 — Bullheads, 335 — Bream, 338 — Campion, 415 — Carrot, 411 — Cat, 334 — Cat’s-tail Grass, 397
  • 59. — Cucumbers, 169 — Devil, 336 — Eggs, 165 — — preserving, 79 — Girdles, 384 — Grass, 61, 353, 400 — Hard-grass, 395 — Holly, 412 — Kale, 420 — Lavender, 409 — Lemons, 233 — Lettuce, 61 — Loach, 328 — Lyme-grass, 395 — Mallow, 415 — Mat, 188 — Meadow Grass, 396 — Mouse, 179 — Pearl-wort, 416 — Perch, 338 — Pill-ball, 268 — Pink, 408 — Purslane, 406, 416 — Radish, 420 — Reed, 396 — Rocket, 420 — Rushes, 400 — Salt, 17, 59 — Saltness of, 17 — Samphire, 411 — Sand-wort, 415 — Sedge, 398 — Slater, 268 — Slugs, 233 — Snails, 331 — Spurge, 403 — Squirts, 188 — Stock, 418 — Stork’s-bill, 414 — Urchins, 157, 165 — — preserving, 79 — — shell of, 166 — teeth, 167
  • 60. — water, artificial, 59 — composition, 59 — weeds, 343 — — classification, 389 — — preserving, 86 — Wormwood, 410 Seaside Arrow Grass, 401 — Bindweed, 409 — Cottonweed, 410 — Feverfew, 411 — Grasses, 392 — Knot Grass, 404 — Plantain, 408 — plants, 391 — classification, 423 Section cutting, 96 Sedges, 398 Selaginellales, 345, 348 Sepia, 253 Sepiadæ, 253, 255 Sepiola, 252 Serpula, 185 Serranidæ, 338 Serrated Pill-ball, 268 Serrated Wrack, 386 Sertularia, 128 Sessile-eyed crustaceans, 266 Shanny, 333 Sharks, 318 Shells, preserving, 83 Shore Crab, 261, 291 — Spider, 293 Shrimps, 278 — preserving, 81 Shrubby Mignonette, 417 Silene, 415 Silicia, 122 Siphonaceæ, 358, 389 Siphonida, 198, 255 Siphonostomata, 236, 247, 255 Six-rayed Sponges, 119 Skates, 318 Slender-beaked Crab, 289
  • 61. Sloke, 61, 355 Smelt, 321 Smooth Hound, 320 Snoods, 37 Solanaceæ, 409, 424 Solanum, 409 Soldier Crab, 280 Sole, 326 Solea, 326 Solecurtus, 207 Solenidæ, 255 Sparidæ, 338 Spartina, 397 Sparus, 338 Spergularia, 415 Sphacelaria, 279 Sphærococcoideæ, 366, 390 Sphærococcus, 366 Sphæroma, 268 Spicules, 118 Spider Crabs, 288 Spike Rush, 399 Spiny-finned fishes, 329 Spirorbis, 187 Sponges, 115 Spongiocarpeæ, 390 Spoon Worms, 176 Sporochnaceæ, 385, 390 Sporochnus, 385 Spotted Dogfish, 320 Spotted Hog-louse, 268 Spout Shell, 245 Sprats, 323 Spring-tails, 299 Spurges, 403 Spyridia, 363 Spyridiaceæ, 368, 389 Squamariæ, 390 Squid, 252 Squirt Worms, 176 Stalk-eyed crustaceans, 266, 269 Starfishes, 157 — preserving, 79
  • 62. Stargazers, 336 Statice, 408 Stenorhynchus, 289 Sticklebacks, 331 Stilophora, 383 Sting Bull, 337 Sting Fish, 335 Stock, 418 Stomopoda, 269, 304 Stone Crab, 280 Strawberry Beadlet, 142 Sucker Fishes, 330 Sweet Alyssum, 419 Swimming Crab, 293 Sycon, 121 Syngnathidæ, 328 Syngnathus, 329 Tamariscaceæ, 413, 425 Tamarisk, 413 Tangles, 384 Tapes, 211 Tealia, 143 Tectibranchiata, 238, 255 Tectibranchs, 236 Teleostomi, 318, 320 Tellina, 208 Tellinidæ, 207, 255 Terebella, 181 Terebratulina, 225 Teredo, 201 Tetrabranchiata, 255 Thalictrum, 421 Thallophytes, 343, 344, 347 Trichoptera, 305 Thornback Crab, 289 Thracia, 204 Thrift, 408 Thuiaria, 132 Thysanoptera, 298, 305 Tides, 9 Tooth shells, 238
  • 63. Top shells, 243 Trachinidæ, 336 Trachinus, 337 Treacle Mustard, 418 Tree Mallow, 415 Trefoil, 413 Trifolium, 413 Triglochin, 401 Triopa, 235 Tritonia, 235 Tritoniadæ, 235 Trivia, 248 Trochus, 243 Trumpet Anemone, 141 Tubularia, 132 Tunicates, 188 Turbellaria, 175 Turbinidæ, 243, 255 Turbot, 326 Turkey-feather Laver, 382 Turret shells, 245 Turritella, 244 Turritellidæ, 244, 255 Twin-bladder Wrack, 387 Two-spotted Sucker, 331 Ulva, 61, 354 Ulvaceæ, 389, 354 Umbelliferæ, 411, 425 Umbilicus, 226 Umbo, 193 Vascular cryptogams, 345 Velutina, 247 Velvet Crab, 292 Veneridæ, 210, 255 Venus, 210 Vermes, 172 Vertebrates, 306 Vetch, 413 Vicia, 413
  • 64. Viola, 417 Violaceæ, 417, 426 Violet Fiddler, 292 Water Ferns, 345 Weavers, 336 Wedge shells, 208 Whales, 340 Wheel animals, 189 Whelks, 248 Whirl Worms, 175 Whistle Fish, 328 Whitebait, 323 White Salmon, 339 Whiting, 327 Wild Cabbage, 418 Wild Celery, 412 Wing shells, 219 Wolf Fish, 334 Woody Nightshade, 409 Worms, 172 — parasitic, 174 Worm Pipe-fish, 329 Wrangeliaceæ, 389 Wrasses, 329 Xantho, 292 Xylophaga, 201 Yellow Poppy, 420 Zeus, 338 Zoantharia, 138 Zoarces, 333 Zonaria, 382 Zostera, 353, 400
  • 65. Printed in England at The Ballantyne Press Spottiswoode, Ballantyne & Co. Ltd. Colchester, London & Eton
  • 66. Transcriber’s Note Minor inconsistencies in punctuation of tables or captions are silently corrected. Hyphenation is variable. Those compound words which are hyphenated only on line breaks are rendered using modern usage. The word ‘movable’ appears only once as ‘moveable’ (165), which is retained. The index entry for 'Œpophilus' is considered to be an error. All instances of the word appear in the text as 'Æpophilus'. This has been corrected and moved to the appropriate alphabetic position. The following corrections were made to obvious printer’s errors: devel[e/o]ped (336); co[n/m]posed (364). The following list contains punctuation corrections made: p. 65 one of them[.] Added. p. 255 [Class] LAMELLIBRANCHIATA Added to match other entries. p. 257 their tendencies[,/.] Corrected. p. 292 low-water[-]mark Unhyphenated elsewhere. p. 340 [(]Cetacea) Added. p. 390 in firm gelatine[,/.] Corrected. p. 403 by its stipuled leaves[.] Added. p. 434 Rhodospermeæ, 350, 355, 38[9] Added.
  • 67. *** END OF THE PROJECT GUTENBERG EBOOK THE SEA SHORE *** Updated editions will replace the previous one—the old editions will be renamed. Creating the works from print editions not protected by U.S. copyright law means that no one owns a United States copyright in these works, so the Foundation (and you!) can copy and distribute it in the United States without permission and without paying copyright royalties. Special rules, set forth in the General Terms of Use part of this license, apply to copying and distributing Project Gutenberg™ electronic works to protect the PROJECT GUTENBERG™ concept and trademark. Project Gutenberg is a registered trademark, and may not be used if you charge for an eBook, except by following the terms of the trademark license, including paying royalties for use of the Project Gutenberg trademark. If you do not charge anything for copies of this eBook, complying with the trademark license is very easy. You may use this eBook for nearly any purpose such as creation of derivative works, reports, performances and research. Project Gutenberg eBooks may be modified and printed and given away—you may do practically ANYTHING in the United States with eBooks not protected by U.S. copyright law. Redistribution is subject to the trademark license, especially commercial redistribution. START: FULL LICENSE
  • 68. THE FULL PROJECT GUTENBERG LICENSE
  • 69. PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK To protect the Project Gutenberg™ mission of promoting the free distribution of electronic works, by using or distributing this work (or any other work associated in any way with the phrase “Project Gutenberg”), you agree to comply with all the terms of the Full Project Gutenberg™ License available with this file or online at www.gutenberg.org/license. Section 1. General Terms of Use and Redistributing Project Gutenberg™ electronic works 1.A. By reading or using any part of this Project Gutenberg™ electronic work, you indicate that you have read, understand, agree to and accept all the terms of this license and intellectual property (trademark/copyright) agreement. If you do not agree to abide by all the terms of this agreement, you must cease using and return or destroy all copies of Project Gutenberg™ electronic works in your possession. If you paid a fee for obtaining a copy of or access to a Project Gutenberg™ electronic work and you do not agree to be bound by the terms of this agreement, you may obtain a refund from the person or entity to whom you paid the fee as set forth in paragraph 1.E.8. 1.B. “Project Gutenberg” is a registered trademark. It may only be used on or associated in any way with an electronic work by people who agree to be bound by the terms of this agreement. There are a few things that you can do with most Project Gutenberg™ electronic works even without complying with the full terms of this agreement. See paragraph 1.C below. There are a lot of things you can do with Project Gutenberg™ electronic works if you follow the terms of this agreement and help preserve free future access to Project Gutenberg™ electronic works. See paragraph 1.E below.
  • 70. 1.C. The Project Gutenberg Literary Archive Foundation (“the Foundation” or PGLAF), owns a compilation copyright in the collection of Project Gutenberg™ electronic works. Nearly all the individual works in the collection are in the public domain in the United States. If an individual work is unprotected by copyright law in the United States and you are located in the United States, we do not claim a right to prevent you from copying, distributing, performing, displaying or creating derivative works based on the work as long as all references to Project Gutenberg are removed. Of course, we hope that you will support the Project Gutenberg™ mission of promoting free access to electronic works by freely sharing Project Gutenberg™ works in compliance with the terms of this agreement for keeping the Project Gutenberg™ name associated with the work. You can easily comply with the terms of this agreement by keeping this work in the same format with its attached full Project Gutenberg™ License when you share it without charge with others. 1.D. The copyright laws of the place where you are located also govern what you can do with this work. Copyright laws in most countries are in a constant state of change. If you are outside the United States, check the laws of your country in addition to the terms of this agreement before downloading, copying, displaying, performing, distributing or creating derivative works based on this work or any other Project Gutenberg™ work. The Foundation makes no representations concerning the copyright status of any work in any country other than the United States. 1.E. Unless you have removed all references to Project Gutenberg: 1.E.1. The following sentence, with active links to, or other immediate access to, the full Project Gutenberg™ License must appear prominently whenever any copy of a Project Gutenberg™ work (any work on which the phrase “Project
  • 71. Gutenberg” appears, or with which the phrase “Project Gutenberg” is associated) is accessed, displayed, performed, viewed, copied or distributed: This eBook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. 1.E.2. If an individual Project Gutenberg™ electronic work is derived from texts not protected by U.S. copyright law (does not contain a notice indicating that it is posted with permission of the copyright holder), the work can be copied and distributed to anyone in the United States without paying any fees or charges. If you are redistributing or providing access to a work with the phrase “Project Gutenberg” associated with or appearing on the work, you must comply either with the requirements of paragraphs 1.E.1 through 1.E.7 or obtain permission for the use of the work and the Project Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9. 1.E.3. If an individual Project Gutenberg™ electronic work is posted with the permission of the copyright holder, your use and distribution must comply with both paragraphs 1.E.1 through 1.E.7 and any additional terms imposed by the copyright holder. Additional terms will be linked to the Project Gutenberg™ License for all works posted with the permission of the copyright holder found at the beginning of this work. 1.E.4. Do not unlink or detach or remove the full Project Gutenberg™ License terms from this work, or any files
  • 72. containing a part of this work or any other work associated with Project Gutenberg™. 1.E.5. Do not copy, display, perform, distribute or redistribute this electronic work, or any part of this electronic work, without prominently displaying the sentence set forth in paragraph 1.E.1 with active links or immediate access to the full terms of the Project Gutenberg™ License. 1.E.6. You may convert to and distribute this work in any binary, compressed, marked up, nonproprietary or proprietary form, including any word processing or hypertext form. However, if you provide access to or distribute copies of a Project Gutenberg™ work in a format other than “Plain Vanilla ASCII” or other format used in the official version posted on the official Project Gutenberg™ website (www.gutenberg.org), you must, at no additional cost, fee or expense to the user, provide a copy, a means of exporting a copy, or a means of obtaining a copy upon request, of the work in its original “Plain Vanilla ASCII” or other form. Any alternate format must include the full Project Gutenberg™ License as specified in paragraph 1.E.1. 1.E.7. Do not charge a fee for access to, viewing, displaying, performing, copying or distributing any Project Gutenberg™ works unless you comply with paragraph 1.E.8 or 1.E.9. 1.E.8. You may charge a reasonable fee for copies of or providing access to or distributing Project Gutenberg™ electronic works provided that: • You pay a royalty fee of 20% of the gross profits you derive from the use of Project Gutenberg™ works calculated using the method you already use to calculate your applicable taxes. The fee is owed to the owner of the Project Gutenberg™ trademark, but he has agreed to donate royalties under this paragraph to the Project Gutenberg Literary Archive Foundation. Royalty
  • 73. payments must be paid within 60 days following each date on which you prepare (or are legally required to prepare) your periodic tax returns. Royalty payments should be clearly marked as such and sent to the Project Gutenberg Literary Archive Foundation at the address specified in Section 4, “Information about donations to the Project Gutenberg Literary Archive Foundation.” • You provide a full refund of any money paid by a user who notifies you in writing (or by e-mail) within 30 days of receipt that s/he does not agree to the terms of the full Project Gutenberg™ License. You must require such a user to return or destroy all copies of the works possessed in a physical medium and discontinue all use of and all access to other copies of Project Gutenberg™ works. • You provide, in accordance with paragraph 1.F.3, a full refund of any money paid for a work or a replacement copy, if a defect in the electronic work is discovered and reported to you within 90 days of receipt of the work. • You comply with all other terms of this agreement for free distribution of Project Gutenberg™ works. 1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™ electronic work or group of works on different terms than are set forth in this agreement, you must obtain permission in writing from the Project Gutenberg Literary Archive Foundation, the manager of the Project Gutenberg™ trademark. Contact the Foundation as set forth in Section 3 below. 1.F. 1.F.1. Project Gutenberg volunteers and employees expend considerable effort to identify, do copyright research on, transcribe and proofread works not protected by U.S. copyright
  • 74. law in creating the Project Gutenberg™ collection. Despite these efforts, Project Gutenberg™ electronic works, and the medium on which they may be stored, may contain “Defects,” such as, but not limited to, incomplete, inaccurate or corrupt data, transcription errors, a copyright or other intellectual property infringement, a defective or damaged disk or other medium, a computer virus, or computer codes that damage or cannot be read by your equipment. 1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the “Right of Replacement or Refund” described in paragraph 1.F.3, the Project Gutenberg Literary Archive Foundation, the owner of the Project Gutenberg™ trademark, and any other party distributing a Project Gutenberg™ electronic work under this agreement, disclaim all liability to you for damages, costs and expenses, including legal fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE. 1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a defect in this electronic work within 90 days of receiving it, you can receive a refund of the money (if any) you paid for it by sending a written explanation to the person you received the work from. If you received the work on a physical medium, you must return the medium with your written explanation. The person or entity that provided you with the defective work may elect to provide a replacement copy in lieu of a refund. If you received the work electronically, the person or entity providing it to you may choose to give you a second opportunity to receive the work electronically in lieu of a refund.
  • 75. If the second copy is also defective, you may demand a refund in writing without further opportunities to fix the problem. 1.F.4. Except for the limited right of replacement or refund set forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE. 1.F.5. Some states do not allow disclaimers of certain implied warranties or the exclusion or limitation of certain types of damages. If any disclaimer or limitation set forth in this agreement violates the law of the state applicable to this agreement, the agreement shall be interpreted to make the maximum disclaimer or limitation permitted by the applicable state law. The invalidity or unenforceability of any provision of this agreement shall not void the remaining provisions. 1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the trademark owner, any agent or employee of the Foundation, anyone providing copies of Project Gutenberg™ electronic works in accordance with this agreement, and any volunteers associated with the production, promotion and distribution of Project Gutenberg™ electronic works, harmless from all liability, costs and expenses, including legal fees, that arise directly or indirectly from any of the following which you do or cause to occur: (a) distribution of this or any Project Gutenberg™ work, (b) alteration, modification, or additions or deletions to any Project Gutenberg™ work, and (c) any Defect you cause. Section 2. Information about the Mission of Project Gutenberg™
  • 76. Project Gutenberg™ is synonymous with the free distribution of electronic works in formats readable by the widest variety of computers including obsolete, old, middle-aged and new computers. It exists because of the efforts of hundreds of volunteers and donations from people in all walks of life. Volunteers and financial support to provide volunteers with the assistance they need are critical to reaching Project Gutenberg™’s goals and ensuring that the Project Gutenberg™ collection will remain freely available for generations to come. In 2001, the Project Gutenberg Literary Archive Foundation was created to provide a secure and permanent future for Project Gutenberg™ and future generations. To learn more about the Project Gutenberg Literary Archive Foundation and how your efforts and donations can help, see Sections 3 and 4 and the Foundation information page at www.gutenberg.org. Section 3. Information about the Project Gutenberg Literary Archive Foundation The Project Gutenberg Literary Archive Foundation is a non- profit 501(c)(3) educational corporation organized under the laws of the state of Mississippi and granted tax exempt status by the Internal Revenue Service. The Foundation’s EIN or federal tax identification number is 64-6221541. Contributions to the Project Gutenberg Literary Archive Foundation are tax deductible to the full extent permitted by U.S. federal laws and your state’s laws. The Foundation’s business office is located at 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up to date contact information can be found at the Foundation’s website and official page at www.gutenberg.org/contact
  • 77. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com