Beginning Java Objects: From Concepts to Code, 3rd Edition

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

As a programming language, Java's object-oriented nature is key to creating powerful, reusable code and applications that are easy to maintain and extend. That being said, many people learn Java syntax without truly understanding its object-oriented roots, setting them up to fail to harness all of the power of Java. This book is your key to learning both! This new third edition of Beginning Java Objects: From Concepts to Code discusses Java syntax, object principles, and how to properly structure the requirements of an application around an object architecture. It is unique in that it uses a single case study of a Student Registration System throughout the book, carrying the reader from object concepts, to object modeling, to building actual code for a full-blown application. A new chapter covers a technology-neutral discussion of the principles of building a three-tier architecture using Java, introducing the notion of model layer – presentation layer – data layer separation. Time and again, I meet software developers—at my place of employment, at clients’ offices, at professional conferences, on college campuses—who have attempted to master an object-oriented programming language (OOPL) like Java by taking a course in Java, reading a book about Java, or installing and using a Java integrated development environment (IDE) such as Eclipse, IntelliJ IDEA, NetBeans, or BlueJ. However, there is something fundamentally missing from virtually all of these approaches: a basic understanding of what objects are all about and, more importantly, knowledge of how to structure a software application from the ground up to make the most of objects. If you’re already experienced with the Java language (but not with object fundamentals), it’s critical to your successful use of the language that you learn about its object-oriented roots. On the other hand, if you’re a newcomer to Java, then this book will get you properly “jump-started.” Either way, this book is a “must-read” for anyone who wishes to become proficient with an OO programming language like Java. Coding examples used throughout the book are Java version-neutral. The core object-oriented principles that you will learn from this book are timeless, and are relevant to all versions of the Java language, as well as to many other object-oriented languages. The book can be used for individual self-study or as a university-level textbook. What You Will Learn: Know basic object-oriented principles, from the simplest notion of classes and objects through the power of encapsulation, abstract classes, and polymorphism Approach the requirements for an application to structure it properly around objects Render the resultant object model into Java code, building a complete functioning model layer for the Student Registration System case study Conceptually round out an object layer by adding presentation and data layers Who This Book Is For: Software developers who have never tackled Java as a programming language, as well as those who have already used Java but want to ensure that they are taking full advantage of the object-oriented nature of the language. Even if you’ve already developed a full-fledged Java application, it’s certainly not too late to read this book if you still feel fuzzy when it comes to the object aspects of structuring an application; it ultimately makes someone a better Java programmer to know the “whys” of object orientation rather than merely the mechanics of the language. You’ll most likely see some familiar landmarks (in the form of Java code examples) in this book, but will hopefully gain many new insights as you learn the rationale for why we do many of the things that we do when programming in Java (or any other OO programming language for that matter). Because this book has its roots in courses that I teach at the university level, it’s ideally suited for use as a textbook for a semester-long university or advanced placement high school course in either object modeling or Java programming.

Author(s): Jacquie Barker
Edition: 3
Publisher: Apress
Year: 2023

Language: English
Pages: 845

About the Author ...................................................................................................xvii
About the Technical Reviewer ................................................................................xix
Preface ...................................................................................................................xxi
Introduction ..........................................................................................................xxiii
Student Registration System (SRS) Case Study ..................................................xxxv
Part I: The ABCs of Objects .............................................................................1
Chapter 1: Abstraction and Modeling ....................................................................... 3
Simplification Through Abstraction ............................................................................................... 3
Generalization Through Abstraction .............................................................................................. 5
Organizing Abstractions into Classification Hierarchies .......................................................... 5
Abstraction as the Basis for Software Development ............................................................. 10
Reuse of Abstractions ................................................................................................................. 11
Inherent Challenges .................................................................................................................... 13
What Does It Take to Be a Successful Object Modeler? ........................................................ 14
Summary .................................................................................................................................... 17
Chapter 2: Some Java Basics ................................................................................. 21
Java Is Architecture Neutral ........................................................................................................ 22
Anatomy of a Simple Java Program ............................................................................................ 27
Comments ............................................................................................................................. 28
The Class Declaration ............................................................................................................ 30
The main Method ................................................................................................................... 31
Setting Up a Simple Java Development Environment ................................................................. 32
vi
The Mechanics of Java ............................................................................................................... 32
Compiling Java Source Code into Bytecode .......................................................................... 32
Executing Bytecode ............................................................................................................... 33
Primitive Types ............................................................................................................................ 34
Variables ..................................................................................................................................... 36
Variable Naming Conventions ................................................................................................ 37
Variable Initialization ................................................................................................................... 39
The String Type ........................................................................................................................... 40
Case Sensitivity ........................................................................................................................... 41
Java Expressions ........................................................................................................................ 42
Arithmetic Operators ............................................................................................................. 43
Relational and Logical Operators ........................................................................................... 45
Evaluating Expressions and Operator Precedence ................................................................ 46
The Type of an Expression ..................................................................................................... 48
Automatic Type Conversions and Explicit Casting ....................................................................... 48
Loops and Other Flow Control Structures ................................................................................... 51
if Statements ......................................................................................................................... 52
switch Statements ................................................................................................................. 55
for Statements ....................................................................................................................... 58
while Statements .................................................................................................................. 61
Jump Statements .................................................................................................................. 63
Block-Structured Languages and the Scope of a Variable .......................................................... 65
Printing to the Console Window .................................................................................................. 67
print vs. println ...................................................................................................................... 69
Escape Sequences ................................................................................................................ 71
Elements of Java Style ................................................................................................................ 72
Proper Use of Indentation ...................................................................................................... 72
Use Comments Wisely ........................................................................................................... 76
Placement of Braces ............................................................................................................. 77
Descriptive Variable Names ................................................................................................... 78
Summary .................................................................................................................................... 78
vii
Chapter 3: Objects and Classes .............................................................................. 81
Software at Its Simplest .............................................................................................................. 81
Functional Decomposition ..................................................................................................... 82
The Object-Oriented Approach .............................................................................................. 85
What Is an Object? ...................................................................................................................... 85
State/Data/Attributes ............................................................................................................. 87
Behavior/Operations/Methods ............................................................................................... 89
What Is a Class? .......................................................................................................................... 91
A Note Regarding Naming Conventions ................................................................................. 92
Declaring a Class, Java Style ................................................................................................. 93
Instantiation ................................................................................................................................ 94
Encapsulation ............................................................................................................................. 96
User-Defined Types and Reference Variables ............................................................................. 97
Naming Conventions for Reference Variables ....................................................................... 99
Instantiating Objects: A Closer Look .......................................................................................... 100
Garbage Collection .............................................................................................................. 110
Objects As Attributes ................................................................................................................. 111
A Compilation “Trick”: “Stubbing Out” Classes ................................................................... 115
Composition ......................................................................................................................... 118
The Advantages of References As Attributes ....................................................................... 120
Three Distinguishing Features of an Object-Oriented Programming Language ........................ 121
Summary .................................................................................................................................. 121
Chapter 4: Object Interactions .............................................................................. 125
Events Drive Object Collaboration ............................................................................................. 126
Declaring Methods .................................................................................................................... 128
Method Headers .................................................................................................................. 129
Method Naming Conventions .............................................................................................. 129
Passing Arguments to Methods ........................................................................................... 130
Method Return Types ........................................................................................................... 131
An Analogy ........................................................................................................................... 133
Method Bodies ..................................................................................................................... 134
Features May Be Declared in Any Order .............................................................................. 135
return Statements ............................................................................................................... 136
Methods Implement Business Rules ......................................................................................... 141
Objects As the Context for Method Invocation .......................................................................... 142
Java Expressions, Revisited ................................................................................................ 146
Capturing the Value Returned by a Method ......................................................................... 147
Method Signatures .............................................................................................................. 148
Choosing Descriptive Method Names .................................................................................. 150
Method Overloading .................................................................................................................. 151
Message Passing Between Objects .......................................................................................... 153
Delegation ................................................................................................................................. 156
Obtaining Handles on Objects ................................................................................................... 157
Objects As Clients and Suppliers .............................................................................................. 162
Information Hiding/Accessibility ............................................................................................... 165
Public Accessibility .............................................................................................................. 166
Private Accessibility ............................................................................................................. 168
Publicizing Services ............................................................................................................ 169
Method Headers, Revisited .................................................................................................. 171
Accessing the Features of a Class from Within Its Own Methods ....................................... 171
Accessing Private Features from Client Code ........................................................................... 176
Declaring Accessor Methods ............................................................................................... 176
Recommended “Get”/“Set” Method Headers ...................................................................... 178
IDE-Generated Get/Set Methods .......................................................................................... 182
The “Persistence” of Attribute Values .................................................................................. 183
Using Accessor Methods from Client Code .......................................................................... 183
The Power of Encapsulation Plus Information Hiding ............................................................... 184
Preventing Unauthorized Access to Encapsulated Data ...................................................... 185
Helping Ensure Data Integrity .............................................................................................. 185
Limiting “Ripple Effects” When Private Features Change ................................................... 188
Using Accessor Methods from Within a Class’s Own Methods ............................................ 191
Exceptions to the Public/Private Rule ....................................................................................... 197
Constructors .............................................................................................................................. 201
Default Constructors ............................................................................................................ 201
Writing Our Own Explicit Constructors ................................................................................ 202
Passing Arguments to Constructors .................................................................................... 203
Replacing the Default Parameterless Constructor .............................................................. 205
More Elaborate Constructors ............................................................................................... 206
Overloading Constructors .................................................................................................... 208
An Important Caveat Regarding the Default Constructor .................................................... 210
Using the “this” Keyword to Facilitate Constructor Reuse .................................................. 212
Software at Its Simplest, Revisited ........................................................................................... 216
Summary .................................................................................................................................. 218
Chapter 5: Relationships Between Objects ........................................................... 223
Associations and Links ............................................................................................................. 224
Multiplicity ........................................................................................................................... 227
Multiplicity and Links .......................................................................................................... 229
Aggregation and Composition ................................................................................................... 232
Inheritance ................................................................................................................................ 234
Responding to Shifting Requirements with a New Abstraction ........................................... 234
(Inappropriate) Approach #1: Modify the Student Class ...................................................... 235
(Inappropriate) Approach #2: “Clone” the Student Class to Create a GraduateStudent
Class .................................................................................................................................... 239
The Proper Approach (#3): Taking Advantage of Inheritance ............................................... 241
The “is a” Nature of Inheritance .......................................................................................... 242
The Benefits of Inheritance ................................................................................................. 246
Class Hierarchies ................................................................................................................. 247
The Object Class .................................................................................................................. 250
Is Inheritance Really a Relationship? .................................................................................. 250
Avoiding “Ripple Effects” in a Class Hierarchy .................................................................... 251
Rules for Deriving Classes: The “Do’s” ................................................................................ 252
Overriding ............................................................................................................................ 252
Reusing Superclass Behaviors: The “super” Keyword ........................................................ 256
Rules for Deriving Classes: The “Don’ts” ............................................................................. 260
Private Features and Inheritance ........................................................................................ 262
Inheritance and Constructors .............................................................................................. 267
A Few Words About Multiple Inheritance ............................................................................. 275
Three Distinguishing Features of an OOPL, Revisited ............................................................... 280
Summary .................................................................................................................................. 280
Chapter 6: Collections of Objects ......................................................................... 285
What Are Collections? ............................................................................................................... 286
Collections Are Defined by Classes and Must Be Instantiated ............................................ 286
Collections Organize References to Other Objects .............................................................. 287
Collections Are Encapsulated .............................................................................................. 289
Three Generic Types of Collection ............................................................................................. 290
Ordered Lists ....................................................................................................................... 290
Dictionaries ......................................................................................................................... 292
Sets ..................................................................................................................................... 293
Arrays As Simple Collections .................................................................................................... 295
Declaring and Instantiating Arrays ...................................................................................... 295
Accessing Individual Array Elements ................................................................................... 297
Initializing Array Contents .................................................................................................... 298
Manipulating Arrays of Objects ........................................................................................... 300
A More Sophisticated Type of Collection: The ArrayList Class ................................................... 305
Using the ArrayList Class: An Example ................................................................................ 306
Import Directives and Packages .......................................................................................... 306
The Namespace of a Class .................................................................................................. 310
User-Defined Packages and the Default Package ............................................................... 313
Generics .............................................................................................................................. 314
ArrayList Features ............................................................................................................... 315
Iterating Through ArrayLists ................................................................................................ 318
Copying the Contents of an ArrayList into an Array ............................................................. 319
The HashMap Collection Class .................................................................................................. 321
The TreeMap Class .................................................................................................................... 329
The Same Object Can Be Simultaneously Referenced by Multiple Collections ......................... 332
Inventing Our Own Collection Types .......................................................................................... 334
Approach #1: Designing a New Collection Class from Scratch .......................................... 334
Approach #2: Extending a Predefined Collection Class (MyIntCollection) ........................... 335
Approach #3: Encapsulating a Standard Collection (MyIntCollection2) ............................... 341
Trade-Offs of Approach #2 vs. Approach #3 ........................................................................ 346
Collections As Method Return Types ......................................................................................... 348
Collections of Derived Types ..................................................................................................... 350
Revisiting Our Student Class Design ......................................................................................... 351
The courseLoad Attribute of Student ................................................................................... 352
The transcript Attribute of Student ...................................................................................... 352
The transcript Attribute, Take 2 ............................................................................................ 356
Our Completed Student Data Structure ............................................................................... 363
Summary .................................................................................................................................. 364
Chapter 7: Some Final Object Concepts ................................................................ 367
Polymorphism ........................................................................................................................... 368
Polymorphism Simplifies Code Maintenance ...................................................................... 375
Three Distinguishing Features of an Object-Oriented Programming Language ........................ 378
The Benefits of User-Defined Types ..................................................................................... 378
The Benefits of Inheritance ................................................................................................. 379
The Benefits of Polymorphism ............................................................................................. 379
Abstract Classes ....................................................................................................................... 380
Implementing Abstract Methods ......................................................................................... 385
Abstract Classes and Instantiation ...................................................................................... 387
Declaring Reference Variables of Abstract Types ................................................................ 389
An Interesting Twist on Polymorphism ................................................................................ 390
Interfaces .................................................................................................................................. 392
Implementing Interfaces ..................................................................................................... 395
Another Form of the “Is A” Relationship .............................................................................. 400
Interfaces and Casting ......................................................................................................... 401
Implementing Multiple Interfaces ........................................................................................ 406
Interfaces and Casting, Revisited ........................................................................................ 409
Interfaces and Instantiation ................................................................................................. 410
Interfaces and Polymorphism .............................................................................................. 411
The Importance of Interfaces .............................................................................................. 412
Static Features .......................................................................................................................... 423
Static Variables .................................................................................................................... 423
A Design Improvement: Burying Implementation Details .................................................... 428
Static Methods .................................................................................................................... 429
Restrictions on Static Methods ............................................................................................ 430
Utility Classes ...................................................................................................................... 432
The final Keyword ................................................................................................................ 433
Custom Utility Classes ......................................................................................................... 437
Summary .................................................................................................................................. 439
Part II: Object Modeling 101 ................................................................................. 443
Chapter 8: The Object Modeling Process in a Nutshell ......................................... 445
The “Big Picture” Goal of Object Modeling ............................................................................... 445
Modeling Methodology = Process + Notation + Tool .......................................................... 446
My Recommended Object Modeling Process, in a Nutshell ...................................................... 451
Thoughts Regarding Object Modeling Software Tools ......................................................... 452
A Reminder .......................................................................................................................... 455
Summary .................................................................................................................................. 455
Chapter 9: Formalizing Requirements Through Use Cases ................................... 457
What Are Use Cases? ................................................................................................................ 458
Functional vs. Technical Requirements ............................................................................... 458
Involving the Users .............................................................................................................. 460
Actors ........................................................................................................................................ 460
Identifying Actors and Determining Their Roles .................................................................. 461
Diagramming a System and Its Actors ................................................................................ 463
Specifying Use Cases ................................................................................................................ 466
xiii
Matching Up Use Cases with Actors ......................................................................................... 468
To Diagram or Not to Diagram? ................................................................................................. 468
Summary .................................................................................................................................. 470
Chapter 10: Modeling the Static/Data Aspects of the System .............................. 473
Identifying Appropriate Classes ................................................................................................ 474
Noun Phrase Analysis .......................................................................................................... 475
Refining the Candidate Class List ........................................................................................ 483
Revisiting the Use Cases ..................................................................................................... 488
Producing a Data Dictionary ..................................................................................................... 491
Determining Associations Between Classes ............................................................................. 492
Association Matrices ........................................................................................................... 495
Identifying Attributes ................................................................................................................. 498
UML Notation: Modeling the Static Aspects of an Abstraction .................................................. 498
Classes, Attributes, and Operations ..................................................................................... 499
Relationships Between Classes ........................................................................................... 503
Reflecting Multiplicity .......................................................................................................... 511
Object/Instance Diagrams ......................................................................................................... 516
Associations As Attributes ......................................................................................................... 518
Information “Flows” Along an Association “Pipeline” ............................................................... 520
“Mixing and Matching” Relationship Notations ........................................................................ 527
Association Classes .................................................................................................................. 531
Our “Completed” Student Registration System Class Diagram ................................................ 534
Metadata ................................................................................................................................... 543
Summary .................................................................................................................................. 545
Chapter 11: Modeling the Dynamic/Behavioral Aspects of the System ............... 547
How Behavior Affects State ...................................................................................................... 548
Events .................................................................................................................................. 551
Scenarios .................................................................................................................................. 556
Scenario #1 for the “Register for a Course” Use Case ........................................................ 557
Scenario #2 for the “Register for a Course” Use Case ........................................................ 559
Sequence Diagrams .................................................................................................................. 560
Determining Objects and External Actors for Scenario #1 .................................................. 561
Preparing the Sequence Diagram ........................................................................................ 563
Using Sequence Diagrams to Determine Methods ................................................................... 568
Communication Diagrams ......................................................................................................... 571
Revised SRS Class Diagram ...................................................................................................... 573
Summary .................................................................................................................................. 575
Chapter 12: Wrapping Up Our Modeling Efforts .................................................... 579
Testing the Model ...................................................................................................................... 579
Revisiting Requirements ........................................................................................................... 580
Reusing Models: A Word About Design Patterns ....................................................................... 584
Summary .................................................................................................................................. 587
Part III: Translating an Object Blueprint into Java Code .............................589
Chapter 13: A Few More Java Details ................................................................... 591
Java-Specific Terminology ........................................................................................................ 592
Java Archive (jar) Files .............................................................................................................. 593
Creating Jar Files ................................................................................................................ 594
Inspecting the Contents of a Jar File ................................................................................... 595
Using the Bytecode Contained Within a Jar File .................................................................. 596
Extracting Contents from Jar Files ...................................................................................... 597
“Jarring” Entire Directory Hierarchies ................................................................................. 597
Javadoc Comments ................................................................................................................... 599
The Object Nature of Strings ..................................................................................................... 608
Operations on Strings .......................................................................................................... 608
Strings Are Immutable ......................................................................................................... 612
The StringBuffer Class ......................................................................................................... 616
The StringTokenizer Class ................................................................................................... 617
Instantiating Strings and the String Literal Pool .................................................................. 620
Testing the Equality of Strings ............................................................................................. 624
Message Chains ........................................................................................................................ 626
Object Self-Referencing with “this” .......................................................................................... 628
Java Exception Handling ........................................................................................................... 630
The Mechanics of Exception Handling ................................................................................. 633
Catching Exceptions ............................................................................................................ 645
Interpreting Exception Stack Traces .................................................................................... 651
The Exception Class Hierarchy ............................................................................................ 654
Catching the Generic Exception Type .................................................................................. 658
Compiler Enforcement of Exception Handling ..................................................................... 659
Taking Advantage of the Exception That We’ve Caught ....................................................... 661
Nesting of Try/Catch Blocks ................................................................................................. 662
User-Defined Exception Types ............................................................................................. 663
Throwing Multiple Types of Exception ................................................................................. 668
Enum(eration)s .......................................................................................................................... 668
Providing Input to Command-Line-Driven Programs ................................................................ 678
Accepting Command-Line Arguments: The args Array ........................................................ 679
Introducing Custom Command-Line Flags to Control a Program’s Behavior ....................... 681
Accepting Keyboard Input: The Scanner Class .................................................................... 687
Using Wrapper Classes for Input Conversion ....................................................................... 689
Features of the Object Class ..................................................................................................... 692
Determining the Class That an Object Belongs To ............................................................... 692
Testing the Equality of Objects ............................................................................................ 694
Overriding the equals Method ............................................................................................. 700
Overriding the toString Method ........................................................................................... 704
Static Initializers .................................................................................................................. 707
Variable Initialization, Revisited ................................................................................................ 709
Variable Arguments (varargs) .............................................................................................. 712
Summary .................................................................................................................................. 716
Chapter 14: Transforming the Model into Java Code ............................................ 719
Suggestions for Getting the Maximum Value from This Chapter .............................................. 720
The SRS Class Diagram Revisited ............................................................................................. 720
The Person Class (Specifying Abstract Classes) .................................................................. 724
The Student Class (Reuse Through Inheritance, Extending Abstract Classes, Delegation) .. 728
The Professor Class (Bidirectionality of Relationships) ....................................................... 740
The Course Class (Reflexive Relationships, Unidirectional Relationships) .......................... 742
The Section Class (Representing Association Classes, Public Static Final Attributes,
Enums) ................................................................................................................................ 747
Delegation Revisited ............................................................................................................ 758
The ScheduleOfClasses Class ............................................................................................. 765
The TranscriptEntry Association Class (Static Methods) ...................................................... 767
The Transcript Class ............................................................................................................ 772
The SRS Driver Program ...................................................................................................... 773
Summary .................................................................................................................................. 787
Chapter 15: Building a Three-Tier User Driven Application .................................. 789
A Three-Tier Architecture .......................................................................................................... 790
What Does the Controller Do? ............................................................................................. 791
Building a Persistence/Data Tier ............................................................................................... 792
Building a Web-Based Presentation Layer ................................................................................ 795
Example Controller Logic .......................................................................................................... 797
The Importance of Model–Data Layer–View Separation ........................................................... 800
Summary .................................................................................................................................. 802
Further Reading ........................................................................................................................ 802
Appendix A: Alternative Case Studies .................................................................. 805
Index ..................................................................................................................... 815