Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Object Oriented Programming using Java
Description: This book will explain the Object Oriented approach to programming and through the use of small exercises, for which feedback is provided, develop some practical skills as well. At the end of the book one larger case study will be used to illustrate the application of the techniques. This will culminate in the development of a complete Java program which can be downloaded with this book. Topics covered include : Abstraction, Inheritance, Polymorphism, Object Oriented Software Analysis and Design, The Unified Modelling Language (UML) , Agile Programming and Test Driven Development. An Introduction to Object Orientated Programming A Brief History of Computing Different Programming Paradigms Why use the Object Orientation Paradigm? Object Oriented Principles What Exactly is Object Oriented Programming? The Benefits of the Object Oriented Programming Approach Summary The Unified Modelling Language (UML) An Introduction to UML UML Class diagrams UML Syntax UML Package Diagrams UML Object Diagrams UML Sequence Diagrams Summary Inheritance and Method Overriding Object Families Generalisation and Specialisation Inheritance Implementing Inheritance in Java Constructors Constructor Rules Access Control Abstract Classes Overriding Methods The ‘Object’ Class Overriding toString() defined in ‘Object’ Summary Object Roles and the Importance of Polymorphism Class Types Substitutability Polymorphism Extensibility Interfaces Extensibility Again Distinguishing Subclasses Summary Overloading Overloading Overloading To Aid Flexibility Summary Object Oriented Software Analysis and Design Requirements Analysis The Problem Listing Nouns and Verbs Identifying Things Outside The Scope of The System Identifying Synonyms Identifying Potential Classes Identifying Potential Attributes Identifying Potential Methods Identifying Common Characteristics Refining Our Design using CRC Cards Elaborating Classes Summary The Collections Framework An Introduction to Collections Collection Interfaces Old and New Collections Lists Sets Maps Collection Implementations Overview of the Collections Framework An Example Using Un-typed Collections An Example Using Typed Collections A Note About Sets Summary Java Development Tools Software Implementation The JRE Java Programs The JDK Eclipse Eclipse Architecture Eclipse Features NetBeans Developing Graphical Interfaces Using NetBeans Applying Layout Managers Using NetBeans Adding Action Listeners The Javadoc Tool Summary Creating And Using Exceptions Understanding the Importance of Exceptions Kinds of Exception Extending the Exception Class Throwing Exceptions Catching Exceptions Summary Agile Programming Agile Approaches Refactoring Examples of Refactoring Support for Refactoring Unit Testing Automated Unit Testing Regression Testing JUnit Examples of Assertions Several Test Examples Running Tests Test Driven Development (TDD) TDD Cycles Claims for TDD Summary Case Study The Problem Preliminary Analysis Further Analysis Documenting the design using UML Prototyping the Interface Revising the Design to Accommodate Changing Requirements Packaging the Classes Programming the Message Classes Programming the Client Classes Creating and Handling UnknownClientException Programming the Main classes Programming the Interface Using Test Driven Development and Extending the System Generating Javadoc Running the System and Potential Compiler Warnings The Finished System… Summary
Description: This book will explain the Object Oriented approach to programming and through the use of small exercises, for which feedback is provided, develop some practical skills as well. At the end of the book one larger case study will be used to illustrate the application of the techniques. This will culminate in the development of a complete Java program which can be downloaded with this book. Topics covered include : Abstraction, Inheritance, Polymorphism, Object Oriented Software Analysis and Design, The Unified Modelling Language (UML) , Agile Programming and Test Driven Development. An Introduction to Object Orientated Programming A Brief History of Computing Different Programming Paradigms Why use the Object Orientation Paradigm? Object Oriented Principles What Exactly is Object Oriented Programming? The Benefits of the Object Oriented Programming Approach Summary The Unified Modelling Language (UML) An Introduction to UML UML Class diagrams UML Syntax UML Package Diagrams UML Object Diagrams UML Sequence Diagrams Summary Inheritance and Method Overriding Object Families Generalisation and Specialisation Inheritance Implementing Inheritance in Java Constructors Constructor Rules Access Control Abstract Classes Overriding Methods The ‘Object’ Class Overriding toString() defined in ‘Object’ Summary Object Roles and the Importance of Polymorphism Class Types Substitutability Polymorphism Extensibility Interfaces Extensibility Again Distinguishing Subclasses Summary Overloading Overloading Overloading To Aid Flexibility Summary Object Oriented Software Analysis and Design Requirements Analysis The Problem Listing Nouns and Verbs Identifying Things Outside The Scope of The System Identifying Synonyms Identifying Potential Classes Identifying Potential Attributes Identifying Potential Methods Identifying Common Characteristics Refining Our Design using CRC Cards Elaborating Classes Summary The Collections Framework An Introduction to Collections Collection Interfaces Old and New Collections Lists Sets Maps Collection Implementations Overview of the Collections Framework An Example Using Un-typed Collections An Example Using Typed Collections A Note About Sets Summary Java Development Tools Software Implementation The JRE Java Programs The JDK Eclipse Eclipse Architecture Eclipse Features NetBeans Developing Graphical Interfaces Using NetBeans Applying Layout Managers Using NetBeans Adding Action Listeners The Javadoc Tool Summary Creating And Using Exceptions Understanding the Importance of Exceptions Kinds of Exception Extending the Exception Class Throwing Exceptions Catching Exceptions Summary Agile Programming Agile Approaches Refactoring Examples of Refactoring Support for Refactoring Unit Testing Automated Unit Testing Regression Testing JUnit Examples of Assertions Several Test Examples Running Tests Test Driven Development (TDD) TDD Cycles Claims for TDD Summary Case Study The Problem Preliminary Analysis Further Analysis Documenting the design using UML Prototyping the Interface Revising the Design to Accommodate Changing Requirements Packaging the Classes Programming the Message Classes Programming the Client Classes Creating and Handling UnknownClientException Programming the Main classes Programming the Interface Using Test Driven Development and Extending the System Generating Javadoc Running the System and Potential Compiler Warnings The Finished System… Summary
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Object Oriented Programming
using Java
Simon Kendal
Download free books at
Simon Kendal
Object Oriented Programming Using Java
“To my wife Janice and daughter Cara, without whom life would be no fun at all!”
Download free eBooks at bookboon
...
com
ISBN 978-87-7681-501-1
Download free eBooks at bookboon
...
1
A Brief History of Computing
12
1
...
3
Why use the Object Orientation Paradigm?
15
1
...
5
What Exactly is Object Oriented Programming?
20
1
...
7 Summary
23
2
The Unified Modelling Language (UML)
24
2
...
2
UML Class diagrams
25
2
...
4
UML Package Diagrams
41
www
...
com
We do not reinvent
the wheel we reinvent
light
...
An environment in which your expertise is in high
demand
...
Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future
...
Light is OSRAM
Download free eBooks at bookboon
...
5
UML Object Diagrams
47
2
...
7 Summary
50
3
Inheritance and Method Overriding
51
3
...
2
Generalisation and Specialisation
52
3
...
4
61
Implementing Inheritance in Java
3
...
6
Constructor Rules
62
3
...
8
Abstract Classes
65
3
...
10
The ‘Object’ Class
3
...
12 Summary
360°
thinking
...
66
68
70
71
360°
thinking
...
deloitte
...
Discover the truth at www
...
ca/careers
© Deloitte & Touche LLP and affiliated entities
...
com
Deloitte & Touche LLP and affiliated entities
...
deloitte
...
Dis
Object Oriented Programming Using Java
Contents
4
Object Roles and the Importance of Polymorphism
72
4
...
2 Substitutability
75
4
...
4 Extensibility
77
4
...
6
Extensibility Again
90
4
...
8 Summary
94
5 Overloading
95
5
...
2
96
Overloading To Aid Flexibility
5
...
1
Requirements Analysis
101
6
...
3
Listing Nouns and Verbs
104
6
...
Send us your CV
...
Send us your CV on
www
...
com
Download free eBooks at bookboon
...
5
Identifying Synonyms
106
6
...
7
Identifying Potential Attributes
108
6
...
9
Identifying Common Characteristics
109
6
...
11
Elaborating Classes
112
6
...
1
An Introduction to Collections
115
7
...
3
Old and New Collections
116
7
...
5 Sets
117
7
...
7
Collection Implementations
119
7
...
9
An Example Using Un-typed Collections
123
AXA Global
Graduate Program
Find out more and apply
Download free eBooks at bookboon
...
10
An Example Using Typed Collections
125
7
...
12 Summary
132
8
Java Development Tools
133
8
...
2
The JRE
137
8
...
4
The JDK
139
8
...
6
Eclipse Architecture
140
8
...
8 NetBeans
142
8
...
10
Applying Layout Managers Using NetBeans
145
8
...
12
The Javadoc Tool
149
8
...
com/Mitas
www
...
com
93%
�e G
for Engine
Ma
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION
Month 16
I was a construction
Mo
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
THAT THE CAPITAL OF SPAIN OFFERS
supervisor ina const
I was
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
PROFESSIONAL GOALS
the North Sea super
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
EXPERIENCE
advising and the No
#10 WORLDWIDE
Real work
he 55 Nationalities
helping foremen advis
5 Specializations
Personalize your program Internationa opportunities
in class
International
al
�ree wo placements
work
or
s Real work
solve problems
he
helping fo
International
Internationa opportunities
al
�ree wo placements
work
or
s
solve pr
MASTER IN MANAGEMENT
Length: 1O MONTHS
Av
...
ie
...
admissions@ie
...
com
8
Click on the ad to read more
Object Oriented Programming Using Java
Contents
9
Creating And Using Exceptions
154
9
...
2
Kinds of Exception
157
9
...
4
Throwing Exceptions
160
9
...
6 Summary
161
10
Agile Programming
162
10
...
2 Refactoring
163
10
...
4
Support for Refactoring
164
10
...
6
Automated Unit Testing
167
10
...
8 JUnit
168
10
...
10
Several Test Examples
168
10
...
com
9
Click on the ad to read more
Object Oriented Programming Using Java
Contents
10
...
13
TDD Cycles
174
10
...
15 Summary
174
11
Case Study
175
11
...
2
Preliminary Analysis
177
11
...
4
Documenting the design using UML
188
11
...
6
Revising the Design to Accommodate Changing Requirements
193
11
...
8
Programming the Message Classes
199
11
...
10
Creating and Handling UnknownClientException
206
11
...
12
Programming the Interface
209
11
...
14
Generating Javadoc
212
11
...
16
The Finished System…
214
11
...
com
10
Object Oriented Programming Using Java
Foreword
Foreword
This book aims to instil the reader with an understanding of the Object Oriented approach to programming
and aims to develop some practical skills along the way
...
The concepts that will be explained and skills developed are in common use among programmers using
many modern object oriented languages and are thus transferrable from one language to another
...
While the Java programming language is used to highlight and demonstrate the application of
fundamental object oriented principles and modelling techniques this book is not an introduction to
Java programming
...
the use of loops, selection statements, performing calculations,
arrays, data types and a basic understanding of file handling)
...
To this end each chapter will
incorporate small exercises with solutions and feedback provided
...
This case study will culminate in the development of
a complete Java program that can be downloaded with this book
...
com
11
Object Oriented Programming Using Java
An Introduction to Object Orientated Programming
1 Introduction to Object
An
Orientated Programming
Introduction
This chapter will discuss different programming paradigms and the advantages of the Object Oriented
approach to software development and modelling
...
Objectives
By the end of this chapter you will be able to…
• Explain what Object Oriented Programming is,
• Describe the benefits of the Object Oriented programming approach and
• Understand and the basic concepts of abstraction, encapsulation, generalisation and
polymorphism on which object oriented programming relies
...
This chapter consists of six sections:1) A Brief History of Computing
2) Different Programming Paradigms
3) Why use the Object Oriented Paradigm
4) Object Oriented Principles
5) What Exactly is Object Oriented Programming?
6) The Benefits of the Object Oriented Programming Approach
...
1
A Brief History of Computing
Computing is a constantly changing our world and our environment
...
Bank account and payroll
programs changed the way organisations worked and made parts of these organisations much more efficient
...
People
started to own their own computers and many used word processors and spreadsheets applications (to
write letters and to manage home accounts)
...
These technologies revolutionised communications allowing individuals to publish information
that could easily be accessed on a global scale
...
Download free eBooks at bookboon
...
In the 1950s the use machine code (unsophisticated, complex
and machine specific) languages were common
...
However these
led to the development of large complex programs that were difficult to manage and maintain
...
The structured programming paradigm proposed methods to logically structure
the programs developed into separate smaller, more manageable components
...
However significant problems still persisted in a) understanding the systems we need to create and b)
changing existing software as users requirements changed
...
In the 1990s the Object Oriented paradigm and component-based software development ideas were
developed and Object Oriented languages became the norm from 2000 onwards
...
Proponents of the Object Oriented software development paradigm argue that this leads to the
development of software components that can be re-used in different applications thus saving significant
development time and cost savings but more importantly allow better software models to be produced
that make systems more maintainable and easier to understand
...
Where these will lead us in 2020 and beyond remains to be seen
...
2
Different Programming Paradigms
The structured programming paradigm proposed that programs could be developed in sensible blocks
that make the program more understandable and easier to maintain
...
com
13
Object Oriented Programming Using Java
An Introduction to Object Orientated Programming
Activity 1
Assume you undertake the following activities on a daily basis
...
Get out of bed
Eat breakfast
Park the car
Get dressed
Get the car out of the garage
Drive to work
Find out what your boss wants you to do today
Feedback to the boss on today’s results
...
Get up:Get out of bed
Get dressed
Eat breakfast
Go to Work:Get the car out of the garage
Drive to work
Park the car
Do your job:Find out what your boss wants you to do today
Do what the boss wants you to do
Feedback to the boss on today’s results
...
For example we could improve the instructions for going to work…
Listen to the local traffic and weather report
Decide whether to go by bus or by car
If going by car, get the car and drive to work
...
In
the same way structuring computer programs can make each part more understandable and make
large programs easier to maintain
...
One advantage of doing this is we get
reusable software components
...
com
14
Object Oriented Programming Using Java
An Introduction to Object Orientated Programming
Activity 2
Imagine and a personal address book with some data stored about your friends
Name,
Address,
Telephone Number
...
Next identify someone else who may use an identical address book for some purpose other than
storing a list of friends
...
e
...
We can create a simple software component to store the data in the address book (i
...
list of
names etc) and the operations we can perform (i
...
By creating a simple software component to store and manage addresses of friends we can reuse
this in another software system i
...
it could be used by a business manager to store and find
details of customers
...
Thus in object oriented programming we can create re-usable software components (in this case
an address book)
...
1
...
Most problems arise from:• poor analysis and design: the computer system we create doesn’t do the right thing
...
Statistics show 70% of the cost of software is not incurred during its initial development phase but is
incurred during subsequent years as the software is amended to meet the ever changing needs of the
organisation for which it was developed
...
Download free eBooks at bookboon
...
1
...
Abstraction allows us to consider complex ideas while ignoring irrelevant detail
that would confuse us
...
Activity 3
Consider your home and imagine you were going to swap your home for a week with a
new friend
...
Now list three irrelevant details that you would not tell your friend
...
”
CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www
...
nl/feb/education
Download free eBooks at bookboon
...
g
...
e which key would operate the front door
and how to switch off the burglar alarm (if you have one)
...
Abstraction allows us to consider the important high level details of your home, e
...
the
address, without becoming bogged down in detail
...
Now consider how difficult it would be to describe the internal components of this item and
give full technical details of how it works
...
Most people do not even know all the
components of the appliances they use or how they work – but this does not stop them from
using appliances every day
...
Encapsulation allows us to consider what a light switch does, and how we operate it, without
needing to worry about the technical detail of how it actually works
...
Generalisation allows us to consider general categories of objects which have common properties and
then define specialised sub classes that inherit the properties of the general categories
...
Now for each of these common occupations list two or three specific categories of staff
...
com
17
Object Oriented Programming Using Java
An Introduction to Object Orientated Programming
Feedback 5
Depending upon your knowledge of the medical profession you may have listed three
very general occupations (e
...
doctor, nurse, cleaner) or you may have listed more specific
occupations such as radiologist, surgeon etc
...
g
...
Nurse:Triage nurse,
Midwife,
Ward sister
Cleaner:General cleaner
Cleaning supervisor
Now we have specified some general categories and some more specialised categories of staff we can
consider the general things that are true for all doctors, all nurses etc
...
Feedback 6
You could make a statement that all doctors have a knowledge of drugs, can diagnose medical
conditions and can prescribe appropriate medication
...
According to our list above all surgeons are doctors and therefore still have a knowledge of
medical conditions and can prescribe appropriate medication
...
What ever we specify as true for doctors is also true for trainee doctors, junior doctors etc –
these specialised categories (or classes) can inherit the attributes and behaviours associated
with the more general class of ‘doctor’
...
com
18
Object Oriented Programming Using Java
An Introduction to Object Orientated Programming
Generalisation / specialisation allows us to define general characteristics and operations of an object and
allows us to create more specialised versions of this object
...
The final principle underlying Object Orientation is Polymorphism which is the ability to interact with
a object as its generalized category regardless of its more specialised category
...
Feedback 7
You may have considered that a hospital manager could pay all doctors (presumably this will
be done automatically at the end of every month) and could discipline any doctor guilty of
misconduct – of course this would be true for other staff as well
...
This would be something that
management would need to do for all doctors irrespective of what their specialism is
...
g
...
i
...
they are
still doctors and need to be treated as such
...
ligsuniversity
...
More info here
...
com
19
Click on the ad to read more
Object Oriented Programming Using Java
An Introduction to Object Orientated Programming
Using the same idea polymorphism allows computer systems to be extended, with new specialised objects
being created, while allowing current parts of the system to interact with new object without concern
for the specific properties of the new objects
...
5
What Exactly is Object Oriented Programming?
Activity 8
Think of an object you possess
...
Feedback 8
You probably thought about an entirely physical object such as a watch, a pen, or a car
...
A watch has a time (represented internally by wheels and cogs or
in an electronic component)
...
A
car has a current speed and has a certain amount of fuel inside it
...
A pen can be used to write
with and a car can be driven
...
A bank account is
not something that can be physically touched but intellectually we can consider a bank account to be
an object
...
Object oriented programming it a method of programming that involves the creation of intellectuals
objects that model a business problem we are trying to solve (e
...
a bank account, a bank customer and
a bank manager – could all be objects in a computerised banking system)
...
e
...
In creating a object oriented program we define the properties of a class of objects (e
...
all bank accounts)
and then create individual objects from this class (e
...
your bank account)
...
com
20
Object Oriented Programming Using Java
An Introduction to Object Orientated Programming
A ‘class’ is a software design which
describes the general properties of
something which the software is
modelling
...
In essence we need to
create an abstract model of the real world that focuses on the essential aspects of a problem and ignores
irrelevant complexities
...
If we were to create a bank account
system should we allow customers to borrow money? Should we acknowledge that their cash may get
stolen and build in some method of them getting an immediate loan – or is this an irrelevant detail that
would just add complexity to the system and provide no real benefit to the bank?
Using object oriented analysis and design techniques our job would be to look at the real world and
come up with a simplified abstract model that we could turn into a computer system
...
Software
Model
Real
World
Download free eBooks at bookboon
...
Imagine one
such item that you may like to reserve and list two or three things that a librarian may want to
know about this item
...
Thus for every object we create in a system we need to define the attributes of that object i
...
the
things we need to know about it
...
Considering this intellectual object (item reservation) list two or three actions the
librarian may need to perform on this object
...
com
22
Click on the ad to read more
Object Oriented Programming Using Java
An Introduction to Object Orientated Programming
Feedback 10
The librarian may need to cancel this reservation (if you change your mind) they may also need to
tell you if the item has arrived in stock for you to collect
...
Activity 11
Considering the most general category of object that can be borrowed from a library, a ‘loan item’,
list two or three more specific subcategory of object a library can lend out
...
g
...
These will share the attributes defined for the general class but will have specific
differences (for example there could be a charge for borrowing audio/visual items)
...
6
The Benefits of the Object Oriented Programming Approach
Whether or not you develop programs in an object oriented way, before you write the software you must
first develop a model of what that software must be able to do and how it should work
...
The general proponents of the object oriented approach claims that this model provides:
• better abstractions (modelling information and behaviour together)
• better maintainability (more comprehensible, less fragile)
• better reusability (classes as encapsulated components)
We will return to look at these claims later in Chapter 11 as we see a case study showing in detail how
object oriented analysis works and how the resultant models can be implemented in an object oriented
programming language (i
...
Java)
...
7 Summary
Object oriented programming involves the creation of classes by modelling the real world
...
Polymorphic
behaviour means that systems can be changed, as business needs change, by adding new specialised
classes and these classes can be accessed by the rest of the system without any regard to their specialised
behaviour and without changing other parts of the current system
...
com
23
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
2
The Unified Modelling
Language (UML)
Introduction
This chapter will introduce you to the roles of the Unified Modelling Language (UML) and explain the
purpose of four of the most common diagrams (class diagrams, object diagrams, sequence diagrams
and package diagrams)
...
Objectives
By the end of this chapter you will be able to…
• Explain what UML is and explain the role of four of the most common diagrams,
• Draw class diagrams, object diagrams, sequence diagrams and package diagrams
...
This chapter consists of six sections:1) An introduction to UML
2) UML Class Diagrams
3) UML Syntax
4) UML Package Diagrams
5) UML Object diagrams
6) UML Sequence Diagrams
2
...
It is not!
A methodology is a system of processes in order to achieve a particular outcome e
...
an organised
sequence of activities in order to gather user requirements
...
As it is graphical in nature it
becomes easy to visualise, understand and discuss the information presented in the diagram
...
Download free eBooks at bookboon
...
UML does not constrain this – it merely
allows those designs to be expressed in an easy to use, but precise, graphical notation
...
2
UML Class diagrams
Classes are the basic components of any object oriented software system and UML class diagrams provide
an easy way to represent these
...
Thus a class diagram shows the architecture of
a system
...
Download free eBooks at bookboon
...
Attributes normally being kept private and methods normally made public
...
Hence it starts with a capital letter
...
Show appropriate visibility modifiers
...
com
26
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
Feedback 1
BankAccount
- balance :int
+depositMoney()
+withdrawMoney()
+displayBalance()
The diagram above shows this information
UML allows us to suppress any information we do not wish to highlight in our diagrams – this allows
us to suppress irrelevant detail and bring to the readers attention just the information we wish to focus
on
...
com
27
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
And finally with the attributes and methods not shown…
BankAccount
i
...
there is a class called ‘BankAccount’ but the details of this are not being shown
...
These relationships are shown by arrows
...
In addition to this class diagrams can make use of keywords, notes and comments
...
mastersopenday
...
com
28
Click on the ad to read more
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
• Relationships
-- navigability
-- multiplicity
-- dependency
-- aggregation
-- composition
• Generalization / specialization
-- inheritance
-- interfaces
• Keywords
• Notes and Comments
2
...
Attributes should be shown as: visibility name: type multiplicity
Where visibility is one of:-- ‘+’ public
-- ‘-’ private
-- ‘#’ protected
-- ‘~’ package
and Multiplicity is one of:-- ‘n’ exactly n
-- ‘*’ zero or more
-- ‘m
...
Download free eBooks at bookboon
...
*]
a protected attribute itemCodes is one or more String values
validCard: boolean
an attribute validCard, of unspecified visibility, has unspecified multiplicity
Operations also have a precise syntax and should be shown as:
visibility name (par1: type1, par2: type2): returntype
where each parameter is shown (in parenthesis) and then the return type is specified
...
Activity 2
Draw a diagram to represent a class called ‘BankAccount’ with a private attribute balance (this
being a single integer) and a public method depositMoney() which takes an integer parameter,
‘deposit’ and returns a boolean value
...
Feedback 2
The diagram below shows this information
BankAccount
- balance :int[1]
+depositMoney(deposit :int) : boolean
Denoting Relationships
As well as denoting individual classes, Class diagrams denote relationships between classes
...
Download free eBooks at bookboon
...
These could be primitive data types (int, boolean etc
...
OneClass
value : OtherClass
Thus the figure above shows a class ‘OneClass’ that has an attribute ‘value’
...
We could denote exactly the same information by the diagram below
...
Download free eBooks at bookboon
...
This would generally be true of all library classes unless we are drawing the diagram
specifically to explain some aspect of the library class for the benefit of someone unfamiliar with its
purpose and functionality
...
*
OneClass
OtherClass
This implies that ‘OneClass’ maintains a collection of objects of type ‘OtherClass’
...
Activity 3
Draw a diagram to represent a class called ‘Catalogue’ and a class called ‘ItemForSale’ as defined
below:ItemForSale has an attribute ‘name’ of type string and an attribute ‘price’ of type int
...
‘Catalogue’ has an attribute ‘listOfItems’ i
...
the items currently held in the catalogue
...
‘Catalogue’ also has one method addItem() which takes an ‘item’ as a parameter (of type
ItemForSale) and adds this item to the ‘listOfItems’
...
Feedback 3
The diagram below shows this information
Catalogue
ItemForSale
0
...
com
32
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
Note: All class names begin in uppercase, attribute and method names begin in lowercase
...
‘listOfItems’ however maintains
a list of zero or more individual objects
...
com
33
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
Typical use of dependency lines would be where Class A has a method which is passed a parameter
object of Class B, or uses a local variable of that class, or calls ‘static’ methods in Class B
...
e
...
The reverse
is not true – the Class B object doesn’t ‘know about’ the Class A object
A simple association typically corresponds to an instance variable in Class A of the target class B type
...
An ItemForSale does not need to access a Catalogue in order to set its price or
perform some other method associated with the item itself
...
Find out what you can do to improve
the quality of your dissertation!
Get Help Now
Go to www
...
co
...
com
34
Click on the ad to read more
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
Bidirectional Association
Class A
Class B
• Bidirectional Association is when Classes A and B have a two-way association
• Each refers to the other class
• Navigability A to B and B to A:
-- A Class A object can access the Class B object(s) with which it is associated
-- Object(s) of Class B ‘belong to’ Class A
-- Implies reference from A to B
-- Also, a Class B object can access the Class A object(s) with which it is associated
A bidirectional association is complicated because each object must have a reference to the other object(s)
and generally bidirectional associations are much less common than unidirectional ones
...
ie
...
Alternatively starting with a student we
may wish to know the Degree they are studying
...
Aggregation
• Aggregation denotes a situation where Object(s) of Class B ‘belong to’ Class A
• Implies reference from A to B
• While aggregation implies that objects of Class B belong to objects of Class A it also implies
that object of Class B retain an existence independent of Class A
...
com
35
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
An example of aggregation would be between a Class Car and a Class Tyre
We think of the tyres as belonging to the car they are on, but at the garage they may be removed and
placed on a rack to be repaired
...
Composition
• Composition is similar to aggregation but implies a much stronger belonging relationship
i
...
Object(s) of Class B are ‘part of ’ a Class A object
• Again implies reference from A to B
• Much ‘stronger’ than aggregation in this case Class B objects are an integral part of Class A
and in general objects of Class B never exist other than as part of Class A, i
...
they have the
same ‘lifetime’
An example of composition would be between Points, Lines and Shapes as elements of a Picture
...
As well as denoting associations, class diagrams can denote:• Inheritance,
• Interfaces,
• Keywords and
• Notes
Inheritance
• Aside from associations, the other main modelling relationship is inheritance:
• Class A ‘inherits’ both the interface and implementation of Class B, though it may override
implementation details and supplement both
...
Download free eBooks at bookboon
...
The methods defined by the interface must be implemented in every class that implements
the interface
...
Brain power
By 2020, wind could provide one-tenth of our planet’s
electricity needs
...
Up to 25 % of the generating costs relate to maintenance
...
We help make it more economical to create
cleaner, cheaper energy out of thin air
...
Therefore we need the best employees who can
meet this challenge!
The Power of Knowledge Engineering
Plug into The Power of Knowledge Engineering
...
skf
...
com
37
Click on the ad to read more
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
NB the dotted-line version of the inheritance line/arrow which shows that Publication ‘implements’ or
‘realizes’ the SaleableItem interface
...
We will look at the application of interfaces in more detail in Chapter 4
...
An abstract class may alternatively be denoted by showing its name in italics though this is perhaps less
obvious to a casual reader
...
This gives us a ‘catch all’ facility for adding
information not conveyed by the graphical notation
...
Explain and discuss your model with other students and your tutor
...
Download free eBooks at bookboon
...
This association relationship is naturally unidirectional –
given a student we might want to find their transcript(s),
but it seems unlikely that we would have a transcript and
need to find the student to whom it belonged
...
A
particular book can be borrowed by at most one reader
...
This might be part of the model for some kind of
educational virtual anatomy program
...
The multiplicities would not always work for real people
though – they might have lost a finger due to accident or
disease, or have an extra one because of a genetic anomaly
...
A customer can have any number of bank accounts, and
a bank account can be held by one person or two people
(a “joint account”)
...
A bank account must either be a current account or a
savings account – hence BankAccount itself is abstract
...
com
39
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
Part of a clock is a display to show the time
...
We could
use a superclass and two subclasses, but since the
implementation of the two displays will be entirely different
it may be more appropriate to use an interface to define
the operations which AnalogDisplay and DigitalDisplay
must provide
...
Feedback 4
There is no specific feedback for this activity
...
com
40
Click on the ad to read more
Object Oriented Programming Using Java
2
...
Here we will touch upon three of these:• Package Diagrams
• Object Diagrams and
• Sequence Diagrams
World maps, country maps and city maps all show spatial information, just on different scales and with
differing levels of detail
...
Thus, just as we need world maps, we need package diagrams
to show the general architecture of a large system
...
e
...
We will see an example of packages in use in Chapter 11
...
A package is not just a visual representation of a group of classes instead a ‘package’ is a directory
containing a group of related classes (and interfaces)
...
Similarly we can also arrange our own classes using the
Java package mechanism
...
g
...
awt
...
The names correspond to
a series of sub-directories in the file system, e
...
A large Java development should be split into suitable packages at the design stage UML provides a
‘Package Diagram’ to represent the relationships between classes and packages
...
com
41
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
We can depict
• classes within packages
• nesting of packages
• dependencies between packages
In the diagram below we see two packages:- ‘java’ and ‘javax’
Looking at this more closely we can see that inside the ‘java’ package is another called ‘awt’ and inside
‘javax’ is a package called ‘swing’
...
Finally we show that the javax
...
awt package
...
awt and javax
...
In the diagram below we have an alternative way of indicating that a JButton is in the javax
...
And again below a form which shows all three classes more concisely than at the top
...
com
42
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
These different representations will be useful in different circumstances depending on what a package
diagram is aiming to convey
...
g
...
interface
mysystem
...
engine
...
database
However, packages are often distributed and to enable this packages need globally unique names, thus
a naming convention has been adopted based on URLs
Download free eBooks at bookboon
...
’ but by ‘::’
...
For speed split the following
shopping list into two halves – items to be collected by you and items to be collected
by your flatmate
...
Matches, Grapes
Feedback 5
To make your shopping efficient you probably organised your list into two lists of
items that are located in the same parts of the shop:List 1
Apples,
Pears,
Grapes
Carrots,
Potatoes
List 2
Furniture polish,
Floor cleaner
Matches
Toilet Rolls,
Activity 6
You run a team of three programmers and are required to write a program in Java to
monitor and control a network system
...
Organise these classes into three packages
...
Give the packages any name you
feel appropriate
...
Download free eBooks at bookboon
...
A suggested solution to activity 6 is given below
...
myorg
...
Draw a package diagram to
convey this information
...
com
45
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
Feedback 7
Note: Dependency arrows have been drawn to highlight relationships between
packages
...
Download free eBooks at bookboon
...
5
The Unified Modelling Language (UML)
UML Object Diagrams
Class diagrams and package diagrams allow us to visualise and discuss the architecture of a system
however at times we wish to discuss the data a system processes
...
Object diagrams look superficially similar to class diagrams however the boxes represent specific instances
of objects
...
attribute = value
These diagrams are useful for illustrating particular ‘snapshot’ scenarios during design
...
The system contains two classes:Book, which store the details of a book and
Library, which maintains a collection of books
...
Looking at this diagram we can see that at a particular moment in time, while three books have been
created only two have been added to the library
...
As with class diagrams, elements can be freely suppressed on object diagrams
...
com
47
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
For example, all of these are legal:
2
...
Class diagrams describe
the architecture of a system and object diagrams describe the state of a system at one moment in time
...
Sequence diagrams
are ‘dynamic’ rather than ‘static’ representations of the system
...
They are useful for understanding how
objects collaborate in a particular scenario
...
com
48
Object Oriented Programming Using Java
The Unified Modelling Language (UML)
We have three objects in this scenario
...
This diagram shows the following actions taking place:• Firstly a method call (often referred to in OO terminology as a message) to method0()
comes to object1 from somewhere – this could be another class outside the diagram
...
• object1
...
method1() – the activation bar indicates that this
executes for a period then returns control to method0()
• Subsequently object1
...
method2() passing two parameters
• method2() subsequently invokes object3
...
When method3() ends it passes a
return value back to method2()
• method2() completes and returns control to object1
...
There is a notation (‘interaction frames’) which allow ifs and loops to be represented in sequence diagrams
however these tend to make the diagrams cluttered
...
Fowler (“UML Distilled”, 3rd Edn
...
Download free eBooks at bookboon
...
7 Summary
UML is not a methodology but a precise diagramming notation
...
Object
diagrams describe the data within an application at one moment in time and sequence diagrams describe
how a system works over a period of time
...
With any UML diagram suppression is encouraged – thus the author of a diagram can suppress any
details they wish in order to convey essential information to the reader
...
RUN LONGER
...
GAITEYE
...
indd 1
Download free eBooks at bookboon
...
Objectives
By the end of this chapter you will be able to…
• Appreciate the importance of an Inheritance hierarchy,
• Understand how to use Abstract classes to factor out common characteristics
• Override methods (including those in the ‘Object’ class),
• Explain how to use ‘Super’ to invoke methods that are in the process of being overridden,
• Document an inheritance hierarchy using UML and
• Implement inheritance and method overriding in Java programs
...
While this chapter will focus on understanding the application and documentation of an
inheritance hierarchy, Chapter 6 will focus on developing the analytical skills required to define your
own inheritance hierarchies
...
com
51
Object Oriented Programming Using Java
3
...
‘Inheritance’ is the idea ‘passing
down’ characteristics from parent to child, and plays an important part in Object Oriented design
and programming
...
Additionally we need to consider the use of Abstract classes and method overriding as these are important
concepts in the context of inheritance
...
3
...
Objects are thus
‘instances’ of their class
...
More concisely,
051234567 is a Student
...
One hierarchy, that we all have some familiarity with, is that which describes the animal kingdom:• Kingdom
(e
...
animals)
• Phylum
(e
...
vertebrates)
• Class
(e
...
mammal)
• Order
(e
...
carnivore)
• Family
(e
...
cat)
• Genus
(e
...
felix)
• Species
(e
...
felix leo)
We can represent this hierarchy graphically…
Download free eBooks at bookboon
...
com
53
Click on the ad to read more
Object Oriented Programming Using Java
Inheritance and Method Overriding
Of course to draw the complete diagram would take more time and space than we have available
...
Fred is not a class of animal but an actual animal
...
Fred is a felix leo is a felix is a cat is a carnivore is a mammal is a vertebrate
Vertebrates have a backbone so Fred has the characteristic ‘has a backbone’
...
This sort of relationship applies
to many real world entities, e
...
BonusSuperSaver is a SavingsAccount is a BankAccount
...
3 Inheritance
We specify the general characteristics high up in the hierarchy and more specific characteristics lower
down
...
All the characteristics from classes above a class/object in the hierarchy are automatically featured in
it – we call this inheritance
...
We can show classes to represent these on a UML class diagram
...
Download free eBooks at bookboon
...
Less obvious is ‘copies’ this is how many are currently
in stock
...
For magazines, orderQty is the number of copies received of each new issue and currIssue is the date/
period of the current issue (e
...
“January 2009”, “Fri 6 Jan”, “Spring 2009” etc
...
Therefore recvNewIssue() sets
currIssue to date of new issue and restores copies to orderQty
...
Activity 1
Look at the ‘Book’ and ‘Magazine’ classes defined above and identify the
commonalities and differences between two classes
...
Feedback 1
These classes have three instance variables in common: title, price, copies
...
The differences are as follows…
Book additionally has author, and orderCopies()
...
We can separate out (‘factor out’) these common members of the classes into a superclass called
Publication
...
com
55
Object Oriented Programming Using Java
Inheritance and Method Overriding
The differences will need to be specified as additional members for the ‘subclasses’ Book and Magazine
...
sylvania
...
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges
...
Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths
...
Come and join us in reinventing
light every day
...
com
56
Click on the ad to read more
Object Oriented Programming Using Java
Inheritance and Method Overriding
In this is a UML Class Diagram
...
Note the Subclass has the generalized superclass characteristics + additional specialized characteristics
...
The inherited characteristics are NOT listed in subclasses
...
Activity 2
Arrange the following classes into a suitable hierarchy and draw these on a
class diagram…
a current account
a deposit account
a bank account
Simon’s deposit account
Feedback 2
Bank Account
Current Account
Deposit Account
The most general class goes at the top of the inheritance hierarchy with the other
classes then inheriting the attributes and methods of this class
...
e
...
Download free eBooks at bookboon
...
We cannot place two classes in an inheritance
hierarchy unless we can use the term is a
...
Activity 4
Describe the following using a suitable class diagram showing ANY
sensible relationship…
a building for rent
this will have a method to determine the rent
a house for rent
this will inherit the determine rent method
a rent collector (person)
this person will use the determine rent method to print out a bill
HINT: You may wish to use the following arrow
Download free eBooks at bookboon
...
However there is a relationship (an association) between
RentCollector and Building ie
...
Activity 5
Looking at the feedback from Activity 4 and determine if a RentCollector can print out
a bill for the rent due on a house (or can they just print a bill for buildings?)
...
There is
no method determineRent() defined for a house – but this does not mean it does
not exist
...
A rent collector requires a building but a House is a type of a Building
...
Wherever a Building object is required we could substitute a
House object as this is a type of Building
...
Download free eBooks at bookboon
...
360°
thinking
...
360°
thinking
...
deloitte
...
Discover the truth at www
...
ca/careers
© Deloitte & Touche LLP and affiliated entities
...
com
Deloitte & Touche LLP and affiliated entities
...
deloitte
...
Dis
Object Oriented Programming Using Java
Inheritance and Method Overriding
Feedback 6
By showing determineRent() in House we are showing that this method is overriding
the one defined in the superclass (Building)
...
Thus RentCollector will invoke
the method defined in House if printing a bill for a house but will use the method
defined in Building for any other type of building
...
Overriding will be discussed in more detail later in this chapter
...
4
Implementing Inheritance in Java
No special features are required to create a superclass
...
A subclass specifies it is inheriting features from a superclass using the keyword extends
...
5 Constructors
Each class (whether sub or super) should encapsulate its own initialization, usually relating to setting
the initial state of its instance variables
...
Download free eBooks at bookboon
...
It does this using the keyword super
...
the superclass constructor, then this must be the first statement in the constructor
...
In other words
super-parameters will be some (or all) of sub-parameters
...
The book constructor
requires four parameters three of which are immediately passed on to the superclass constructor to
initialize its instance variables
...
public Book (String pTitle, String pAuthor, double pPrice,
{
int pCopies)
super(pTitle, pPrice, pCopies);
//etc
...
6
author = pAuthor;
Constructor Rules
Rules exist that govern the invocation of a superconstructor
...
Download free eBooks at bookboon
...
To illustrate this…
On the left above:- it is legal, though bad practice, to have a subclass with no constructor because
superclass has a parameterless constructor
...
Send us your CV
...
Send us your CV on
www
...
com
Download free eBooks at bookboon
...
On the right:- because superclass has no paramterless constructor, subclass must have a constructor and
it must call super
...
3
...
The sellCopy() method of Publication needs to alter the value of the variable ‘copies’ it can do this even
if ‘copies’ is a private variable
...
There are two ways we can do this…
1) make ‘copies’ ‘protected’ rather than ‘private’ – this makes it visible to subclasses, or
2) create accessor and mutator methods
...
g
...
Thus in the superclass Publication we define ‘copies’ as a variable private but create two methods that
can set and access the value ‘copies’
...
In the superclass Publication we would therefore have…
private int copies;
public int getCopies ()
{
}
return copies;
public void setCopies(int pCopies)
{
}
copies = pCopies;
Download free eBooks at bookboon
...
As currently written they don’t actually impose any restrictions, but suppose for example we wanted to
make sure ‘copies’ is not set to a negative value
...
e
...
We might even consider making these methods protected rather than public themselves so their use is
restricted to subclasses only and other classes cannot interfere with the value of ‘copies’
...
8
mCopies = mOrderQty
Abstract Classes
The idea of a Publication which is not a Book or a Magazine is meaningless, just like the idea of a Person
who is neither a MalePerson nor a FemalePerson
...
Download free eBooks at bookboon
...
g
...
As Publication will never be instantiated ie
...
We can enforce the fact that Publication is non-instantiable by declaring it ‘abstract’:abstract class Publication
{
// etc
...
9
Overriding Methods
A subclass inherits the methods of its superclass and must therefore always provide at least that set of
methods, and often more
...
This is overriding the method
...
AXA Global
Graduate Program
Find out more and apply
Download free eBooks at bookboon
...
For example, imagine a special category of magazine which has a disc attached to each copy – we can
call this a DiscMag and we would create a subclass of Magazine to deal with DiscMags
...
Therefore we want some additional functionality in the recvNewIssue()
method to remind us to do this
...
Note: when a new issue of Magazine arrives, as these don’t have a disc we want to invoke the original
recNewIssue() method defined in the Magazine class
...
When we call the recvNewIssue() method on a Magazine it is the method in the superclass that
is invoked
...
No additional instance
variables or methods are required though it is possible to create some if there was a need
...
Download free eBooks at bookboon
...
recvNewIssue(pNewIssue);
System
...
println("Check discs attached to this
magazine");
}
}
Note the user of the super keyword to call a method of the superclass, thus re-using the existing
functionality as part of the replacement, just as we do with constructors
...
Operations
Formally, ‘recvNewIssue()’ is an operation
...
However this distinction is an important part of
‘polymorphism’ which we will meet in Chapter 4
...
10
The ‘Object’ Class
In Java all objects are (direct or indirect) subclasses of a class called ‘Object’
...
Thus this class exists in every Java program ever created
...
Object defines no instance variables but several methods
...
An example is the toString() method
...
If our classes are organised into a hierarchy then the topmost superclass in the hierarchy is a direct
subclass of object, and all others are indirect subclasses
...
com
68
Object Oriented Programming Using Java
Inheritance and Method Overriding
Thus directly, or indirectly, all classes created in Java inherit toString()
...
com/Mitas
www
...
com
Ma
Month 16
I was a construction
Mo
supervisor ina const
I was
the North Sea super
advising and the No
he
helping foremen advis
s Real work
solve problems
he
helping fo
International
Internationa opportunities
al
�ree wo placements
work
or
s
solve pr
Download free eBooks at bookboon
...
11
Inheritance and Method Overriding
Overriding toString() defined in ‘Object’
The Object class defines a toString() method, one of several useful methods
...
The version of toString() defined
by Object produces output like: “Book@11671b2”
...
However to be generally useful we need to override this to give a more meaningful string
...
toString() + " by " + mAuthor;
In Magazine
public String toString()
{
}
return super
...
overridden,
so that Publication
...
The toString() method has been overridden again in Book such that Book
...
Ie
...
Thus if Publication
...
toString() would automatically return the title, ISBN number and author
...
toString() returns title (via superclass toString() method) and issue
Download free eBooks at bookboon
...
We could choose to provide more data (i
...
more, or even all, of the instance variable values) in these
strings
...
In this case title and author for a book, or title and current issue for a magazine,
serve well to uniquely identify a particular publication
...
12 Summary
Inheritance allows us to factor out common attributes and behaviour
...
Subclasses are used to model specialized attributes and behaviour
...
If we amend or improve code for a superclass it impacts
on all subclasses
...
Special rules apply to constructors for subclasses
...
e
...
We can ‘override’ inherited methods so a subclass implements an operation differently from its superclass
...
Download free eBooks at bookboon
...
Objectives
By the end of this chapter you will be able to…
• Understand how polymorphism allows us to handle related classes in a generalized way
• Employ polymorphism in Java programs
• Understand the implications of polymorphism with overridden methods
• Define interfaces to extend polymorphism beyond inheritance hierarchies
• Appreciate the scope for extensibility which polymorphism provides
This chapter consists of eight sections:1) Class Types
2) Substitutability
3) Polymorphism
4) Extensibility
5) Interfaces
6) Extensibility Again
7) Distinguishing Subclasses
8) Summary
4
...
com
72
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
If you were asked to give someone a pig you could give them Pinky or any other pig
...
g
...
If you were asked to give someone an animal you could give
them Pinky, any other pig, any other mammal or any other animal (bird, fish, insect etc)
...
This is true in object oriented programs as well
...
Types
determine compatibility between variables, parameters etc
...
Following this we can substitute objects of a subtype whenever objects of a supertype are
required (as in the example above)
...
93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION
MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
THAT THE CAPITAL OF SPAIN OFFERS
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
PROFESSIONAL GOALS
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
EXPERIENCE
5 Specializations
Personalize your program
www
...
edu/master-management
#10 WORLDWIDE
MASTER IN MANAGEMENT
FINANCIAL TIMES
mim
...
edu
Length: 1O MONTHS
Av
...
com
73
Click on the ad to read more
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
In other words we can ‘substitute’ an object of any subclass where an object of a superclass is required
...
e
...
Publication p = new DiscMag(…);
This is OK because DiscMag is a subclass of Magazine which is a subclass of
Publication ie
...
Magazine m = new DiscMag(…);
This is OK because DiscMag is a subclass of Magazine
DiscMag dm = new Magazine(…);
This is illegal because Magazine is a SUPERclass of DiscMag
Publication p = new Publication(…);
This is illegal because Publication is an abstract class and therefore cannot
be instantiated
...
com
74
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
4
...
However this has implications for the design of subclasses – we need to make
sure they are genuinely substitutable for the superclass
...
Thus while a subclass may have additional methods
it must at least have all of the methods defined in the superclass and should therefore be substitutable
...
Therefore when overriding methods, while it is perfectly acceptable to tailor the method to the needs
of the subclass a method should not be overridden with functionality which performs an inherently
different operation
...
However, it extends that functionality in a way specifically relevant to DiscMags
by displaying a reminder to check the cover discs
...
Note that a subclass can never remove an operation inherited from its superclass(es) – this would break
the guarantee
...
It is quite likely that we would choose to override the toString() method (initially defined within ‘Object’)
within Publication and override it again within Magazine so that the String returned provides a better
description of Publications and Magazines
...
Doing this would break the substitutability principle
...
com
75
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
4
...
Furthermore because a superclass guarantees certain operations in its subclasses
we can invoke those operations without caring which subclass the actual object is an instance of
...
Thus a Publication comes in various shapes…it could be a Book, Magazine or DiscMag
...
Polymorphism is a fancy name for a common idea
...
There will be lots of
differences between any two cars, but you can think of them as subclasses of a superclass which defines
these crucial shared ‘operations’
...
Whichever, it has a sellCopy() method
...
com
76
Click on the ad to read more
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
So we can invoke p
...
This can make life a lot simpler when we are manipulating objects within an inheritance hierarchy
...
g
...
Polymorphism makes it very easy to extend the functionality of our programs as we will see in Chapter 11
...
4 Extensibility
Huge sums of money are spent annually creating new computer programs but over the years even more
is spent changing and adapting those programs to meet the changing needs of an organisation
...
Of course the application of good programming standards, commenting and
layout etc, have a part to play here but also polymorphism can help as it allows programs to be made
that are easily extended
...
Without
polymorphism we would need separate methods for each type of item:
sellBook (Book pBook)
sellMagazine (Magazine pMagazine)
sellDiscMag (DiscMag pDiscMag)
With polymorphism we need only
sellItem (Publication pPub)
Every subclass is ‘type-compatible’ with its superclass
...
This also has important implications for extensibility of systems
...
Download free eBooks at bookboon
...
Thus we can call:p
...
If ‘p’ is a Magazine, again at
runtime Java will determine this and invoke the sellCopy() method for a Magazine
...
Implementing CashTill
The code below shows how CashTill can be implemented to make use of Polymorphism
...
getPrice();
pPub
...
out
...
getPrice() + "\nSubtotal = " +
runningTotal);
}
{
}
public void showTotal()
System
...
println ("GRAND TOTAL: " + runningTotal);
}
Download free eBooks at bookboon
...
The
constructor simply initializes this to zero
...
It takes a Publication parameter, which may be a
Book, Magazine or DiscMag
...
Then the sellCopy() operation is invoked on the publication
...
g
...
75
Subtotal = 2
...
This implicitly
invokes the toString() method for the subclass of this object, and remember that toString() is different
for books and magazines
...
”
CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www
...
nl/feb/education
Download free eBooks at bookboon
...
What is actually passed will of course be an object of one of the concrete types
descended from Publication
...
a) Publication p = new Publication(…); p
...
recvNewIssue();
c) Publication p = new Magazine(…); p
...
recvNewIssue();
e) Magazine m = new Magazine(…); m
...
com
80
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
Activity 2
Look at the diagram below and, assuming Publication is not an abstract type, decide
which of the pairs of operations shown are legal
...
sellCopy();
Publication p = new Publication(…); p
...
sellCopy();
Publication p = new Magazine(…); p
...
recvNewIssue();
Feedback 2
a) Legal – you can invoke sellCopy() on a publication
b) Illegal – the recNewIssue() method does not exist in publications
c) Legal – Magazine is a type of Publication and therefore you can assign an object
of type Magazine to a variable of type Publication (you can always substitute
subtypes where a supertype is requested)
...
The publication happens to be a magazine but this is irrelevant as far
as the compiler knows in this instance ‘p’ is just a publication
...
e) Legal – m is a magazine and we can invoke this method on magazines
...
com
81
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
Activity 3
Look at the diagram below and, noting that Student is an abstract class, decide which
of the following code segments are valid…
<
Student
Lecturer
printTimetable()
help(Student pStudent)
PtStudent
FtStudent
applyForJob()
applyForLoan()
Note FtStudent is short for Full Time Student and PtStudent is short for
Part Time Student
...
help(s);
b) Student s = new FtStudent(); Lecturer l = new Lecturer(); l
...
FtStudent is a type of Student and can be assigned to variable of
type Student
...
help()
Download free eBooks at bookboon
...
help(s);
<
Student
Lecturer
printTimetable()
help(Student pStudent)
PtStudent
FtStudent
applyForJob()
applyForLoan()
a) pStudent
...
applyForLoan();
American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:
▶▶ enroll by September 30th, 2014 and
▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www
...
com to
find out more!
Note: LIGS University is not accredited by any
nationally recognized accrediting agency listed
by the US Secretary of Education
...
Download free eBooks at bookboon
...
b) Not Valid! While we can invoke this method on a FtStudent object, and we are
passing an FtStudent object as a parameter to the help() method, the help()
method cannot know that the object passed will be a FtStudent (it could be any
object of type Student)
...
Hence this line of code would generate a compiler error
...
5 Interfaces
There are two aspects to inheritance:
• the subclass inherits the interface (i
...
access to public members) of its superclass – this
makes polymorphism possible
• the subclass inherits the implementation of its superclass (i
...
instance variables and method
implementations) – this saves us copying the superclass details in the subclass definition
In Java, the extends keyword automatically applies both these aspects
...
It’s interface must include all of the interface of its superclass, though the
implementation of this can be different (though overriding) and the interface of the subclass may be
more extensive with additional features being added
...
This might be because:• they aren’t really related by a true ‘is a’ relationship
• we want a class to have interfaces shared with more than one would-be superclass, but Java
does not allow such ‘multiple inheritance’
• we want to create a ‘plug and socket’ arrangement between software components, some of
which might not even be created at the current time
...
Be careful of the term ‘interface’ – in Java programming it has at least three meanings:
1) the public members of a class – the meaning used above
2) the “user interface” of a program, often a “Graphical User Interface” – an essentially
unrelated meaning
3) a specific Java construct which we are about to meet
Download free eBooks at bookboon
...
e
...
This is why the CashTill class can deal with a ‘Publication’ without worrying of which specific subclass
it is an instance
...
)
Tickets
Now consider the possibility that in addition to books and magazines, we now want to sell tickets, e
...
for entertainment events, public transport, etc
...
However we do want to make them both acceptable to CashTill as
things to sell and we need a mechanism for doing this
...
Download free eBooks at bookboon
...
However the sellCopy() method is very different form the sellCopy() method defined in Publication
...
Download free eBooks at bookboon
...
out
...
out
...
out
...
out
...
out
...
But we do want to be
able to check tickets through the till as we can with publications
...
In fact CashTill can sell anything that has these methods not
just Publications
...
interface SaleableItem
{
}
public void sellCopy ();
public double getPrice ();
Note that the interface defines purely the signatures of operations without their implementations
...
Download free eBooks at bookboon
...
That is left to classes which implement the interface
...
The SaleableItem interface says “I undertake to provide, at least,
methods with these signatures:
public void sellCopy ();
public double getPrice ();
though I might include other things as well”
Where more than one class implements an interface it provides a guaranteed area of commonality which
polymorphism can exploit
...
They certainly are not related by any “is a” relationship –
they are entirely different kinds of things, one a vehicle, the other an arcade game
...
We now need to state that both Publication (and all its subclasses) and Ticket both offer the operations
defined by this interface:
class Publication implements SaleableItem
{
}
[
...
]
class Ticket implements SaleableItem
{
}
[
...
]
Contrast implements with extends
...
• implements gives a guarantee that the operations specified by an interface will be
provided – this is enough to allow polymorphic handling of all classes which implement a
given interface
Download free eBooks at bookboon
...
Any class which implements the interface is acceptable for assignment to the variable/parameter
because the interface is a type and all classes implementing it are subtypes of that type
...
Download free eBooks at bookboon
...
The relationships from Publication and Ticket to SaleableItem are like inheritance arrows except that
the lines are dotted – this shows that each class implements the interface
...
6
Extensibility Again
Polymorphism allows objects to be handled without regard for their precise class
...
For example, we could create new classes for more products or services and so long as they implement
the SaleableItem interface the CashTill will be able to process them without a single change to its code!
An example could be ‘Sweets’
...
We can define
the price of the sweets depending upon the weight and then sell the sweets by subtracting this weight
from our total stock
...
However if we create a class ‘Sweets’ that implements the SaleableItem interface our enhanced polymorphic
cash till can sell them because it a sell any SaleableItem
...
com
90
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
In this case, without polymorphism we would need to add an additional “sale” method to CashTill to
handle Tickets, Sweets and further new methods for every new type of product to be sold
...
Poymorphism
makes it easy to extend our programs and this is very important
...
Think
of the number of different electrical appliances which can be lugged into a standard power socket – and
imagine how inconvenient it would be if instead you had to call out an electrician to wire up each new
one you bought!
Activity 5
Adapt the following diagram by adding a class for Diesel cars in such a way that it can
be used to illustrate polymorphism
...
Here Mechanic is directly interacting with Car
...
g
...
g
...
These are all different (different shapes) and yet Mechanic can still interact
with them as they are all Cars
...
If an ElectricCar class was added Mechanic would still be able to work with them
without making any changes to the Mechanic class
...
com
91
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
Activity 6
Assume Car has a fixEngine() method that is overridden in DieselCar but not
overridden in PetrolCar (as shown on the diagram below)
...
fixEngine();
b) If a DiesalCar object was passed to the repair() method which actual method
would be invoked by pCar
...
mastersopenday
...
com
92
Click on the ad to read more
Object Oriented Programming Using Java
Object Roles and the Importance of Polymorphism
Feedback 6
a) Yes! We can apply the method fixEngine() to any Car object as it is defined in the
class Car
...
The method must be defined in the
class Car else the compiler will complain at compile time
...
Clever stuff given that
the repairCar() method is unaware of which type of car is actually passed
...
7
Distinguishing Subclasses
What if we have an object handled polymorphically but need to check which subtype it actually is? The
instanceof operator can do this:
object instanceof class
This test is true if the object is of the specified class (or a subclass), false otherwise
...
Strictly instanceof is testing whether the item on the left is of the type, or a subtype of, the type specified
on the right
...
public void saleType (SaleableItem pSelb)
{
if (pSelb instanceof Publication)
{
}
System
...
println("This is a Publication");
else if (pSelb instanceof Ticket)
{
}
System
...
println("This is a Ticket");
else
{
}
}
System
...
println("This is a an unknown sale type");
Download free eBooks at bookboon
...
e
...
If we wished to we could equally test for a more specific subtype, e
...
pSelb instanceof Book
Notice that once we compromise the polymorphism by checking for subtypes we also compromise the
extensibility of the system – new classes (e
...
Sweets) implementing the SaleableItem interface may
also require new clauses adding to this if statement, so the change ripples through the system with the
consequence that it becomes more costly and error-prone to maintain
...
g
...
Thus each subtype would display
a message giving the type of item being sold
...
describeSelf()
...
4
...
Polymorphism makes it easy to extend our programs by adding additional classes without needing to
change other classes
...
Java ensures that the appropriate method for the actual class of the object is invoked at run-time
...
The ‘interface’ construct allows us to provide shared interfaces (i
...
collections of
operations) in this situation
...
Any number of classes can implement a particular interface
...
com
94
Object Oriented Programming Using Java
Overloading
5 Overloading
Introduction
This chapter will introduce the reader to the concept of method overloading
Objectives
By the end of this chapter you will be able to…
• Understand the concept of ‘overloading’
• Appreciate the flexibility offered by overloading methods
• Identify overloaded methods in the online API documentation
This chapter consists of the following three sections:1) Overloading
2) Overloading To Aid Flexibility
3) Summary
Download free eBooks at bookboon
...
1 Overloading
Historically in computer programs method names were required to be unique
...
However several methods were often required to perform very similar functionality for example a method
could add two integer numbers together and another method may be required to add two floating point
numbers
...
We
could therefore call one method addInt() and the other addFloat() but this could lead to a proliferation
of names each one describing different methods that are essentially performing the same operation ie
...
To overcome this problem in Java you are not required to give each method a unique name – thus both
of the methods above could be called add()
...
ie
...
It does this by looking at the parameter list
...
:add(int number1, int number2)
add(float number1, float number2)
This is resolved at run time by the JRE
...
e
...
If two integers are being passed then the first method is invoked
...
Overloading refers to the fact that several methods may share the same name
...
5
...
Download free eBooks at bookboon
...
A method would probably be required to enrol, or
register, a new student
...
Thus given a call to
enrollStudent(“Fred”, “123 Abbey Gardens”, “G700”)
the JRE would use the first method
...
This method could take two parameters:- the account identity (a String) and the
amount of cash required by the user (int)
...
Identify another variation of the withdrawCash() method that takes a different
parameter list that may be a useful variation of the method above
...
These methods essentially perform the same operation but by overloading this
method we have made the system more flexible – users now have a choice they
can specify the amount of cash to be withdrawn or they can accept the default
sum specified
...
Constructors can be overloaded as well as ordinary methods
...
com
97
Object Oriented Programming Using Java
Overloading
Activity 2
Go online and look at the Java Standard Edition API documentation by 1) going
online to java
...
com/javase 2) following the link to the API 3) selecting the link for
Core API documents for the latest version
...
sun
...
Scroll down this list until you find the String class
...
lang package in the upper left window (as the String class is
in this package)
...
Feedback 2
The String class specifies 15 different constructors
...
One of these constructors takes no parameters and creates an empty String object
...
By massively overloading the Sting constructor the creators of this class have
provided flexibility for other programmers who may wish to use these different
options in the future
...
Find out what you can do to improve
the quality of your dissertation!
Get Help Now
Go to www
...
co
...
com
98
Click on the ad to read more
Object Oriented Programming Using Java
Overloading
We can make our programs more adaptable by overloading constructors and other methods
...
Activity 3
Still looking at the String class in the API documentation find other methods that
are overloaded
...
These include:- format(), indexOf(), replace(), split(), subString() and valueOf()
...
When we use the subString() method the JRE will select the correct implementation
of this method, at run time, depending upon whether or not we have provided one
or two parameters
...
3 Summary
Method overloading is the name given to the concept that several methods may exist that essentially
perform the same operation and thus have the same name
...
If two or more methods have the same name then their parameter list must be different
...
By overloading constructors and ordinary methods we are providing extra flexibility to the programmers
who may use our classes
...
Download free eBooks at bookboon
...
Leading
the reader to an understanding of how to get from a preliminary specification to an Object Oriented
Architecture
...
Already today, SKF’s innovative knowhow is crucial to running a large proportion of the
world’s wind turbines
...
These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication
...
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations
...
Visit us at www
...
com/knowledge
Download free eBooks at bookboon
...
1
Requirements Analysis
The development of any computer program starts by identifying a need:• An engineer who specialises in designing bridges may need some software to create three
dimensional models of the designs so people can visualise the finished bridge long before it
is actually built
...
But how do we get from a ‘need’ for some software to an object oriented software design that will meet
this need?
Some software engineers specialise in the task of Requirement Analysis which is the task of clarifying
exactly what is required of the software
...
Download free eBooks at bookboon
...
given a description of a system how do we convert this into
a potential OO design
...
Producing simple and elegant designs is important if we want the software to work well and be easy to
develop however identifying good designs from weaker designs is not simple and experience is a key factor
...
Similarly experience is essential
to becoming skilled at performing user requirements analysis and in producing good designs
...
Starting with a problem specification we will work through the following steps:• Listing Nouns and Verbs
• Identifying Things Outside The Scope of The System
• Identifying Synonyms
• Identifying Potential Classes
• Identifying Potential Attributes
• Identifying Potential Methods
• Identifying Common Characteristics
• Refining Our Design using CRC Cards
• Elaborating Classes
By doing this we will be able to take a general description of a problem and generate a feasible, and
hopefully elegant, OO design for a system to meet these needs
...
2
The Problem
The problem for which we will design a solution is ‘To develop a small management system for an
athletic club organising a marathon
...
Download free eBooks at bookboon
...
A field comprising both world-ranking professionals and charity fund-raising amateurs
(some in fancy dress!) will compete on the 26
...
As part of the software system which will track runners and announce the results and sponsorship
donations, a model is required which represents the key characteristics of the runners (this will
be just part of the finished system)
...
A runner is described as e
...
“Runner 42” where 42
is their number
...
Their result status can be checked and will be displayed as either “Not finished” or “Finished
in hh:mm:ss”
...
Further to the above, a professional additionally has a world ranking and is described as e
...
“Runner 174 (Ranking 17)”
...
When an
amateur finishes the race they print a collection list from their sponsorship form
...
com
103
Click on the ad to read more
Object Oriented Programming Using Java
Object Oriented Software Analysis and Desig
A sponsorship form has the number of sponsors, a list of the sponsors, and a list of amounts
sponsored
...
A fancy dress runner is a kind of amateur (with sponsorship etc
...
g
...
6
...
• The verbs indicate actions to be performed some of these will appear in the final system
as methods
...
g
...
g
...
Activity 1
Look at the description above list five nouns and five verbs (use noun and verb
phrases where appropriate)
...
Nouns:- GetFit Althletic Club, field, world ranking professional, fund-raising amateur,
fancy dress, 26
...
Verbs:- Organise, marathon, compete, track runners, announce results, describe
(runner), finish race, specify time, check status, display status, describe (professional),
print collection list, add (sponsor and amount), print list, describe (fancy dress runner)
Download free eBooks at bookboon
...
4
Object Oriented Software Analysis and Desig
Identifying Things Outside The Scope of The System
An important part in designing a system is to identify those aspects of the problem that are not relevant
or outside the scope of the system
...
e
...
Furthermore while parts of the description may refer to tasks that are performed by users
of the system as they are using the system, and thus describe functions that need to be implemented
within the system, other parts may describe tasks performed by users while not using the system – and
thus don’t describe functions within the system
...
Activity 2
Look at the list of nouns and verbs above and identify one of each that is outside the
scope of the system
...
We also need to look at other parts of the
description to identify parts that are not relevant
...
It is not an entity we need to model within the system
...
Again we do not need to model this as an object
within the system
...
Verbs:Organise – this is an activity done by members of the athletic club, these
may be users of the system but this is not an activity that they are using the
system for
...
It is not something the system
needs to do
...
Therefore this in NOT in fact outside the
scope of the system
...
com
105
Object Oriented Programming Using Java
6
...
It is important to identify these in the description
of the system
...
Activity 3
Look at the list of nouns and verbs and identify two synonyms, one from the list of
nouns and one from the verbs
...
com
106
Click on the ad to read more
Object Oriented Programming Using Java
Object Oriented Software Analysis and Desig
Feedback 3
Synonyms
Nouns:•
•
•
world ranking professional=professional runner
fund-raising amateur=amateur runner
runner=competitor
Note runner is not a synonym of professional runner as some runners are amateurs
...
6
marathon=compete
check status=display status
print collection list = print list
finish race = record specified time
Identifying Potential Classes
Having simplified the problem by identifying aspects that are outside the scope of the system and by
identifying different parts of the description that are in reality describing the same entities and operations
we can now start to identify potentials classes in the system to be implemented
...
Good OO design suggests that data and operations should be packaged together – thus classes represent
complex conceptual entities for which we can identify associated data and operations (or methods)
...
Activity 4
Look at the list of nouns above and identify five that could become classes
...
com
107
Object Oriented Programming Using Java
6
...
Activity 5
Look at the list of nouns and identify one that could become an attribute of the class
‘Runner’ and one for the class ‘FancyDresser’
...
For Runner: number,
resultStatus ie
...
6
...
Activity 6
Look at the list of verbs and identify one that could become a method of the class
‘Runner’ and one for the class ‘FancyDresser’
...
For Runner:
describe (this will actually become an overridden version of toString())
finishRace
displayStatus
For FancyDresser:
describe (toString() will need to be overridden again to encompass the
description of the costume)
Of course we need to identify all of the methods for all of the classes
...
com
108
Object Oriented Programming Using Java
6
...
Activity 7
Look at the list of classes below and place four into an appropriate inheritance
hierarchy
...
com
109
Click on the ad to read more
Object Oriented Programming Using Java
Object Oriented Software Analysis and Desig
Feedback 7
The most general class i
...
the one at the top of the inheritance tree is ‘Runner’
...
We can fit these into an inheritance hierarchy because these classes are all related
by an is-a relationship
...
A
Professional is-a Runner as well
...
This class will be related to one of the other classes by some form of an association
...
There is therefore an association between
Amateur and SponsoshipFrom
...
6
...
However in a real world system the problem
would be larger and less well-defined than the problem we are working on here and the analysis and
refinement of design would therefore be a longer more complex process that we can realistically simulate
...
One method of doing checking our designs is to document our designs using CRC cards and to check
if these work by role-playing different scenarios
...
CRC stands for Class, Responsibilities and Collaborations
...
Download free eBooks at bookboon
...
the methods) though on a CRC card these are not as precisely defined as on a UML diagram
...
The diagram below shows CRC cards developed for two classes in the system
...
If not we can amend before getting into the time consuming process of programming a flawed plan
...
In this case by looking at
the CRC cards above a Runner is able to record sponsorship information in collaboration with the
SponsorshipForm class
...
Testing out a range of scenarios may highlight flaws in our system designs that we can then fix – long
before any time has been wasted by programming weak designs
...
com
111
Object Oriented Programming Using Java
6
...
To do this
we need to take our general specification documented via CRC cards and our resolve any ambiguities
e
...
exact data types
...
com
112
Object Oriented Programming Using Java
Object Oriented Software Analysis and Desig
6
...
Turning a complex requirements specification into an elegant simple object oriented architectural design
is a skilled task that requires experience
...
Through a sequence of tasks we have seen how to analyse a textual description of a problem
...
g
...
• Document the resulting classes using CRC cards and tested the validity of our design by
role-playing a range of scenarios and amending our designs as appropriate
• Finally we can elaborate these details and document the results using a class diagram
...
Download free eBooks at bookboon
...
Objectives
By the end of this chapter you will be able to…
• Understand the basic concepts of the Java Collections Framework
• Contrast the characteristics of various Collections interfaces
• Understand the related concept of an iterators
Challenge the way we run
EXPERIENCE THE POWER OF
FULL ENGAGEMENT…
RUN FASTER
...
RUN EASIER…
READ MORE & PRE-ORDER TODAY
WWW
...
COM
1349906_A6_4+0
...
com
22-08-2014 12:56:57
114
Click on the ad to read more
Object Oriented Programming Using Java
The Collections Framework
This chapter consists of twelve sections:1) An Introduction to Collections
2) Collection Interfaces
3) Old and New Collections
4) Lists
5) Sets
6) Maps
7) Collection Implementations
8) Overview of the Collections Framework
9) An Example Using Un-typed Collections
10) An Example Using Typed Collections
11) A Note About Sets
12) Summary
7
...
Arrays
provide one means of doing this, but the Java Collections support much more varied and flexible forms
of grouping
...
The
Java platform provides a ‘Collections Framework’, a consistent set of interfaces and implementations
• interfaces define the available functionality
• implementations influence other issues including performance
7
...
This defines methods that are
at the core of the framework
...
Note that because these are interfaces, not classes, they only define operation signatures, not any aspect
of their implementation as methods
...
This is not an extension of Collection – this is because maps
do not entirely fit in to the Collection hierarchy for reasons we will see later, although they are still part
of the ‘Collections Framework’
...
com
115
Object Oriented Programming Using Java
The Collections Framework
Thus we have the following interfaces…
• Collection: the most general grouping
-- List: a collection of objects (which can contain duplicates) held in a specific order
-- Set: a collection of unique objects in no particular order
-- SortedSet: a set with objects arranged in ascending order
• Map: a collection of unique ‘keys’ and associated objects
-- SortedMap: a map with objects arranged in ascending order of keys
Just as List and Set extend the Collection interface, SortedSet is an extension of Set and SortedMap is
an extension of Map
...
7
...
4, collections held items of type Object – i
...
objects of any class since all are subclasses
of Object
...
However when objects are taken out of a
collection the compiler does not know what the object is and this can cause some additional complications
...
Thus in
Java JDK 5
...
‘Generics’ allow a class to be defined without specifying the
types of data items it handles
...
Thus using ‘generics’ we can create collections that only store objects of a specified type
...
4 Lists
Lists are the most commonly used type of collection – where you might have used an array, a List will
often provide a more convenient method of handling the data
...
They are
in many ways like arrays, but are more flexible as they are automatically resized as data is added
...
Lists store items in a particular sequence (though not necessarily sorted into
any meaningful order) and duplicate items are permitted
...
com
116
Object Oriented Programming Using Java
The Collections Framework
7
...
They are based on the mathematical idea of a ‘set’ – a
grouping of ‘members’ that can contain zero, one or many distinct items
...
Download free eBooks at bookboon
...
7
...
The pair is made up of a ‘key’ and a ‘value’
...
The value is a piece of information or an object associated with the key
...
There is only one value for each key, but since values are objects they can contain several pieces of data
...
So in the previous example if you looked
up two people in the address book you may find them living at the same address – but one person would
not have two homes
...
Download free eBooks at bookboon
...
1) We want to record the members of a club
...
3) We want to record bank account details – each identified by a bank
account number
Feedback 1
1) For this we would use a Set
...
2) For this we would use a List – this would record the items bought in the
order in which they were purchased
...
7
...
To actually use them we need classes which implement these interfaces
...
com
119
Object Oriented Programming Using Java
The Collections Framework
The implementations shown here are all part of the Java platform library packages, but programmers
can also write implementations of their own for special purposes
...
it provides us with a
SortedSet
• HashMap implements the Map interface
-- It provide fast access but the items are unordered
• and TreeMap which also implements the Map interface
-- slower than a HashMap it maintain elements in order of the Key ie
...
www
...
com
We do not reinvent
the wheel we reinvent
light
...
An environment in which your expertise is in high
demand
...
Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future
...
Light is OSRAM
Download free eBooks at bookboon
...
8
The Collections Framework
Overview of the Collections Framework
The diagram below gives us a slightly simplified overview of the collections framework
...
Remember, interfaces have no implementation
within them, they just contain public method signatures with must be fulfilled by any class implementing
that interface
...
Arrows with solid lines denote inheritance; e
...
the Set interface
extends the Collection interface
...
g
...
This is because, unlike Lists and Sets which store
individual objects, Maps store pairings of key objects and value objects
...
Activity 2
Documentation for all the collections interfaces and implementations is available to
browse online or download at:
http://java
...
com/javase/6/docs/api/
The interfaces and implementation classes of the Collections Framework can all be
found in the java
...
Use the online API documentation to find the methods for an ArrayList
...
Download free eBooks at bookboon
...
get() – which returns the object at a specified position and
remove() – which removes an object from a list
Note some of these methods are overloaded such as remove() which can
either remove an object at a specified position or remove the first instance of a
specified object
...
360°
thinking
...
Discover the truth at www
...
ca/careers
© Deloitte & Touche LLP and affiliated entities
...
deloitte
...
Download free eBooks at bookboon
...
Discover the truth at www
...
ca/careers the ad to read more
122
Click on
© Deloitte & Touche LLP and affiliated entities
...
9
The Collections Framework
An Example Using Un-typed Collections
The code below shows an example of an Un-typed list of Strings
...
util
...
util
...
util
...
add(pStr);
}
/**
* Insert a string at a specified position in the list
* @param pPos position at which string to be added
*
(0 = before first)
* @param pStr string to be added to list
*/
public void insertString(int pPos, String pStr)
{
mAList
...
remove(pPos);
}
Download free eBooks at bookboon
...
iterator();
while (it
...
next();
System
...
print(nextItem + " ");
}
System
...
println();
}
}
We will turn your CV into
an opportunity of a lifetime
Do you like cars? Would you like to be a part of a successful brand?
We will appreciate and reward both your enthusiasm and talent
...
You will be surprised where it can take you
...
employerforlife
...
com
124
Click on the ad to read more
Object Oriented Programming Using Java
The Collections Framework
Mostly the code above is self explanatory however perhaps the display method needs some explanation
...
Note – this is not a simple
process as each collection can be made up of different objects but, thankfully the hard work has been
done for us
...
The method
iterator() is then invoked on our specific collection thus returning an object capable of iterating around
our List of Strings
...
Thus the loop above iterates around the list rerunning and displaying each object
...
This will cause a compiler warning as this will fail if we add non String objects
to the list
...
7
...
0
introduced an improved for loop that can loop through every item in a typed collection without using
a loop counter (or iterator)
...
com
125
Object Oriented Programming Using Java
The Collections Framework
Hence see example below…
...
util
...
util
...
out
...
out
...
You can think of < > syntax to mean ‘of ’ ie in this case a list of strings
Appending, inserting and deleting elements is just the same as with untyped collections however
displaying the collection is much simpler as we know what each element of the list contains
...
Download free eBooks at bookboon
...
Note nextItem is defined as a String
variable because here we are using a list of Strings
...
7
...
Sets don’t allow duplicate object to be stored
...
Are two object only the same if the name of the object is the same – or could they
be the same if some of the data is identical?
Consider a set of bank accounts:-
AXA Global
Graduate Program
Find out more and apply
Download free eBooks at bookboon
...
However unless told otherwise Java will treat the two object below as different objects as
both objects have different names (Account1 and Account2) and thus while Sets do not allow duplicates
objects inside them both of these accounts could be created and added to a set
...
We can do this as below…
public boolean equals (Object pObj)
{
}
Account account = (Account) pObj;
return (accountNumber
...
accountNumber);
This overrides Object
...
com
128
Object Oriented Programming Using Java
The Collections Framework
Even though it will always be an Account object passed as a parameter, we have to make the parameter
an Object type (and then cast it to Account) in order to override the equals() method inherited from
Object which has the signature
public boolean equals (Object obj)
(You can check this in the “API and Language” section of the JDK documentation
...
equals()
...
One additional complication concerns how objects are stored in sets
...
However two accounts with the same accountNumber should generate the
same hashcode even if the object name is different
...
We can ensure that the hashcode generated
is based on the account number by overriding this method as shown below…
...
hashCode();
The simplest way to redefine hashCode for an object is to join together the instance values which are
to define equality as a single string and then take the hashcode of that string
...
It looks a little strange, but we can use the hashCode() method on this String even though we are
overriding the hashCode() method for objects of type Account
...
Occasionally the same
hash code may be produced for different key values, but that is not a problem
...
com
129
Object Oriented Programming Using Java
The Collections Framework
By overriding equals() and hashCode() methods Java will prevent objects with duplicate data (in this
case with duplicate account numbers) from being added to sets
...
Amend this so this will work
find a Publication in a set of Publications (called publicationSet)
...
contains(pStr);
if (found)
{
System
...
println("Element " + pStr + " found in set");
}
else
{
System
...
println("Element " + pStr + " NOT found in set");
}
}
I joined MITAS because
I wanted real responsibili�
I joined MITAS because
I wanted real responsibili�
Real work
International
Internationa opportunities
al
�ree wo placements
work
or
�e Graduate Programme
for Engineers and Geoscientists
Maersk
...
discovermitas
...
com
130
�e G
for Engine
Click on the ad to read more
Object Oriented Programming Using Java
The Collections Framework
Feedback 3
public void findPublication(Publication pPub)
{
boolean found;
found = publicationSet
...
out
...
out
...
1) Could the code above be used to store a collection of books?
2) Could it store a combination of books and magazines?
3) If a book was found in the set what would the following line of code do?
System
...
println(“Element “ + pPub + “ found in set”);
Feedback 4
1) Yes
2) Yes
3) pPub would invoke the toString() method on the publication
...
Download free eBooks at bookboon
...
12 Summary
The Java ‘Collections Framework’ provides ready-made interfaces and implementations for storing
collections of objects
...
There are ‘untyped’ collections, and as of JDK 5
...
Collection interfaces include List, Set and Map, each defining appropriate operations
...
Special attention is required when defining objects to be stored in Sets (or as keys in Maps) to define
the meaning of ‘duplicate’
...
While we have not been able to provide a detailed discussion of collection in this chapter the case study,
in Chapter 11, will demonstrate the use of Maps and Sets for storing our own objects (not just Strings)
...
93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION
MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
THAT THE CAPITAL OF SPAIN OFFERS
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
PROFESSIONAL GOALS
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
EXPERIENCE
5 Specializations
Personalize your program
www
...
edu/master-management
#10 WORLDWIDE
MASTER IN MANAGEMENT
FINANCIAL TIMES
mim
...
edu
Length: 1O MONTHS
Av
...
com
132
Click on the ad to read more
Object Oriented Programming Using Java
Java Development Tools
8 Java Development Tools
Introduction
This chapter will introduce the reader to various development tools that support the development of
large scale Java systems (e
...
Eclipse and NetBeans)
...
Objectives
By the end of this chapter you will be able to…
• Understand the roles of the JDK and JRE
• Investigate professional development environments (Eclipse and NetBeans)
• Understand the importance of the Javadoc tool and the value of embedding Javadoc
comments within your code
...
This chapter consists of thirteen sections:1) Software Implementation
2) The JRE
3) Java Programs
4) The JDK
5) Eclipse
6) Eclipse architecture
7) Eclipse Features
8) NetBeans
9) Developing Graphical Interfaces Using NetBeans
10) Applying Layout Managers Using NetBeans
11) Adding Action Listeners
12) The Javadoc Tool
13) Summary
Download free eBooks at bookboon
...
1
Java Development Tools
Software Implementation
Before a computer can complete useful tasks for us (e
...
check the spelling in our documents) software
needs to be written and implemented on the machine it will run on
...
Of course
before the software is written it needs to be designed and at some point it needs to be tested
...
Of particular concern here are the three long established approaches
to getting source code to execute on a particular machine…
• compilation into machine-language object code
• direct execution of source code by ‘interpreter’ program
• compilation into intermediate object code which is then interpreted by run-time system
Implementing Java programs involves compiling the source code (Java) into intermediate object code
which is then interpreted by a run-time system called the JRE
...
Compilation
The compiler translates the source code into machine code for the relevant hardware/OS combination
...
The compiled program then runs as a ‘native’ application for that platform
...
It allows fast execution speeds but requires re-compilation of the program each time the code is changed
...
com
134
Object Oriented Programming Using Java
Java Development Tools
Interpretation
Here the source code is not translated into machine code
...
Download free eBooks at bookboon
...
No re-compilation is required after changing the code, but the interpretation process inflicts a significant
impact on execution speed
...
Intermediate Code
This model is a hybrid between the previous two
...
However, the use of an intermediate code which is then executed by
run-time system software allows the compilation process to be independent of the OS/hardware platform,
i
...
the same intermediate code should run on different platforms so long as an appropriate run-time
system is available for each platform
...
g
...
Download free eBooks at bookboon
...
2
Java Development Tools
The JRE
To run Java programs we must first generate intermediate code (called bytecode) using a compiler
available as part of the Java Development Kit (JDK) – see section 8
...
A version of the Java Runtime Environment (JRE), which incorporates a Java Virtual machine (VM),
is required to execute the bytecode and the Java library packages
...
The Java bytecode is standard and platform independent and as JRE’s have been created for most
computing devices (including PC’s, laptops, mobile devices, mobile phones, internet devices etc) this
makes Java programs highly portable
...
com
137
Object Oriented Programming Using Java
8
...
Options include the use of simple discrete tools (e
...
editor, compiler, interpreter) invoked
manually as required or alternatively the use of an Integrated Development Environment (IDE) which
incorporates these implementation tools behind a seamless interface
...
When writing java programs each class (or interface) in a Java program has its own name
...
These are processed by the compiler to produce name
...
To actually run as an application, one of the classes must contain a main() method with the signature
shown above
...
”
CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www
...
nl/feb/education
Download free eBooks at bookboon
...
4
Java Development Tools
The JDK
To develop Java programs you must first install the Java Development Kit (JDK)
...
sun
...
Prior to version 5
...
5) this
was known as the Java Software Development Kit (SDK)
...
g
...
When using an IDE it is easy to forget that much of the functionality is in fact part of the
JDK and when the IDE is asked to compile a program it is infact just passing on this request to the JDK
sitting underneath
...
Somewhat confusingly the current version of Java is known both as 6
...
6 and even 1
...
0
...
A description of each of these is available from http://java
...
com/
javase/downloads/ and following the links for Documentation, APIs and JDK Programmer guides
...
com
139
Object Oriented Programming Using Java
Java Development Tools
To compile MyProg
...
java
If successful this will create MyProg
...
8
...
With some practice you will soon
find it offers lots of helpful and time-saving facilities that you will not want to work without again…
Eclipse is a flexible and extensible IDE platform
...
eclipse
...
Eclipse was itself written in Java and like all Java programs it needs a JRE to work but using this it will
therefore run on a large range of platforms
...
The Eclipse ‘runtime platform’ is sufficiently flexible that it can even be used as a framework for the
development of applications unrelated to IDEs
...
6
Eclipse Architecture
Because Eclipse relies on the JRE it is intrinsically multi-platform (Windows, Linux, Mac etc
...
Download free eBooks at bookboon
...
)
and languages (including C/C++)
...
zip file from www
...
org
American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:
▶▶ enroll by September 30th, 2014 and
▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www
...
com to
find out more!
Note: LIGS University is not accredited by any
nationally recognized accrediting agency listed
by the US Secretary of Education
...
Download free eBooks at bookboon
...
8
...
These include:• code completion and help facilities,
• a code formatter which can automatically adjust a huge variety of code format aspects,
• powerful facilities to support program development including refactoring (see Chapter 10
section 4) and automatic testing facilities (see Chapter 10 section 5)
...
8 NetBeans
NetBeans is another very powerful IDE, originally developed and distributed by Sun Microsystems,
NetBeans was made open source in 2000 and is extensively supported with plug-ins and video tutorials
developed by the open source community
...
netbeans
...
These
include…
• A quick start guide, on line tutorials and online videos (covering among other topics an
introduction to the IDE, the Javascript debugger, and PHP support)
...
These code completion facilities do far more than cut and paste sample
blocks of text – for example when inserting a constructor for a subclass the code to call a
super-constructor is automatically added and relevant parameters are defined for the subconstructor and passed to the super-constructor
...
Netbeans also includes templates for a range of Java applications including windows, enterprise, web
and mobile applications
...
Thus with
just a few button clicks Netbeans will create a simple Java application with a main method that invokes
a blank GUI as shown below…
Download free eBooks at bookboon
...
While this tool does have its limitations it does not just support the creation of the diagrams but provides
facilities that you may expect from a CASE tool such as automatic code generation (from a diagram) and
reverse engineering (i
...
analysing current code to generate a UML diagram from the code)
...
Method stubs would be created for each of the specified methods
and while the code inside each method would still need to be written the constructor for CurrentAccount
would automatically invoke the constructor for Bank Account passing the parameter pBalance upwards
...
com
143
Object Oriented Programming Using Java
8
...
This tools allows
a window to be created and a range of objects to be dropped onto it including panels, tabbed panes,
scrolled panes, buttons, radio buttons, check boxes, combo boxes, password fields, progress bars, and trees
...
com
144
Click on the ad to read more
Object Oriented Programming Using Java
8
...
Interfaces are thus displayed exactly how they are designed
...
Most PC
games are designed to run on window of 14"–21"
...
However Java programs are expected to be platform independent – one of the strengths of Java is that
code written in Java will work on a PC, laptop or small mobile device irrespective of the hardware or
operating systems these devices use (as long as they all have a JRE)
...
For this reason when developing interfaces
in Java it is usual to give Java some control over deciding exactly how / where to display objects
...
This
has benefits as the display will be reconfigured automatically to fit whatever device is being used to run
the program but this flexibility comes at a cost
...
Layout Managers are ‘objects’ that define how an interface should be displayed and it is normal to create
a layout manager and assign it to a ‘container’ object such as a window frame
...
Using flow layout Java will arrange objects in a row and objects will automatically flow onto
another row if the window is not big enough to hold each object on one row
...
Download free eBooks at bookboon
...
Grid Layout In Action
Another very common layout manager is gird layout
...
Java will work out how many columns it needs to use in order to place the required
number of objects in that number of rows
...
Java will shrink
or enlarge the objects to fit the window – even if this means that not all of the text can be shown
...
Download free eBooks at bookboon
...
Layout managers can be used in layers and applied to any container object Thus we can create a grid
where one element contains multiple objects arranged in a flow
...
Creating a layout managers and setting their properties using NetBeans is very easy
...
Selecting this option will display the list of layout managers possible
...
...
com
147
Click on the ad to read more
Object Oriented Programming Using Java
8
...
Action listeners are objects that listen for user actions and respond accordingly – thus
when a ‘calculate’ button is pushed a program will calculate and display some results
...
Though many objects, such as labels, will be not be required to respond to a users interactions
...
Download free eBooks at bookboon
...
Selecting the events tab
will allow a range of actions to be created for this object
...
Code will automatically be written to create an object of this class and assign this
to the object selected in the design
...
In the example below an event has been created to listen for button1 being pushed
...
12
The Javadoc Tool
One particularly useful tool within the JDK is ‘javadoc’
...
Some of this documentation is intended for users and explain what a program does and
how to use it
...
These
programmers need to know what the program does and how it is structured
...
Download free eBooks at bookboon
...
The tool analyses *
...
This website provides, as a set of indexed web pages, essential details of the Java language specification
including all packages, classes, methods and method parameters and return values
...
The same tool can produce the same style of documentation doe any Java program
...
Because this documentation is generated automatically, at the push of a button, it saves programmers
from a tedious, time consuming and error prone task
...
This tool does require a programmer to add meaningful comments to code as it is developed and poor
attention to commenting of source code will result in poor javadoc output! On the other hand, if the
commenting is done properly then the reference documentation is produced ‘for free’!
Javadoc comments should be added at the start of every class using the standard tags @author and @
version to give an overview of that class in the following format
...
com
150
Object Oriented Programming Using Java
Java Development Tools
/***********************************
* A description of the class
*
* @author name of author
* @version details of version (and date)
...
The details of each parameter, starting with the name
of the parameter, should be provided on separate lines as shown below
...
mastersopenday
...
com
151
Click on the ad to read more
Object Oriented Programming Using Java
Java Development Tools
Activity 1
The method below takes two integer numbers and adds them together
...
Write a javadoc comment, using appropriate tags, to
describe this method
...
*
* @param pNumber1 first number to be added
* @param pNumber2 second number to be added
* @return sum of the two numbers
***********************************/
The javadoc tool cannot analyse the description of a method to determine if this description provides an
accurate summary of that method
...
One thing this tool does is analyse method signatures and compare
this with the tags in the comments to check for logical errors
...
“warning – @param argument “pNumber3” is not a parameter name
...
The reference documentation produced is for programmers using the class(es) concerned, it does
not include comments within methods intended for programmers editing the class source code in
maintenance work
...
html in a web browser
...
Items which are private or for which no access qualifier is given
are omitted
...
com
152
Object Oriented Programming Using Java
Java Development Tools
8
...
Java uses an
intermediate language called ‘bytecode’ and a main method is required
...
Specialist tools are available for aspects of development such as GUI design, diagramming and
documentation but some IDEs go beyond the basics and provide some of these facilities in built into the IDE
...
These are both available as a free download
...
g
...
The Javadoc tool is an extremely useful and timesaving device but it does require the programmer to
inserting meaningful Javadoc style comments into the code (for all classes and all public methods)
...
com
153
Click on the ad to read more
Object Oriented Programming Using Java
Creating And Using Exceptions
9 Creating And Using Exceptions
Introduction
If the reader has written Java programs that make use of the file handling facilities they will have written
code to catch exceptions i
...
they will have used try\catch blocks
...
Objectives
By the end of this chapter you will be able to…
• Appreciate the importance of exceptions
• Understand how to create your own exceptions and
• Understand how to throw these exceptions
...
1
Understanding the Importance of Exceptions
Exception handling is a critical part of writing Java programs
...
com
154
Object Oriented Programming Using Java
Creating And Using Exceptions
Activity 1
Imagine part of a banking program made up of three classes, and three methods as shown below…
BankManager
listOfClients
awardLoan()
BookofClients
1
getClient(pClientIID :String) :Client
*
Client
determineCreditRating()
The system shown above is driven by the BankManager class
...
This method is intended to accept or reject a
loan application
...
However the only method of interest to us is
the getClient() method
...
The Client class has only one method of interest determineCreditRating()
...
Considering the scenario above look at the snippet of code below …
Client c = listOfClients
...
determineCreditRating();
This fragment of code would exist in the awardLoan() method
...
This method would return the appropriate client object
(assuming of course that a client with this ID exists) which is then stored in a local variable ‘c’
...
Look at these two lines of code
...
com
155
Object Oriented Programming Using Java
Creating And Using Exceptions
Feedback 1
If a client with the specified ID exists this code above will work
...
The second line of code would then cause a run time error (specifically a NullPointerException) as it
tries to invoke the determineCreditRating() method on a non existent client and the program would
crash at this point
...
Client c = listOfClients
...
determineCreditRating();
}
Feedback 2
If the code was amended to allow for the possible NULL value returned it would work – however
this protection is insecure as it relies on the programmer to spot this potential critical error
...
However this relies on every programmer who ever uses this
method to recognise and protect against this eventuality
...
Find out what you can do to improve
the quality of your dissertation!
Get Help Now
Go to www
...
co
...
com
156
Click on the ad to read more
Object Oriented Programming Using Java
Creating And Using Exceptions
If any programmer using this method failed to protect against a NULL return then their program could
crash – potentially in this case losing the bank large sums of money
...
A more secure programming method is required to ensure that that a potential crash situation is always
dealt with!
Such a mechanism exists – it is a mechanism called ‘exceptions’
...
Thus we can ensure that no such situation is ‘forgotten’
...
In the situation above rather than return a NULL value the getClient() method should generate an
exception
...
9
...
Subclasses of java
...
Exception are used for anticipated problems which need to be managed
...
Subclasses of java
...
RuntimeException are used for situations which lead to runtime failure and where
it may not be possible to take any sensible remedial actions
...
Thus we have the choice as to whether the Java compiler should force us to explicitly deal with a particular
kind of exception
...
g
...
RuntimeException subclasses are appropriate for things which should not happen at all and where there
is probably nothing we can do to recover the situation, e
...
an out of memory error or discovering that
the system is in an inconsistent state which should never be able to arise
...
com
157
Object Oriented Programming Using Java
9
...
g
...
When a potential error occurs we should generate
an ‘Exception’ object i
...
an object of the Exception class
...
e
...
A new exception is just like any new class in this case it is a subclass of java
...
Exception
In the case above an error could occur if no client is found with a specified ID
...
The parameter to the constructor for the Exception requires a Sting thus the constructor for
UnknownClientException also requires a String
...
The code to create this new class is given below…
import java
...
Exception;
/*******************************************************
* Exception thrown when attempting to get an non-existent client ID
*
* @author Simon Kendal
* @version 1
...
Here we are creating a subclass of Exception but our subclass
does not contain any new methods – nor does it override any existing methods
...
If sublasses of Exception did not exist we would only be able to catch the most general type of exception
i
...
Thus we would only be able to write a catch block that would catch every single
type of exception
...
com
158
Object Oriented Programming Using Java
Creating And Using Exceptions
Having defined a subclass we instead have a choice… a) we could define a catch block to catch objects
of the general type ‘Exception’ i
...
it would catch ALL exceptions or b) we could define a catch block
that would catch UnknownClientExceptions but would ignore other types of exception
...
There
are many of these including:• IOException
-- CharConversionException
-- EOFException
-- FileNotFoundException
-- ObjectStreamException
• NullPointerException
• PrinterException
• SQLexception
Thus we could write a catch block that would react to any type of exception, or we could limited it to
input \ output exceptions or we could be even more specific and limit it to FileNotFound exceptions
...
Already today, SKF’s innovative knowhow is crucial to running a large proportion of the
world’s wind turbines
...
These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication
...
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations
...
Visit us at www
...
com/knowledge
Download free eBooks at bookboon
...
4
Creating And Using Exceptions
Throwing Exceptions
Having defined our own exception we must then instruct the getClient() method to throw this exception
(assuming a client has not been found with the specified ID)
...
To tell the compiler this method throws an exception we add the following statement to the methods
signature ‘throws UnknownClientException’
...
We use the keyword ‘throw’ to throw an exception at the appropriate point within the body of the method
...
getClient():
unknown client ID:" + pClientID);
}
In the example above if a client is found the method will return the client object
...
Instead if a client has not been found the constructor for UnknownClientException
is invoked, using ‘new’
...
The message is specifying:• the class which generated the exception (i
...
BookOfClients),
• the method within this class (i
...
getClient()),
• some text which explains what caused the exception and
• the value of the parameter for which a client could not be found
...
This enables the Java compiler to make sure a try/catch block is provided where required
...
com
160
Object Oriented Programming Using Java
9
...
The code in the try block will be terminated if an exception is generated and the code in the catch block
will be initiated instead
...
getClient(clientID) ;
c
...
out
...
awardLoan()\n"
+ "Exception details: " + uce);
}
Now, instead of crashing with a NullPointerException if the client ID is not found, the
UnknownClientException we have deliberately thrown will be handled by the Java Virtual Machine
which will terminate the code in the try clause and invoke the code in the catch clause, which in this
case will display a message warning the user about the problem
...
6 Summary
Java exceptions provide a mechanism to deal with abnormal situations which occur during program
execution
...
The exception mechanism will ensure other programmers who use our methods recognise and deal
with error situations
...
In either case at least the
program doesn’t just ‘stop’
...
com
161
Object Oriented Programming Using Java
Agile Programming
10 Agile Programming
While a detailed discussion of Agile development methods is beyond the scope of this book, this chapter
will explain the claims made by proponents of agile programming methods and show how modern IDE’s
(such as Eclipse) offers tools to support agile programming
...
Objectives
By the end of this chapter you will be able to…
• Appreciate the importance of the claims made for Agile development
• Understand the need for refactoring and how a modern IDE supports this
• Understand the advantages of Unit testing and
• Understand how to create JUnit test cases
...
com
162
Click on the ad to read more
Object Oriented Programming Using Java
Agile Programming
This chapter consists of fifteen sections:1) Agile Approaches
2) Refactoring
3) Examples of Refactoring
4) Support for Refactoring
5) Unit Testing
6) Automated Unit Testing
7) Regression Testing
8) JUnit
9) Examples of Assertions
10) Several Test Examples
11) Running Tests
12) Test Driven Development (TDD)
13) TDD Cycles
14) Claims for TDD
15) Summary
10
...
This is a very hot topic in Software Engineering circles at the moment, and as with all such developments
it has its share of zealots and ideologues!
Is the waterfall lifecycle model really successful in enabling large, complex projects to proceed from
start to finish without ever looking back? Advocates of agile approaches contend that these better fit the
reality of software development
...
Two specific
tools provided by modern IDEs that support agile programming are refactoring and testing tools
...
2 Refactoring
A key element of ‘agile’ approaches is ‘refactoring’
...
Download free eBooks at bookboon
...
Although the idea of structurally improving existing software is not new, the difference is as follows
...
In agile methodologies
refactoring is regarded as a natural healthy part of the development process
...
3
Examples of Refactoring
During the development process a programmer may realise that a variable within a program has been
badly named
...
Changing a local variable will only require changes in one particular method – if a variable with the
same name exists in a different method this will not require changing
...
Thus implementing a seemingly trivial change requires an understanding of the consequences of
that change
...
These include
...
4
Support for Refactoring
Even the simplest refactoring operation, e
...
renaming a class, method, or variable, requires careful
analysis to make sure all the necessary changes are made consistently
...
Download free eBooks at bookboon
...
g
...
However if you
rename a public instance variable this may require changes in other classes and even in other packages
as methods from these classes may access and use this variable
...
As a system design evolves, just as we may sometimes decide a class
has become too large and complex and decide to split it into two or more separate classes, so we might
decide to split a package
...
Eclipse will allow us to drag a class from one package to another
...
The screen shot below shows the refactoring options provided by the Eclipse IDE
...
com
165
Click on the ad to read more
Object Oriented Programming Using Java
Agile Programming
Another essential tool provided by modern IDEs are automated testing tools
...
5
Unit Testing
Testing the individual methods of a class in isolation from their eventual context within the system under
construction is known as Unit Testing
This testing is generally ‘wrapped into’ the implementation process:
• Write class
• Write tests
• Run tests, debugging as necessary
Download free eBooks at bookboon
...
6
Agile Programming
Automated Unit Testing
Tools and frameworks are available to automate the unit testing process
...
However the main benefit arises from the
ability to re-run the tests as often as desired just by pushing a button
...
Regression testing was developed long before agile methods were proposed and automated unit testing
supports this
...
We will explore the Test Driven Development processes within this chapter but before doing so we will
first explore conventional regression testing and the support offered for this via JUnit a testing framework
within Java
...
7
Regression Testing
Regression testing is required as a software is adapted to meet changing business needs
...
To do this as we write
classes we must also write test cases that demonstrate these classes work
...
Without regression testing any modification of existing code is extremely hazardous!
As we regularly need to re-run sets of test cases it is helpful, and hugely timesaving, to have automated
testing facilities such as those that exist within Java
...
com
167
Object Oriented Programming Using Java
Agile Programming
10
...
It has been developed as a suite of opensource classes, and is integrated into popular Java IDEs such as Eclipse and NetBeans
...
JUnit test classes are constructed as subclasses of junit
...
TestCase
The correct behaviour of code being tested is checked using assert…() methods which must be true for
the test to pass
Currently version 3
...
Here we are using the more widely established Junit 3
...
9
Examples of Assertions
When setting up test cases we make assertions
...
Example of assertion include…
• assertTrue(…)
• assertFalse(…)
• assertEquals(…)
• assertNotEquals(…)
• assertNull(…)
• assertNotNull(…)
• fail()
assertEquals() and fail() will be adequate for many testing purposes, as we will see here
...
10
...
com
168
Object Oriented Programming Using Java
Agile Programming
Download free eBooks at bookboon
...
Client objects can be added by the
addClient() method which requires an ID for that client and the client object to be added
...
The Client class has a constructor that requires the name of the client and the clients address and provides
associated accessor methods
...
This is of course only a small fraction of the test cases which would be needed to thoroughly demonstrate
the correct operation of all classes and all methods within the system
...
The code for this is given below…
public void testAddClient() {
BookofClients bofc = new BookofClients();
Client c = new Client("Simon",
"No 5, Main St
...
addClient("SK001", c);
try {
c2 = bofc
...
getName());
assertEquals("No 5, Main St
...
getAddress());
}
Download free eBooks at bookboon
...
, Sunderland, SR1 0DD”
...
Note that the two parameters of the assertEquals() method are first the expected value and second the
actual value
...
If the test method ends without failing any assertions then the test is passed
...
It is common practice in designing classes to create accessor methods which were intended purely to
support unit testing even when these are not required in the actual system
...
To test this we create an new empty BookofClients and try to retrieve a client from
this – any client!
The code for this is given below…
public void testGetUnknownClient() {
BookofClients bofc = new BookofClients();
try {
bofc
...
If the exception is caught the fail() statement is skipped, the catch block has no action to take and the
test then completes successfully
...
com
171
Object Oriented Programming Using Java
Agile Programming
Testing the toString() method
One way of implicitly testing that ALL the attributes a client have been stored correctly is to test the
toString() method returns the value expected
...
The alternative however is to test the value returned by every accessor method
...
public String toString() {
return ("Client name: " + mName + "\nAddress: " + mAddress);
}
Hint: Firstly create a new Client object with specified attributes then test the attributes of this
object are as expected by using an assertion to test the string returned by the toString() method
...
public void testClientToString() {
Client c = new Client("Simon", "5 Main St
...
,
Sunderland", c
...
toString() is equal to the string we are expecting
...
This test is of course implicitly testing that ALL the attributes have been stored correctly which is useful
...
11 Running Tests
Having designed a batch of test cases we need to set these up so that they can be run as often as required
at the push of a button
...
com
172
Object Oriented Programming Using Java
Agile Programming
10
...
This has become a hot topic in software engineering
The Test Driven Development approach is to
1) Write the tests (before writing the methods being tested)
...
Which of the following is simpler?
• Teach someone everything you know about a subject and then decide how to test their
knowledge or
• Decide specifically what it is they need to learn (i
...
decide what to test) and then teach the
person just what they need to know in order to pass that test
...
RUN LONGER
...
GAITEYE
...
indd 1
Download free eBooks at bookboon
...
13 TDD Cycles
When undertaking test driven development the test will initially cause a compilation error as the method
being tested doesn’t exist!
...
We then implement the correct functionality of the method so that the test succeeds
...
10
...
• it encourages programmers to write simple code directly addressing the requirements
• a comprehensive suite of unit tests is compiled in parallel with the code development
• a rapid cycle of “write test, write code, run test”, each for a small developmental increment,
increases programmer confidence and productivity
...
With Test Driven
Development this is not possible as the tests are written before the system has been implemented
...
15 Summary
‘Agile’ development approaches emphasize flexible cyclic development with the system evolving towards
a solution
...
An automated unit testing framework (e
...
JUnit) allows unit tests to be regularly repeated as system
development progresses
...
Download free eBooks at bookboon
...
Objectives
By the end of this chapter you will see…
• how a problem description is turned into a UML model (as described in Chapter 6)
• an example of how typed collections can be effectively used, in particular you will see an
example of the use of sets and maps (as described in Chapter 7)
• an example of polymorphism and see how this enables programs to be extended simply
(as described in Chapter 4)
• a simple example of the use of inheritance and method overriding (as described in
Chapter 3)
• several example of UML diagrams (as described in Chapter 2)
• finally you will see the use of the Javadoc tool (as described in Chapter 8)
...
Eclipse is freely available from www
...
org
...
com
175
Object Oriented Programming Using Java
Case Study
14) Generating Javadoc
15) Running the System and Potential Compiler Warnings
16) The Finished System…
17) Summary
11
...
The purpose of this chapter is not to show how requirements
are obtained but to show how a problem statement is modelled using OO principles and turned into a
complete working system once requirements are gathered
...
’
For the purpose of this exercise we will assume preliminary requirements analysis has been performed
by interviewing the shop owner, and the workers who would use the system, and from this the following
textual description has been generated:-
Download free eBooks at bookboon
...
It has recently also become a
ticket agency for various local entertainment and transport providers
...
Rory intends to use this to advertise his own products and offers and
also to provide a message display service for fee-paying clients (e
...
private sales, lost and found,
staff required etc
...
g
...
A book of clients is maintained to which clients can be
added and in which we can look up a client by their ID
...
No duplicate messages (i
...
the
same text for the same client) are permitted
...
The software is to be written before the display board is installed – therefore the connection to the
board should be via a well-defined interface and a dummy display board implemented in software
for testing purposes
...
11
...
This has therefore been ignored
...
com
177
Object Oriented Programming Using Java
Case Study
List of Nouns
From the remaining paragraphs we can list the following nouns or noun phrases:•
•
•
•
•
•
•
•
•
LCD message display board
shopfront
scrolling text message
client
ID string
name
address
phone number
credit
•
•
•
•
•
•
•
•
•
credit unit
message
day
book of clients
ID
text
number of days
cost of message (units)
set of current messages
•
•
•
•
•
•
•
•
•
message set
display board
days remaining
client’s credit
cost of message
software
connection
interface
dummy display board
•
•
•
•
•
•
add (a client)
look up
permit (duplicates – NOT!)
purge
decrement
reduce credit
•
•
•
•
•
•
expire
delete
write (the software)
install
implement
test
List of Verbs
and the following verbs:•
•
•
•
•
•
acquire
mount
show
advertise
give (a unique ID)
display
Outside Scope of System
By identifying things outside the scope of the system we simplify the problem…
• Nouns:
-- shopfront
-- software
• Verbs:
-- acquire, mount (the display board)
-- advertise
-- give (a unique ID)
-- write, install, implement, test (the software)
The shopfront is not part of the system and it is not a part of the system to acquire and mount the
displayboard
...
And writing / installing the software
is the job of the programmer – it is not part of the system itself
...
com
178
Object Oriented Programming Using Java
Case Study
Synonyms
The following are synonyms:• Nouns:
-- LCD message display board = display board
-- scrolling text message = message
-- ID string = ID
-- credit units = client’s credit = credit
-- set of current messages = message set
-- days = number of days = days remaining
• Verbs:
-- show = display
By identifying synonyms we avoid needless duplication and confusion in the system
...
sylvania
...
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges
...
Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths
...
Come and join us in reinventing
light every day
...
com
179
Click on the ad to read more
Object Oriented Programming Using Java
Case Study
Potential Classes, Attributes and Methods
Nouns that describe significant entities for which we can identify properties i
...
data and behaviour i
...
methods could become classes within the system
...
g
...
g
...
This is a design judgement – introducing classes for significant entities (Client, Message etc
...
g
...
Download free eBooks at bookboon
...
For instance:• For a ‘client’:
-- decrease credit
• For a ‘message’:
-- decrement days
The other verbs describing potential methods should also be listed:• display
• add (client to book)
• add (message to set)
• lookUp (client in book)
• purge
• decrement
• expire
• delete
For each of these the associated class should be identified
...
Looking at the list of candidate classes provided we can see that two classes that share common
characteristics:• DisplayBoard
• DummyDisplayBoard
This either implies these classes should be linked within the system within an inheritance hierarchy or
via ‘an interface’(see section 4
...
In this case the clue is within the description “These will have
a ‘connection’ to the rest of the system via a ‘well-defined interface”
...
For this to work the dummy board must implement the same methods as
a real display board
...
com
181
Object Oriented Programming Using Java
Case Study
Thus we should define a java ‘interface’
...
However the dummy board and the real
display board should both implement the methods defined via a common interface
...
As the connection with the dummy board is via the interface changing the dummy board with the real
display board should have no impact on our system
...
The methods and attributes can be associated with classes
...
• MessageSet
• DisplayBoard
• DummyDisplayBoard
The Interface is:-
• DisplayBoardControl (a name we have made up)
360°
thinking
...
Discover the truth at www
...
ca/careers
© Deloitte & Touche LLP and affiliated entities
...
deloitte
...
Download free eBooks at bookboon
...
Discover the truth at www
...
ca/careers the ad to read more
182
Click on
© Deloitte & Touche LLP and affiliated entities
...
3
Further Analysis
We could now document this proposed design using UML diagrams and program a system accordingly
...
Thus we should now refine our design using CRC cards and elaborate our classes
...
10 and 6
...
The two CRC cards below have been developed to describe the Client and ClientBook classes
...
Download free eBooks at bookboon
...
In this case what happens when we get a new
client in the shop? Can this client be created and added to the client book?
To do this the system must perform the following actions:• create a new Client object
• pass it (along with the unique ID to associate with it) to the ClientBook object
• add the client to the client book
...
It would therefore appear that this part of the system will work at least in this respect – of course we
need to create CRC cards to describe every class and to test the system with a range of scenarios
...
Download free eBooks at bookboon
...
A point of requirements definition occurs here
...
b) we load a collection of messages in one go, then tell the board to display them in sequence
which it does autonomously
The correct choice depends on finding out how the real display board actually works
...
For this exercise we will assume the answer to this is (b), hence the responsibilities of scrolling through
a set of messages will be assigned to the DisplayBoardControl interface
...
Send us your CV
...
Send us your CV on
www
...
com
Download free eBooks at bookboon
...
The Message Purge Scenario
The final scenario that we want to run though here is the message purge scenario
...
CRC cards for the classes involved in this have been drawn below…
Download free eBooks at bookboon
...
Looking at the CRC cards above work through the following steps and identify any potential
problems with these classes:For each message
- tell the Message to decrement its days remaining and
- tell the relevant Client to decrease its credit
- ask the Message for its client ID
- ask the Message for its cost
- ask the ClientBook for the client with this ID
- tell the Client to decrease its credit by the cost of the message
- if either the Client’s credit is <= 0 or the Message is
now expired
delete the message from the list
Feedback 1
A problem becomes evident when we try to find the client associated with a message as Message
does not know the client ID
...
A revised design for the Message class is given below…
By drawing out CRC cards for each class and interface and by role playing a range of scenarios we have
checked and revised our plans for the system – we can now refine these and document these using
UML diagrams
...
com
187
Object Oriented Programming Using Java
11
...
Elaborating the Classes
Having worked through CRC scenarios we can make an initial assignment of instance variables and
methods among our classes, including some accessors and mutators whose necessity has become evident
(see diagram below)
...
com
188
Object Oriented Programming Using Java
Case Study
We don’t know of any simple attributes which ClientBook and MessageSet will require, but they will
need to be associated with other classes so we still have some work to do there – hence the ?s (which
are not an official part of UML)!
Relationships Between Classes
We can now start to work out how these classes are related
...
The navigability will be from ClientBook to client because the book “knows about” its Clients (in
implementation terms it will have references to them) but the individual Clients will not have references
back to the book
...
The specification states that each Client will have a unique ID thus the collection will in fact be a map
where each entry is made up of a pair of values – in this case a clientID (a string) and a Client object
...
com
189
Click on the ad to read more
Object Oriented Programming Using Java
Case Study
The relationship between MessageSet and Message is very similar to the relationship between ClientBook
and Clients
...
The specification states that messages must be unique
but does not imply a key value is required thus a simple set will suffice
...
com
190
Object Oriented Programming Using Java
Case Study
Relating the Classes: MessageSet, ClientBook, and DisplayBoardControl
Because MessageSet is responsible for initiating the display of the messages on the display board it has
a dependency on a class implementing the DisplayBoardControl interface
...
This is shown below
...
An additional class, DummyBoard, has
been included which will implement the DisplayBoardControl interface for testing purposes
...
Download free eBooks at bookboon
...
I joined MITAS because
I wanted real responsibili�
I joined MITAS because
I wanted real responsibili�
Real work
International
Internationa opportunities
al
�ree wo placements
work
or
�e Graduate Programme
for Engineers and Geoscientists
Maersk
...
discovermitas
...
com
192
�e G
for Engine
Click on the ad to read more
Object Oriented Programming Using Java
Case Study
While the classes above will form the heart of the system two additional classes will be required to drive
and manage the system as a whole
...
The other additional class ‘Manager’ will control additional functionality not specified by the shop owner
but implicitly required – for instance at the end of the day the details of the ClientBook and MessageSet
will need to be saved to file
...
11
...
The figure below shows the proposed interface for this system:MessageManager v7
NEW CLIENTS
NEW MESSAGES
Find Client
Increase Credit
Client ID
Delete Client
Name
Client ID
Address
Display Message
Phone
Purge Messages
Credits
Add Client
Add Message
Save and Exit
This is made up of three areas
...
Each of these three areas will be implemented using a JPanel placed within one larger JFrame
...
6
Revising the Design to Accommodate Changing Requirements
Changing software requirements are a fact of life and OO programming is intended to help software
engineers make program adaptations easier, quicker, cheaper and with less risk of generating errors
...
Download free eBooks at bookboon
...
These should be highlighted on the display by placing three stars before and
after the message and the cost of these messages will be twice the cost of ordinary messages
...
Modifying the interface design to accommodate this change is easy – we can either:• create an new panel to accommodate the creation of ‘Urgent Messages’ or
• since the data required is identical to normal messages we can just add an extra button to
the middle panel
...
Firstly there
is clearly a strong relationship between a ‘Message’ and an ‘Urgent Message’
If both classes had some unique features but there was a significant overlap in functionality we could
introduce an inheritance hierarchy to deal with this:-
However in this case there are no unique features of an ordinary message – messages have an associated
cost, the cost and text can be obtained and new messages can be created
...
An urgent message is just the same as an ordinary message where the text and the cost has
been changed slightly
...
Thus the Message and UrgentMessage classes are be related as shown below, with UrgentMessage
inheriting all of the values and methods associated with Message but overriding getCost() and getText(0
methods to reflect the different cost and text associated with urgent messages
...
com
194
Object Oriented Programming Using Java
Case Study
93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION
MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
THAT THE CAPITAL OF SPAIN OFFERS
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
PROFESSIONAL GOALS
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
EXPERIENCE
5 Specializations
Personalize your program
www
...
edu/master-management
#10 WORLDWIDE
MASTER IN MANAGEMENT
FINANCIAL TIMES
mim
...
edu
Length: 1O MONTHS
Av
...
com
195
Click on the ad to read more
Object Oriented Programming Using Java
Case Study
A revised class diagram is below
...
But what about
UrgentMessages?
Urgent messages are just a specific type of message
...
e
...
Therefore, without making any changes at all to MessageSet, MessageSet can maintain a set of all messages
to be displayed (both urgent and ordinary)!
Furthermore when the dailyPurge() method is invoked it invokes the getCost() method on a Message
object so that the client can be charged for that message
...
This is polymorphism in action!
Download free eBooks at bookboon
...
If later we
decided to create new message types (such as a Christmas message) MessageSet would be able to deal
with these as well without changing a single line of code!
Thus in this application we are able to extend the system to add the facility for urgent messages by adding
only one class and making one small change to the interface
...
Object Orientation has enabled to the system to be extended with minimal effort!
11
...
The system being used here to demonstrate the theory in this textbook hardly qualifies as large –
nonetheless it has been decided to package related classes together as shown below
...
com
197
Click on the ad to read more
Object Oriented Programming Using Java
Case Study
This diagram shows the four packages used and the classes within each package
...
Not surprisingly the main package, which houses the system interface,
is associated with all of the other packages – this is because the interface invokes functionality throughout
the system
...
This will be done in two phases:In the first phase a basic system will be implemented which will allow messages and clients to be created,
the details written to file and messages to be displayed
...
This will be done in a way to allow the demonstration of Test Driven
Development (as described in Chapter 10)
...
com
198
Object Oriented Programming Using Java
11
...
Message has various instance variables (Strings: clientID, text and int: daysRemaining)
...
To do this all Client
objects and Message objects will also need to be stored hence these classes (including the Message class)
will need to implement the Serializable interface
...
e
...
”
Therefore Message must override the equals() and hashCode() methods to ensure that duplicates will
not be permitted when the messages are stored in a Set
...
”
CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www
...
nl/feb/education
Download free eBooks at bookboon
...
package messages;
import java
...
Serializable;
public class Message implements Serializable
{
final int COST=1;
private String clientID;
private String messageText;
private int daysRemaining;
public Message (String pClientID, String pText,
int pDaysRemaining) {
clientID = pClientID;
messageText = pText;
daysRemaining = pDaysRemaining;
}
public void decrementDays() {
daysRemaining--;
}
public boolean hasExpired() {
return (daysRemaining == 0);
}
public String getClientID() {
return clientID;
}
public String getText () {
return messageText;
}
public int getCost() {
return COST;
}
public int hashCode () {
return (clientID + messageText)
...
equals(otherMsg
...
equals(otherMsg
...
com
200
Object Oriented Programming Using Java
Case Study
The UrgentMessage class is extremely short and sweet as it inherits almost all of its functionality
from Message:package messages;
public class UrgentMessage extends Message
{
final int COST=2;
public UrgentMessage (String pClientID, String pText,
int pDaysRemaining){
super(pClientID, pText, pDaysRemaining);
}
public String getText () {
return "*** "+super
...
This implies a collection type and
the fact that duplicate massages are not allowed (at least for the same client) implies the collection
should be a Set
...
A constructor is required to assign a new HashSet() to messageSet and to initialize clientBook to a
parameter
...
com
201
Object Oriented Programming Using Java
Case Study
Some of the code from this class is shown below:package messages;
import
...
add(pMsgToAdd);
}
public void display(DisplayBoardControl db)
{
db
...
run();
}
public void dailyPurge() {
// code omitted here
}
public void saveToFile(ObjectOutputStream oos) {
try {
oos
...
showMessageDialog(null, ""+ioe);
}
}
static public MessageSet readFromFile(ObjectInputStream ois) {
MessageSet cb = null;
try {
cb = (MessageSet) ois
...
showMessageDialog(null, ""+ioe);
System
...
showMessageDialog(null, ""+cnfe);
System
...
com
202
Object Oriented Programming Using Java
Case Study
The code above shows the creation of a typed collection of ‘Message’ and methods to add and
display messages
...
Initially a DummyBoard object will be provided however when a real display board is
purchased then this object will replace the DummyBoard object
...
This is
another example of the application of polymorphism
...
American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:
▶▶ enroll by September 30th, 2014 and
▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www
...
com to
find out more!
Note: LIGS University is not accredited by any
nationally recognized accrediting agency listed
by the US Secretary of Education
...
Download free eBooks at bookboon
...
decrementDays();
try
{
// decrease client credit for this message
client = clients
...
getClientID());
client
...
getCost());
// if message expired or client out of credit remove it
if (msg
...
getCredit() <= 0) {
messageSet
...
showMessageDialog(null,
"INTERNAL ERROR IN MessageSet
...
hasExpired()) {
messageSet
...
This will be discussed
in the next section
...
com
204
Object Oriented Programming Using Java
11
...
Programming the ClientBook class is also very similar to programming MessageSet, and most of this
class is omitted here however there are two significant differences:• All clients have a clientID so ClientBook uses a Map instead of a Set
...
We need to
build in protection in case a client cannot be found
...
public class ClientBook implements Serializable {
private Map
public ClientBook() {
clientMap = new HashMap
}
public void addClient(String pClientID, Client pNewClient) {
clientMap
...
Download free eBooks at bookboon
...
10 Creating and Handling UnknownClientException
The getClient() method in the ClientBook class will return a null value if no client exists with the
specified ID
...
We therefore need to build in protection against this eventuality
...
The first step is simple and not shown here
...
com
206
Click on the ad to read more
Object Oriented Programming Using Java
Case Study
Telling the getClient() method and deleteClient() method to generate this exception is relatively straight
forward (as shown below):public Client getClient(String pClientID)
throws UnknownClientException {
Client foundClient;
foundClient = clientMap
...
getClient():
unknown client ID:" + pClientID);
}
}
Firstly we must tell the compiler that this method can generate an exception
...
The object returned by the constructor is then ‘thrown’
...
The compiler will then ensure that the programmer writing the dailyPurge() method catches this
exception – hopefully they will then deal with it to prevent a crash situation
...
8 (Programming the Message Classes)
...
However in this case we have chosen to be
more cautious since we simply don’t know how we have come to have an ‘unowned’ message
...
The message will continue to be displayed (even without having a client to charge!)
...
Download free eBooks at bookboon
...
11 Programming the Main classes
There are two classes, not shown on the class diagrams given previously, that ‘drive’ the system
...
It performs the following functions:• it has a permanent reference to the client book and message set
...
The startup() method is shown below:public void startUp() {
try {
FileInputStream fis = new FileInputStream(MMS_DATA_FILE);
ObjectInputStream ois = new ObjectInputStream(fis);
cb = ClientBook
...
readFromFile(ois);
fis
...
showMessageDialog(null, "No existing
client/message data found");
cb = new ClientBook();
ms = new MessageSet(cb);
} catch (IOException ioe) {
JOptionPane
...
exit(1);
}
}
The startup() method tries to setup an Object Input stream from which it then tries to reconstruct
ClientBook and MessageSet objects
...
The first will catch a FileNotFoundException – this will occur if the file of data
cannot be found e
...
the first time this program is run
...
The second catch block will catch any other IO error and in this case will then exit the program
...
com
208
Object Oriented Programming Using Java
Case Study
11
...
This has a main() method which invokes the createGUI() method
...
A Grid layout manager was applied to these JPanels (as described in section 10 of chapter 8)
...
Shown below is the action listener associated with the FindClient button:
private class FindClientListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
String id = JOptionPane
...
showMessageDialog(null,
manager
...
getClient(id)
...
showMessageDialog(null,
"No such client");
}
}
}
...
com
209
Click on the ad to read more
Object Oriented Programming Using Java
Case Study
This action listener does the following:• It opens a dialog box to ask the user for a clients ID,
• If cancel is pressed it replaces the null returned with an ID of “”
...
• On the client book object it invokes the getClient() method passing the ID as a parameter
• Assuming a client is returned the toString() method is then invoked to get a string
representation of the client and this is passed as a parameter to the showMessageDialog()
method (which displays the details of the client with that ID)
...
11
...
We need
a method to increase a clients credit – this should be placed within the Client class
...
It has been decided to use Test Driven Development to extend the system by providing this functionality
(as discussed in Chapter 10 Agile Programming)
...
Download free eBooks at bookboon
...
increaseCredit(10);
assertEquals(20, c
...
addClient("sk", c);
try {
cb
...
getClient("sk");
fail();
} catch (UnknownClientException uce) {
}
}
The first of these creates a client with 10 units of credit, adds an additional 10 units of credit and then
checks that this client has 20 units of credit
...
The second test creates and empty client book, creates a client, adds the client to the client book and
tries to delete this client – if at this point an unknownClientexception is generated then we know there
is a problem
...
If an exception is not generated at this point then
the class is flawed and the test should ‘fail’
...
We must now create the methods and revise them until these tests pass
...
com
211
Object Oriented Programming Using Java
Case Study
Theory suggest that TDD leads to simple code
...
Of course we may need a range of test case to make sure the method
has all of the essential functionality it needs
...
14 Generating Javadoc
Documentation is essential and can be generated automatically (as described in Chapter 8 – Java
Development Tools) assuming appropriate comments have been placed in the code
...
All parameters and return values have been described
...
0 (26 June 2009)
***********************************************************/
public class Client implements Serializable {
...
/**
* Constructor
*
* @param pName name of client
* @param pAddress client's address
* @param pPhone client's phone number
* @param pCredit initial credit for client
*/
public Client(String pName, String pAddress, String pPhone,
int pCredit) {
...
/**
* return the client's current credit
*
* @return credit units remaining
*/
public int getCredit() {
...
}
Download free eBooks at bookboon
...
The following picture shows part of the Java documentation describing the UrgentMessage class:-
11
...
To run this program:• Download the file ‘OOP Using Java’
• Import it into Eclipse by selecting File | Import | Existing Project Into Workspace | Select
Archive File ‘OOP Using Java’ and then select the Message Management System project that
is inside the archive file
...
In this exported file are all classes, methods and test cases discussed in this chapter along with the
Javadoc generated by the Javadoc tool
...
doc folder and double click on
the index
...
Download free eBooks at bookboon
...
One in particular that you are likely to see refers to the serializable classes (MessageSet, Message
etc) as I have not given them version numbers
...
11
...
Firstly the main interface window – this is very similar to the design
...
Download free eBooks at bookboon
...
Firstly asking for a client ID…
Secondly displaying the client details – assuming a client with this ID has been added
...
mastersopenday
...
com
215
Click on the ad to read more
Object Oriented Programming Using Java
Case Study
The ‘Display Messages’ button shows each of the messages on the screen that should be display using the
DummyBoard class
...
‘Purge Messages’ invokes the purgeMessages() method
...
This
can be tested by running Find Client before and after doing a daily purge
...
17 Summary
The fundamental principles of the Object Orientated development paradigm are
• abstraction
• encapsulation
• generalization/specialization (inheritance)
• polymorphism
These principles are ubiquitous throughout the Java language and library package APIs as well as providing
a framework for our own software development projects
...
Throughout this chapter you will hopefully have seen how Object Orientation supports the programmer by:• using abstraction and encapsulation to enables us to focus on and program different parts of
a complex system without worrying about ‘the whole’
...
This has been exemplified using Java but the same principles and benefits apply to all OO programming
languages and the tools demonstrated here are available in many modern IDE’s
...
I hope you have found this book helpful and I wish you all the best for the future
Title: Object Oriented Programming using Java
Description: This book will explain the Object Oriented approach to programming and through the use of small exercises, for which feedback is provided, develop some practical skills as well. At the end of the book one larger case study will be used to illustrate the application of the techniques. This will culminate in the development of a complete Java program which can be downloaded with this book. Topics covered include : Abstraction, Inheritance, Polymorphism, Object Oriented Software Analysis and Design, The Unified Modelling Language (UML) , Agile Programming and Test Driven Development. An Introduction to Object Orientated Programming A Brief History of Computing Different Programming Paradigms Why use the Object Orientation Paradigm? Object Oriented Principles What Exactly is Object Oriented Programming? The Benefits of the Object Oriented Programming Approach Summary The Unified Modelling Language (UML) An Introduction to UML UML Class diagrams UML Syntax UML Package Diagrams UML Object Diagrams UML Sequence Diagrams Summary Inheritance and Method Overriding Object Families Generalisation and Specialisation Inheritance Implementing Inheritance in Java Constructors Constructor Rules Access Control Abstract Classes Overriding Methods The ‘Object’ Class Overriding toString() defined in ‘Object’ Summary Object Roles and the Importance of Polymorphism Class Types Substitutability Polymorphism Extensibility Interfaces Extensibility Again Distinguishing Subclasses Summary Overloading Overloading Overloading To Aid Flexibility Summary Object Oriented Software Analysis and Design Requirements Analysis The Problem Listing Nouns and Verbs Identifying Things Outside The Scope of The System Identifying Synonyms Identifying Potential Classes Identifying Potential Attributes Identifying Potential Methods Identifying Common Characteristics Refining Our Design using CRC Cards Elaborating Classes Summary The Collections Framework An Introduction to Collections Collection Interfaces Old and New Collections Lists Sets Maps Collection Implementations Overview of the Collections Framework An Example Using Un-typed Collections An Example Using Typed Collections A Note About Sets Summary Java Development Tools Software Implementation The JRE Java Programs The JDK Eclipse Eclipse Architecture Eclipse Features NetBeans Developing Graphical Interfaces Using NetBeans Applying Layout Managers Using NetBeans Adding Action Listeners The Javadoc Tool Summary Creating And Using Exceptions Understanding the Importance of Exceptions Kinds of Exception Extending the Exception Class Throwing Exceptions Catching Exceptions Summary Agile Programming Agile Approaches Refactoring Examples of Refactoring Support for Refactoring Unit Testing Automated Unit Testing Regression Testing JUnit Examples of Assertions Several Test Examples Running Tests Test Driven Development (TDD) TDD Cycles Claims for TDD Summary Case Study The Problem Preliminary Analysis Further Analysis Documenting the design using UML Prototyping the Interface Revising the Design to Accommodate Changing Requirements Packaging the Classes Programming the Message Classes Programming the Client Classes Creating and Handling UnknownClientException Programming the Main classes Programming the Interface Using Test Driven Development and Extending the System Generating Javadoc Running the System and Potential Compiler Warnings The Finished System… Summary
Description: This book will explain the Object Oriented approach to programming and through the use of small exercises, for which feedback is provided, develop some practical skills as well. At the end of the book one larger case study will be used to illustrate the application of the techniques. This will culminate in the development of a complete Java program which can be downloaded with this book. Topics covered include : Abstraction, Inheritance, Polymorphism, Object Oriented Software Analysis and Design, The Unified Modelling Language (UML) , Agile Programming and Test Driven Development. An Introduction to Object Orientated Programming A Brief History of Computing Different Programming Paradigms Why use the Object Orientation Paradigm? Object Oriented Principles What Exactly is Object Oriented Programming? The Benefits of the Object Oriented Programming Approach Summary The Unified Modelling Language (UML) An Introduction to UML UML Class diagrams UML Syntax UML Package Diagrams UML Object Diagrams UML Sequence Diagrams Summary Inheritance and Method Overriding Object Families Generalisation and Specialisation Inheritance Implementing Inheritance in Java Constructors Constructor Rules Access Control Abstract Classes Overriding Methods The ‘Object’ Class Overriding toString() defined in ‘Object’ Summary Object Roles and the Importance of Polymorphism Class Types Substitutability Polymorphism Extensibility Interfaces Extensibility Again Distinguishing Subclasses Summary Overloading Overloading Overloading To Aid Flexibility Summary Object Oriented Software Analysis and Design Requirements Analysis The Problem Listing Nouns and Verbs Identifying Things Outside The Scope of The System Identifying Synonyms Identifying Potential Classes Identifying Potential Attributes Identifying Potential Methods Identifying Common Characteristics Refining Our Design using CRC Cards Elaborating Classes Summary The Collections Framework An Introduction to Collections Collection Interfaces Old and New Collections Lists Sets Maps Collection Implementations Overview of the Collections Framework An Example Using Un-typed Collections An Example Using Typed Collections A Note About Sets Summary Java Development Tools Software Implementation The JRE Java Programs The JDK Eclipse Eclipse Architecture Eclipse Features NetBeans Developing Graphical Interfaces Using NetBeans Applying Layout Managers Using NetBeans Adding Action Listeners The Javadoc Tool Summary Creating And Using Exceptions Understanding the Importance of Exceptions Kinds of Exception Extending the Exception Class Throwing Exceptions Catching Exceptions Summary Agile Programming Agile Approaches Refactoring Examples of Refactoring Support for Refactoring Unit Testing Automated Unit Testing Regression Testing JUnit Examples of Assertions Several Test Examples Running Tests Test Driven Development (TDD) TDD Cycles Claims for TDD Summary Case Study The Problem Preliminary Analysis Further Analysis Documenting the design using UML Prototyping the Interface Revising the Design to Accommodate Changing Requirements Packaging the Classes Programming the Message Classes Programming the Client Classes Creating and Handling UnknownClientException Programming the Main classes Programming the Interface Using Test Driven Development and Extending the System Generating Javadoc Running the System and Potential Compiler Warnings The Finished System… Summary