You are on page 1of 174



POUL KLAUSEN

JAVA 3: OBJECT-
ORIENTED
PROGRAMMING
SOFTWARE DEVELOPMENT

2
Java 3: Object-oriented programming: Software Development
1st edition
© 2017 Poul Klausen & bookboon.com
ISBN 978-87-403-1691-9
Peer review by Ove Thomsen, EA Dania

3
JAVA 3: OBJECT-ORIENTED PROGRAMMING Contents

CONTENTS
Foreword 6

1 Introduction 8

2 Classes 15
Exercise 1 20
2.1 More classes 22
Exercise 2 34
Exercise 3 35
Problem 1 38
2.2 Methods 41
2.3 Objects 46
2.4 Visibility 48
2.5 Statical members 49
2.6 The CurrencyProgram 53
Problem 2 66

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

4
JAVA 3: OBJECT-ORIENTED PROGRAMMING Contents

3 Interfaces 69
3.1 Interfaces 70
Exercise 4 82
3.2 More students 83
Exercise 5 91
3.3 Factories 94
Exercise 6 97

4 Inheritance 98
Exercise 7 111
Problem 2 112
4.1 More about inheritance 118

5 The class Object 119

6 Typecast of objects 128

7 A last note about classes 130


7.1 Considerations about inheritance 130
Problem 3 134
7.2 The composite pattern 142

8 Final example 143


8.1 Analyse 144
8.2 Design 148
8.3 Programming 155

Appendix A 159
Comment the code 159
Debug the code 162
Unit test 164

5
JAVA 3: OBJECT-ORIENTED PROGRAMMING Foreword

FOREWORD
This book is the third in a series of books on software development. The programming language
is Java, and the language and its syntax and semantics fills obviously much, but the books have
also largely focus on the process and how to develop good and robust applications. In the first
book I have generally mentioned classes and interfaces, and although the book Java 2 also intesiv
used classes and interfaces I have deferred the details to this book and also the next, that are
dealing with object-oriented programming. It deals with how a running program consists of
cooperating objects and how these objects are defined and created on the basis of the program’s
classes. Object-oriented programming is the knowledge of how to find and write good classes
to a program, classes which helps to ensure that the result is a robust program that is easy to
maintain. The subject of this book is object-oriented programming and here primarily about
classes and how classes are used as the basic building blocks for developing a program. The
book assumes a basic knowledge of Java corresponding to the book Java 1 of this series, but
since some of the examples and exercises are relating to programs with a graphical user interface
it is also assumed knowledge of the book Java 2 and how to write less GUI programs.

As the title says this series of books deals with software development, and the goal is to
teach the reader how to develop applications in Java. It can be learned by reading about
the subject and by studying complete sample programs, but most importantly by yourself
to do it and write your own programs from scratch. Therefore, an important part of the
books is exercises and problems, where the reader has to write programs that correspond to
the substance being treated in the books. All books in the series is built around the same
skeleton and will consist of text and examples and exercises and problems that are placed
in the text where they naturally belongs. The difference between exercises and problems is
that the exercises largely deals with repetitions of the substance that is presented in the text,
and furthermore it is relatively accurately described what to do. Problems are in turn more
loosely described, and are typically a little bigger and there is rarely any clear best solution.
These are books to be read from start to finish, but the many code examples, including
exercises and problems plays a central role, and it is important that the reader predict in
detail studying the code to the many examples and also solves the exercises and problems
or possibly just studying the recommended solutions.

All books ends with one or two larger sample programs, which focus primarily is on process
and an explanation of how the program is written. On the other hand appears the code only
to a limited extent – if at all – and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the development of programs
that are larger than the examples, which otherwise is presented, the aim of the concluding
examples also is to show program examples from varying fields of application.

6
JAVA 3: OBJECT-ORIENTED PROGRAMMING Foreword

Most books also ends with an appendix dealing with a subject that would not be treated
in the books. It may be issues on the installation of software or other topics in computer
technology, which are not about software development, but where it is necessary to have
an introductory knowledge. If the reader already is familiar with the subject, the current
appendix can be skipped.

The programming language is, as mentioned Java, and besides the books use the following
products:

-- NetBeans as IDE for application development


-- MySQL to the extent there is a need for a database server (from the book Java 6
onwards)
-- GlassFish as a web server and application server (from the book Java 11 onwards)

It is products that are free of charge and free to install, and there is even talk about products,
where the installation is progressing all by itself and without major efforts and challenges.
In addition, there are on the web detailed installation instructions for all the three products.
The products are available on Windows and Linux, and it therefore plays no special role if
you use Linux or Windows.

All sample programs are developed and tested on machines running Linux. In fact, it plays
no major role, as both Java and other products work in exactly the same way whether the
platform is one or the other. Some places will be in the books where you could see that
the platform is Linux, and this applies primarily commands that concerning the file system.
Otherwise it has no meaning to the reader that the programs are developed on a Linux
machine, and they can immediately also run under Windows unless a program refers to
the file system where it may be necessary to change the name of a file.

Finally a little about what the books are not. It is not “how to write” or for that matter
reference manuals in Java, but it is as the title says books on software development. It is
my hope that the reader when reading the books and through the many examples can find
inspiration for how to write good programs, but also can be used as a source collection
with a number of examples of solutions to concrete everyday programming problems that
you regularly face as a software developer.

7
JAVA 3: OBJECT-ORIENTED PROGRAMMING Introduction

1 INTRODUCTION
Programs should deal with data, and data must be represented and stored, which happens
in variables. A language like Java has a number of built-in types to variables (as explained
in the book Java 1), but often you need to define your own data types that better reflects
the task the program must solve. This is where the concept of a class comes in. A class is
something that define a concept or thing within the problem area, and that can be said a
lot about what a classes is, and what is not, but technically a class is a type. It’s a bit more
than just a type, as a class partly defines how data should be represented, but also what we
can do with the data of that type. A class defines both how the type will be represented,
and what operations you can perform on variables of that type. Classes are also generally
been described in the book Java 1, but in this book I will start or continue with a more
detailed discussion of Java’s class concept.

When wee create variables whose type is a class, wee talk about objects, so that a variable
of a class type is called an object, but really there is no great difference between a variable
and an object, and there is well along the road no reason to distinguish between the two.
But dig a little further down, there is a reason that has to do with how variables and objects
are allocated in the machine’s memory.

Variables whose type is int, double, boolean, char, etc., are called simple variables or primitive
types. To a running program is allocated a so-called stack that is a memory area used by the
application among other to store variables. The stack is highly efficient, so that it is very
fast for the program to continuously create and remove variables as needed. This is called
a stack, because one can think of the stack as a data structure illustrated as follows:

8
JAVA
JAVA3:3:
JAVA 3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Introduction
IntroduCtIon
IntroduCtIon

When
Whenthe
When theprogram
the programcreates
program createsa aanew
creates newvariable,
new variable,itit
variable, ithappens
happensatat
happens atthethetop
the topofof
top ofthe
thestack
the stack––
stack –where
wherethe
where the
the
arrow
arrowisis
arrow ispointing,
pointing,and
pointing, andifif
and ifa aavariable
variablemust
variable mustbebe
must beremoved,
removed,itit
removed, itisis
isthe
theone
the onethat
one thatlies
that liesatat
lies atthe
thetop
the topofof
top of
the
thestack.
the stack.Variables
stack. Variablesofof
Variables ofsimple
simpledata
simple datatypes
data typeshave
types havethe
have theproperty
the propertythat
property thatthey
that theyalways
they alwaystake
always takeup
take upthe
up the
the
same.
same.As
same. Asan
As anexample
an examplefills
example fillsan
fills anint
an intthe
int thesame
the same(4(4
same (4bytes),
bytes),no
bytes), nomatter
no matterwhat
matter whatvalue
what valueitit
value ithas.
has.Therefore
has. Therefore
Therefore
for
forthe
for thekind
the kindofof
kind ofvariables
variablesstored
variables storeddirectly
stored directlyon
directly onthe
on thestack
the stackthe
stack thecompiler
the compilerknows
compiler knowshow
knows howmuch
how muchspace
much space
space
they
theyuse.
they use.Thus,
use. Thus,ifif
Thus, ifone
oneasas
one asananexample
an exampleinin
example ina aamethod
methodwrites
method writes
writes

int a
int a =
= 23;
23;

then
thenthere
then therewill
there willbebe
will becreated
createda aavariable
created variableon
variable onthe
on thestack
the stackofof
stack oftype
typeint
type intand
int andwith
and withthe
with thespace
the spaceasas
space asan
anint
an int
int
requires
requires(4(4
requires (4bytes),
bytes),and
bytes), andthe
and thevalue
the valueisis
value isstored
storedthere.
stored there.Variables
there. Variablesthat
Variables thatinin
that inthis
thisway
this wayare
way arestored
are storeddirectly
stored directly
directly
on
onthe
on thestack,
the stack,are
stack, arealso
are alsocalled
also calledvalue
called valuetypes,
value types,and
types, andthe
and thesimple
the simpleoror
simple orprimitive
primitivetypes
primitive types––
types –except
exceptString
except String––
String –
are
areallall
are allvalue
valuetypes.
value types.
types.

Things
Thingsare
Things aredifferent
are differentwith
different withthe
with thevariables
the variablesofof
variables ofreference
referencetypes
reference typessuch
types suchasas
such asvariables,
variables,that
variables, thathas
that hasa aaclass
has class
class
type.
type.They
type. Theyhave
They havetoto
have tobebe
becreated
createdexplicitly
created explicitlywith
explicitly withnew.
with new.If,If,
new. If,forforexample
for exampleyou
example youhave
you havea aaclass
have classnamed
class named
named
Cube,
Cube,and
Cube, andyou
and youwant
you wanttoto
want tocreate
createsuch
create suchan
such anobject,
an object,you
object, youmust
you mustwrite
must write
write

Cube c
Cube c =
= new
new Cube();
Cube();

Itlooks
ItIt lookslike,
looks like,how
like, howtoto
how tocreate
createa aasimple
create simplevariable.
simple variable.The
variable. Thevariable
The variableisis
variable iscalled
calledc.c.
called c.When
Whennew
When newisis
new isexecuted,
executed,
executed,
whathappens
what
what happensisis
happens isthat
thaton
that onthe
on thea aaso-called
the so-calledheap
so-called heapisis
heap iscreated
createdan
created anobject
an objectofof
object ofthe
thetype
the typeCube.
type Cube.One
Cube. One
One
canthink
can
can thinkofof
think ofthe
theheap
the heapasas
heap asa aamemory
memorypool
memory poolfrom
pool fromwhich
from whichtoto
which toallocate
allocatememory
allocate memoryasas
memory asneeded.
needed.On
needed. On
On
thestack
the
the stackisis
stack iscreated
createdan
created anusual
an usualvariable
usual variableofof
variable oftype
typeCube,
type Cube,but
Cube, butstored
but storedon
stored onthe
on thestack
the stackisis
stack isnot
notthe
not thevalue
the value
value
ofa aaCube
ofof Cubeobject,
Cube object,but
object, butrather
but rathera aareference
rather referencetoto
reference tothe
theobject
the objecton
object onthe
on theheap.
the heap.All
heap. Allreferences
All referencestake
references takeup
take up
up
thesame
the
the sameregardless
same regardlessofof
regardless ofthe
thetype,
the type,and
type, andthey
and theycan
they canthen
can thenbebe
then bestored
storedon
stored onthe
on thestack.
the stack.That
stack. Thatisis
That iswhy
whyitit
why it
iscalled
isis calleda aareference
called referencetype.
reference type.Where
type. Whereexactly
Where exactlyan
exactly anobject
an objectisis
object iscreated
createdon
created onthe
on theheap
the heapisis
heap isdetermined
determinedby
determined by
by
a aaso-called
so-calledheap
so-called heapmanager
heap managerthat
manager thatisis
that isa aaprogram
programthat
program thatisis
that isconstantly
constantlyrunning
constantly runningand
running andmanages
and managesthe
manages the
the
heap.ItIt
heap.
heap. Itisis
isalso
alsothe
also theheap
the heapmanager,
heap manager,which
manager, whichautomatically
which automaticallyremoves
automatically removesan
removes anobject
an objectwhen
object whenitit
when itisis
isnono
no
longerneeded.
longer
longer needed.
needed.

99
9
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Introduction
IntroduCtIon

For
For the
the above
above reasons,
reasons, itit isis clear
clear that
that the
the variables
variables ofof value
value typestypes are
are more
more effective
effective than
than the
the
objects
objects of
of reference
reference types.
types. ItIt in
in no
no way
way means
means that
that objects
objects of of reference
reference types
types are
are ineffective,
ineffective,
and
and inin most
most cases
cases itit isis not
not aa difference
difference that
that you
you need
need to to relate
relate to,
to, but
but conversely
conversely there
there are
are
also
also situations
situations where
where the the difference
difference matters.
matters. Thus,
Thus, itit isis important
important to to know
know thatthat there
there are
are
big
big differences
differences inin how
how value value types
types and
and reference
reference types
types are are handled
handled by by the
the system,
system, andand that
that
in
in some
some contexts
contexts itit are
are ofof great
great importance
importance for for how
how thethe program
program will will behave,
behave, but but there’ll
there’ll
be
be many
many examples
examples that that clarify
clarify the
the difference.
difference. So So far,
far, itit isis enough
enough to to know
know thatthat the
the data
data
can
can be
be grouped
grouped into
into two two categories
categories depending
depending on on their
their data
data type,
type, soso that
that the
the data
data of
of value
value
types
types are
are allocated
allocated on on thethe stack
stack and
and isis usually
usually called
called variables,
variables, whilewhile data
data of
of reference
reference types
types
are
are allocated
allocated onon the
the heapheap andand called
called objects
objects –– although
although there there isis no
no complete
complete consistency
consistency
between
between thethe two
two names.
names.

In
In the
the bokk
bokk Java
Java 1,
1, II defined
defined the
the following
following class,
class, which
which represents
represents aa usual
usual cube:
cube:

public class Cube


{
private static Random rand = new Random();
private int eyes;

public Cube()
{
roll();
}

public int getEyes()


{
return eyes;
}

public void roll()


{
eyes = rand.nextInt(6) + 1;
}

public String toString()


{
return "" + eyes;
}
}

10
10
JAVA 3: OBJECT-ORIENTED PROGRAMMING Introduction
JAVA3:3:OBJECT-ORIENTED
JAVA OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING IntroduCtIon
IntroduCtIon

The
Thevalue
valueofofthe
theCube
Cubeor orit’s
it’sstate
stateisisisrepresented
representedby
byan
anint,
int,while
whileits
itsproperties
propertiesororbehavior
behavior
The value of the Cube or it’s state represented by an int, while its properties or behavior
isisrepresented
represented byby three
by three methods.
three methods.
methods. In In a program,
In aa program, you
program, you can
you can then
can then create
then create objects
create objects of
objects of type
typeCube
of type Cube
is represented Cube
asasfollows:
follows:
as follows:

Cube c1
Cube c1 == new
new Cube();
Cube();
Cube c2
Cube c2 == new
new Cube();
Cube();

When
Whenyou
When youcreate
you createan
create anobject
an objectof
object ofaaaclass,
of class,the
class, theclass’s
the class’sinstance
class’s instancevariables
instance variablesare
variables arecreated,
are created,and
created, andthen
and thenclass’s
then class’s
class’s
constructor
constructorisisisexecuted.
constructor executed.IfIfIfaaaclass
executed. classhas
class hasno
has noconstructor,
no constructor,there
constructor, thereautomatically
there automaticallywill
automatically willbe
will becreated
be created
created
aaadefault constructor
default constructor
default – a constructor
constructor –– aa constructor
constructor with with no
with no parameters.
no parameters. A constructor
parameters. AA constructor is characterized
constructor isis characterized
characterized
in that
in that
in it is a method
that itit isis aa method which
method which
which hashas the
has the same
the same name
same name as the
name asas the class
the class and
class and do
and do not
do not have
haveany
not have anytype.
any type.AAA
type.
constructor
constructorisisisaaamethod,
constructor method,but
method, butitititcan
but cannot
can notbe
not becalled
be calledexplicitly
called explicitlyand
explicitly andisisisperformed
and performedonly
performed onlywhen
only whenan
when an
an
object
objectisisisinstantiated.
object instantiated.The
instantiated. Theclass
The classCube
class Cubehas
Cube hasaaaconstructor,
has constructor,that
constructor, thatisisisaaadefault
that defaultconstructor.
default constructor.
constructor.

The
Theobjects
The objectsare
objects areas
are asasmentioned
mentionednot
mentioned notallocated
not allocatedon
allocated ononthethestack,
the stack,but
stack, butisisiscreated
but createdon
created onthe
on theheap.
the heap.c1
heap. c1and
c1 and
and
c2c2are
c2 areusual
are usualvariables
usual variableson
variables onthe
on thestack,
the stack,but
stack, butdoes
but doesnot
does notinclude
not includethe
include theobjects
the objectsbut
objects butinclude
but includeinstead
include instead
instead
references
referencesto
references tothe
to thetwo
the twoobjects
two objectson
objects onthe
on theheap.
the heap.It’s
heap. It’srare
It’s rareyou
rare youas
you asasaaaprogrammer
programmerneed
programmer needto
need totothink
thinkabout
think about
about
it, but
it,but
it, in
butin some
insome situations
somesituations it is important
situationsititisisimportant
importantto to know
toknow
knowthe the difference
thedifference between
differencebetweenbetweenan an object
anobject allocated
objectallocated
allocated
on the
on the
on stack
the stack and
stack and
and onon the
on the heap.
the heap. The
heap. The figure
The figure below
figure below illustrate
below illustrate how
illustrate how it looks
how itit looks in
looks in the
in the machine’s
the machine’s
machine’s
memory
memorywith
memory withthe
with thetwo
the twovariables
two variableson
variables onthe
on thestack
the stackthat
stack thatrefer
that referto
refer toobjects
to objectson
objects onthe
on theheap:
the heap:
heap:

If,
If,for
If, forexample
for exampleyou
example youin
you inthe
in theprogram
the programwrites
program writes
writes

c1 == c2;
c1 c2;

11
1111
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Introduction
IntroduCtIon

itit means
means that
that there
there no
no longer
longer is
is aa reference
reference to
to the
the object
object as
as c1
c1 before
before referring
referring to,
to, but
but
there
there are
are instead
instead two
two references
references to
to the
the object
object as
as c2
c2 refers
refers to
to (see
(see the
the figure
figure below).
below). If,
If, you
you
then writes
then writes

c1.roll();
c2.roll();

it means that the same cube is rolled twice because both references refer to the same object.
it means that the same cube is rolled twice because both references refer to the same object.
When there are no longer are any references to an object, it also means that the object is
When there are no longer are any references to an object, it also means that the object is
automatically removed from heap by the heap manager and the memory that the object
automatically removed from heap by the heap manager and the memory that the object
used, will be deallocated.
used, will be deallocated.

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

12
12
JAVA 3: OBJECT-ORIENTED PROGRAMMING Introduction

A class is referred to as a type, but it is also a concept of design. The class defines objects
state as instance variables, how objects are created, and which memory is allocated for the
objects. Objects have at a given moment a value as the content of the instance variables,
and an object’s value is referred to as its state. The class also defines in terms of its methods,
what can be done with the object, and thus how to read and modify the object’s state. The
methods define the object’s behavior.

Every Java program consists of a family of classes that together defines how the program
would operate and a running program will at a given time consist of a number of objects
instantiated from the program’s classes, objects that work together to accomplish what the
program now must do. The work to write a program is then to write the classes that the
program should consist of. Which classes that is, are in turn, not very clearly, and the
same program may typically be written in many ways made up of classes, which are quite
different. The work to determine which classes a program should consist of and how these
classes should look like in terms of variables and methods is called design. In principle,
one can say that if a program does the job properly, it may be irrelevant, which classes it
is composed of, but unsuitable classes means

-- that it becomes difficult to understand the program and thus to find and fix errors
-- that it in the future will be difficult to maintain and modify the program
-- that it becomes difficult to reuse the program’s classes in other contexts

Therefore, the design and choice of classes, is a very key issue in programming, and in that
context wee are speaking of program quality (or lack thereof ). A class is more than just a
type, but it is a definition or description of a concept from the program’s problem area.
When you have to define which classes a program must consist of, you must therefore
largely focus on classes as a tool to define important concepts more than the classes as a
type in a programming language.

13
JAVA 3: OBJECT-ORIENTED PROGRAMMING Introduction

An object is characterized by four things:

-- a unique identifier that identifies a particular object from all other


-- a state that is the object’s current value
-- a behavior that tells what you can do with the object
-- a life cycle from when the object is created and to it again is deleted

An object is created from a class, and is that time assigned a reference that identifies the
object. The class’s instance variables determine which variables to be created for the object,
and the value of these variables is the state of the object. The class’s methods define what
you can do with the object and thus the object’s behavior. The last point of concerning is
the objects life cycle, which is explained later.

To program in that way in which you see a program as composed of a number of cooperating
objects, is called object-oriented programming. For many years wee have used object-oriented
programming, and although it is primarily a question of design, it also requires that the
current programming language supports the object-oriented thinking, and this is what
makes Java an object oriented programming language. This book focuses on object-oriented
programming, including both object-oriented design, and how it is supported in Java. There
are many concepts that includes

1. objects life cycle


2. inheritance and polymorphism
3. generic types
4. collection classes

all subjects that are discussed below, and in the next book. To explain these concepts I will
consider classes as concerning students at an educational institution, as well as books in
a library.

14
JAVA3:
JAVA 3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes

2 CLASSES
2 CLASSES
In the
In the book
book Java
Java 1,
1, II have
have generally
generally described
described classes,
classes, but
but there
there isis much
much more
more toto say,
say, and
and
classes are
classes are the
the whole
whole fundamental
fundamental concept
concept inin object-oriented
object-oriented programming.
programming. This This book
book isis
therefore about
therefore about how
how to to write
write classes
classes and
and how,
how, based
based on
on these
these classes
classes to
to create
create objects.
objects. I’ll
I’ll
start with
start with aa class
class that
that can
can represent
represent aa course
course atat an
an educational
educational institution:
institution:

package students;

/**
* Class which represents a subject associated with an education.
* A subject consists in this context an id, which is an acronym that
* identifies the subject and a name.
*/

360°
public class Subject
{

.
private String id; // the subject id

thinking
private String name; // the subject's name

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


15
15
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

/**
* Creates a new subject. A subject must have both an ID and a name, and is it
* not the case, the constructor raises an exception.
* @param id The subjects id
* @param navn The subjects name
* @throws Exception If the id or the name are illegal
*/
public Subject(String id, String name) throws Exception
{
if (!subjectOk(id, name))
throw new Exception("The subject must have both an ID and a name");
this.id = id;
this.name = name;
}

/**
* @return The subjects id
*/
public String getId()
{
return id;
}

/**
* @return The subjects name
*/
public String getName()
{
return name;
}

/**
* Changes the subject's name. The subject must have a name, and if the parameter
* does not specify a name the method raises a exception.
* @param navn The subjects name
* @throws Exception If the name is null or blank
*/
public void setName(String name) throws Exception
{
if (!subjectOk(id, name)) throw new Exception("The subject must have a name");
this.name = name;
}

/**
* @return The subjects name
*/

16
16
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

public String toString()


{
return name;
}' /**

* Method tthat tests whether two strings can represent a subject.


* @param id The subjects id
* @param name The subjects name
* @return true, if id and name represents a legal subject
*/
public static boolean subjectOk(String id, String name)
{
return id != null && id.length() > 0 && name != null && name.length() > 0;
}
}

Compared
Comparedtotowhat
whatI have saidsaid
I have about classes
about in the
classes in book Java 1Java
the book there1 isthere
not much
is notnew
muchto explain,
new to
and the meaning of variables and methods are explained in the class as comments,
explain, and the meaning of variables and methods are explained in the class as comments,but you must
be
butaware
you of the be
must following.
aware of the following.

Classes
Classes are
are defined
defined by
by the
the reserved
reserved word
word class,
class, and
and aa class
class has
has aa name
name asas here
here is
is Subject.
Subject.
In Java, it is recommended that you write the name of classes capitalized,
In Java, it is recommended that you write the name of classes capitalized, but otherwise but otherwise
applies
applies the
the same
same rules
rules for
for classes
classes names,
names, that
that makes
makes the
the names
names ofof variables.
variables. AA class
class can
can have
have
aa visibility that may be public or private, but so far I will define all classes public.
visibility that may be public or private, but so far I will define all classes public. VisiblityVisiblity
says
says something
something about
about who
who may
may use
use the
the class.
class.

Classes
Classes consist
consist of
of variables
variables and
and methods,
methods, andand there
there isis in
in principle
principle nono upper
upper limit
limit for
for any
any
of
of the two parts. Both variables and methods can have public and private visibility. If aa
the two parts. Both variables and methods can have public and private visibility. If
member
member (variable
(variable or
or method)
method) is is public,
public, it
it can
can be be referenced
referenced fromfrom methods
methods in in all
all other
other
classes, that have an object of the current class, and if it is private, it can only
classes, that have an object of the current class, and if it is private, it can only be referencedbe referenced
by
by methods
methods in in the
the class
class itself.
itself. Usually
Usually you
you define
define variables
variables as as private,
private, while
while the
the methods
methods to to
be used by other classes, are defined public. Put a little different then a class
be used by other classes, are defined public. Put a little different then a class defines with defines with
public
public methods,
methods, whatwhat can
can be
be done
done with
with objects
objects ofof the
the class
class and
and thus
thus the
the objects
objects behavior.
behavior.

In
In this
this case,
case, the
the class
class has
has two
two variables,
variables, both
both ofof which
which are
are of
of the
the type
type String.
String. Such
Such variables
variables
are called instance variables, and each object of the class has its own copies of these
are called instance variables, and each object of the class has its own copies of these variables variables
whose
whose values
values are
are the
the object’s
object’s state.
state. The
The type
type String
String is
is also
also aa class
class type,
type, and
and the
the two
two variables
variables
are therefore reference types. They do not refer necessarily to anything and
are therefore reference types. They do not refer necessarily to anything and such variablessuch variables
has
has the
the value
value null
null (null
(null reference),
reference), which
which simply
simply means
means that
that you
you has
has reference
reference variables,
variables,
which does not refer to an object.
which does not refer to an object.

17
17
JAVA
JAVA 3:
JAVA 3: OBJECT-ORIENTED
3: OBJECT-ORIENTED PROGRAMMING
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes
Classes

Classes
Classes can
Classes can have
can have one
have one or
one or more
or more constructors
more constructors that
constructors that are
that are special
are special methods
special methods executed
methods executed when
executed when creating
when creating
creating
an
an object
an object of
object of the
of the class.
the class. A
class. AA construction
construction is
construction isis written
written in
written inin the the same
the same way
same way as
way as other
as other methods,
other methods, but
methods, but
but
the
the name
the name is
name isis the
the same
the same as
same as the
as the class,
the class, and
class, and they
and they do
they do not
do not have
not have any
have any type.
any type. Constructors
type. Constructors can
Constructors can
can inin
in
principle
principle perform
principle perform anything,
perform anything, but
anything, but they
but they are
they are typically
are typically used
typically used to
used to initialize
to initialize instance
initialize instance variables
instance variables in
variables in the
in the
the
class.
class. In
class. In this
In this case,
this case, the
case, the constructor
the constructor has
constructor has parameters
has parameters for
parameters for an
for an object’s
an object’s values.
object’s values. These
values. These parameters
These parameters
parameters
have
have the
have the same
the same names
same names as
names as the
as the instance
the instance variables
instance variables (it
variables (it is
(it isis notnot aaa requirement,
not requirement, and
requirement, and the
and the parameters
the parameters
parameters
must
must be
must be named
be named anything),
named anything), and
anything), and in
and in the
in the constructor’s
the constructor’s code
constructor’s code there
code there are
there are two
are two things
two things with
things with the
with the same
the same
same
name
name (both
name (both an
(both an instance
an instance variable
instance variable and
variable and aaa parameter).
and parameter). It
parameter). ItIt is
isis solved
solved by
solved by the
by the word
the word this
word this where,
this where, for
where, for
for
example
example this.name
example this.name refer
this.name refer to
refer to the
to the instance
the instance variable,
instance variable, while
variable, while name
while name specific
name specific the
specific the parameter.
the parameter. III will
parameter. will
will
insist
insist that
insist that aaa specific
that specific subject
specific subject must
subject must have
must have both
have both an
both an id
an id and
id and aaa name.
and name. Therefore,
name. Therefore, the
Therefore, the constructor
the constructor
constructor
tests
tests the
tests the parameters,
the parameters, and
parameters, and if
and ifif they
they not
they not both
not both how
both how aaa value
how value the
value the constructor
the constructor
constructor raisesraises an
raises an exception.
an exception.
exception.
Exceptions
Exceptions are
Exceptions are discussed
are discussed later,
discussed later, but
later, but if
but ifif aaa method
method as
method as here
as here can
here can raise
can raise an
raise an exception,
an exception, the
exception, the method
the method
method
must
must be
must be marked
be marked with
marked with throws:
with throws:
throws:

throws
throws Exception
Exception

IfIf the
the parameters
parameters do
do not
not have
have legal
legal values,
values, raises
raises the
the constructor
constructor an
an exception
exception

if
if (!subjectOk(id,
(!subjectOk(id, name))
name))
throw
throw new Exception("The subject
new Exception("The subject must
must have
have both
both an
an ID
ID and
and aa name");
name");

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? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

18
18
18
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes

You
You should
You should note
should note that
note that the
that the parameters
the parameters
parameters are are tested
are tested by
tested by the
by the method
the method subjectOk().
method subjectOk(). This
subjectOk(). This method
This method
method
is defined
isis defined static,
defined static, meaning
static, meaning
meaning thatthat it can
that itit can be
can be used
be used without
used without having
without having created
having created an
created an object
object ofof
an object the
of the
the
class.
class. Other
class.Other classes
Otherclasses can
classescan use
canuse the
usethe method
themethod to
methodtototest test values
testvalues before
valuesbefore creating
beforecreating
creatingthe the object.
theobject. That
object.That kind
Thatkind
kind
of control
ofof control methods
control methods
methods may may
may bebe reasonable,
be reasonable, if
reasonable, ifif youyou later
you later find
later find out
find out that
out that
that thethe controls
the controls should
controls should
should be be
be
different.
different. You
different.You should
You should then
should then simply
then simply change
simply change
change thethe method,
the method,
method, and and it is not
and itit isis not necessary
not necessary to change
necessary toto change
change
elsewhere
elsewhere in the
elsewhereininthe code.
thecode.
code.

That
Thataaaconstructor
That constructor
constructorinin this
inthis way
thisway raises
wayraises an
raisesan exception
exceptionisis
anexception isaaaguarantee
guarantee that
guaranteethat
thatnono one
noone instantiates
oneinstantiates
instantiates
illegal
illegal objects
illegal objects – the
objects –– the one
the one that
one that instantiates
that instantiates an
instantiates an object,
an object, must
object, must necessarily
must necessarily decide
necessarily decide what
decide what should
what should
should
happen
happen in
happeninincasecase the
casethe object
theobject is illegal.
objectisisillegal. However,
illegal.However,
However,we we can
wecan discuss
candiscuss the
discussthe wisdom
thewisdom of in this
wisdomofofininthis way
waytoto
thisway to
let
let constructor
letconstructor validate
constructorvalidate input
validateinput parameters
inputparameters
parametersand and possible
andpossible raise
possibleraise an
raisean exception,
anexception, and
exception,and the
andthe diskusion
thediskusion
diskusion
I will
I Iwill return
willreturn to later.
returntotolater.
later.

InIn this
Inthis case,
thiscase, the
case,the class’s
theclass’s other
class’sother methods
othermethods
methodsareare simple.
aresimple. An
simple.An object’s
object’sidid
Anobject’s must
idmust be
mustbe readable,
bereadable, but
butitit
readable,but it
must
must
mustnotnot be
notbe changed.
bechanged. Therefore,
changed.Therefore, the
Therefore,the class
theclass has
classhas only
hasonly a method
onlyaamethod
method
public String getId()
public String getId()

toto returns
to returns the
returns the value.
the value. Methods
value. Methods which
which inin
Methods which that
in that way
that way just
way just returns
just returns the
returns the value
value ofof
the value of anan instance
an instance
instance
variable,
variable, usually
variable,usually
usuallyallall use
alluse this
usethis syntax
thissyntax (the
syntax(the variable’s
(thevariable’s name
variable’sname
namewithwith the
withthe first
thefirst character
firstcharacter in uppercase
characterininuppercase
uppercase
and
and prefixed
andprefixed with
prefixedwith
withthe the word
theword get),
wordget), and
get),and you
andyou
youcallcall them
callthem
themforfor get-methods.
forget-methods. Similarly,
get-methods.Similarly,
Similarly,thethe variable
thevariable
variable
name
name
namealsoalso has
alsohas a
hasaaget get method,
getmethod, but
method,but here
buthere it must
hereititmust also
mustalso
alsobebe possible
bepossible to change
possibletotochange
changethethe name.
thename.
name.TheThe
The
class
class then
classthen has
thenhas a set-method
hasaaset-method
set-methodforfor name:
forname:
name:
public void setName(String name)
public void setName(String name)

and
and methods which in that way only are used to change the value of an instance variable,
and methods
methods which
which in in that
that way
way only
only are
are used
used to
to change
change the
the value
value of
of an
an instance
instance variable,
variable,
usually
usuallyall use this syntax. In this case, the method may raise an exception ififthe name has
usually all use this syntax. In this case, the method may raise an exception if the name has
all use this syntax. In this case, the method may raise an exception the name has
an
anillegal
illegalvalue,
value, but
but ititisisnot
notaarequirement
requirement that
thatthe
theset-methods
set-methods may
may raise
raise anan exception.
exception.
an illegal value, but it is not a requirement that the set-methods may raise an exception.

Both
Both the class and its methods are decorated with Java comments. With aa special tool
Both the
the class
class and and its
its methods
methods are are decorated
decorated with
with Java
Java comments.
comments. With
With a special
special tool
tool
you
you can
can from
from these
these comments
comments create
create aa full
full finished
finished html
html documentation
documentation ofof classes
classes inin aa
you can from these comments create a full finished html documentation of classes in a
program.
program. I’ll explain how later, and also what the various descriptions elements means, but
program. I’ll
I’ll explain
explain how
how later,
later, and
and also
also what
what thethe various
various descriptions
descriptions elements
elements means,
means, butbut
ininthis
this case,
case, ititisiseasy
easy enough
enough totofigure
figure out
out the
the meaning.
meaning. IfIfyou
youplace
place the
thecursor
cursor ininfront
front
in this case, it is easy enough to figure out the meaning. If you place the cursor in front
ofofaamethod and enters
of a method
method and and enters
enters
/**
/**
plus the Enter key, then NetBeans creates a skeleton for a comment, and one of the
plus
plus the
the Enter
Enter key, then NetBeans creates aa skeleton for
for aa comment, and one
one of
of the
advantages is, thatkey, thenway
in that NetBeans creates to
you remember skeleton
write comments comment, and parameters
for a method’s the
advantages
advantages is, that
is, that in that
in any way you remember
thatexceptions. to write comments for a method’s parameters
way you remember to write comments for a method’s parameters
and return value and
and
and return value and any exceptions.
return value and any exceptions.

19
1919
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes

Objects
Objectsmust
mustbebecreated
createdororinstantiated,
instantiated,which
whichisisdone
donewith
withnew:
new:

package students;

public class Students


{
public static void main(String[] args)
{
try
{
Subject subject = new Subject("MAT7", "Matematichs");
System.out.println(subject);
subject.setName("Matematichs 7");
System.out.println(subject);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

The
Theprogram
programcreates
createsananobject
objectsubject
subjectofofthe
thetype
typeSubject.
Subject.When
Whenthe theconstructor
constructorininthe theclass
class
Subject
Subjectmay
mayraise
raiseananexception,
exception,ititshould
shouldbebehandled,
handled,and andititisisnecessary
necessarytotoplace
placethe
thecode
code
that
thatmay
mayraise
raiseananexception
exceptioninina atry/catch.
try/catch.After
Afterthe theobject
objectisiscreated,
created,ititisisprinted
printedon onthe
the
screen.
screen.IfIfyou
youprints
printsananobject
objectwith
withprintln(),
println(),ititisisthe
thevalue
valueofofthe
theobject’s
object’stoString()
toString()method
method
that
thatisisprinted.
printed.InInprinciple,
principle,allallclasses
classeshas
hasa atoString()
toString()method
methodwhichwhichreturns
returnsa atext
textthat
that
represents
representsa aparticular
particularobject.
object.Finally
Finallythe
theprogram
programchangeschangesthe thename
nameofofthe thesubject,
subject,and
and
the
theobject
objectisisprinted
printedagain.
again.

The
Theclasses
classes(Subject
(Subjectand
andStudents)
Students)described
describedabove
abovecan
canbebefound
foundininthe
theproject
projectStudents1.
Students1.

EXERCISE
EXERCISE11
Create
Createa anew
newproject
projectininNetbeans
Netbeansthat
thatyou
youcan
cancall
callLibrary.
Library.You
Youmust
mustadd
adda aclass
classthat
that
should
shouldbebecalled
calledPublisher
Publisherthat
thatrepresents
representsa abook
bookpublisher
publisherwhen
whenthe
thepublisher
publishermust
musthas
has
the
thefollowing
followingtwo
twoproperties:
properties:

1.
1.ananinteger,
integer,that
thatyou
youcan cancall
callcode
codewhich
whichisistotobebeinterpreted
interpretedasasa apublisher
publisheridentifier
identifier
2.
2.a aname,
name,that
thatjust
justisisa atext
textand
andisisthe
thepublishers
publishersname name

20
20
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

ItIt isis aa requirement


requirement that
that the
the publisher
publisher number
number isis aa positive
positive integer
integer and
and that
that aa publisher
publisher must
must
have
have aa name. name. The
The class
class must
must have
have aa constructor
constructor that
that has
has parameters
parameters for
for both
both variables
variables and
and
has
has the the following
following public
public methods:
methods:

--- get
get methods
methods toto both
both variables
variables
--- aa set
set method
method toto the
the publishers
publishers name
name
--- aa toString()
toString() method
method that
that returns
returns the
the publishers
publishers name
name followed
followed by
by the
the publisher
publisher
number
number in in square
square brackets
brackets

When
Whenyou youhave
havewritten
writtenthe
theclass,
class,you
youmust
mustdocument
documentititand
andits
itsmethods
methodsusing
usingJava
Javacomments.
comments.
Finally,
Finally, in
in the
the main
main class
class –– that
that class
class Library
Library –– you
you should
should write
write aa main()
main() method
method that
that

--- Creates
Creates aa Publisher
Publisher object
object –– you
you decide
decide the
the values
values
--- Prints
Prints the
the publisher
publisher
--- Change
Change thethe publishers
publishers name
name
--- Prints
Prints the
the publisher
publisher again
again

IfIf you
you executes
executes the
the program,
program, the
the result
result could
could be
be the
the following:
following:

The new Publisher [123]


The old Publisher [123]

AXA Global
Graduate Program
Find out more and apply

21
21
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

2.1
2.1 MORE
MORE CLASSES
CLASSES
II will
will then
then look
look at
at aa class
class representing
representing aa subject
subject that
that aa student
student has
has completed
completed or or participate
participate
in.
in. ItIt isis assumed
assumed forfor simplicity
simplicity that
that the
the same
same subjects
subjects only
only can
can be
be performed
performed once once aa year
year
and
and therefore
therefore areare identified
identified thethe subject’s
subject’s id
id and
and the
the year.
year. The
The project
project isis called
called Students2
Students2
and
and isis created
created as
as aa copy
copy ofof Strudents1.
Strudents1. There
There isis added
added thethe class
class Course
Course as
as shown
shown below,
below, and
and
again
again explains
explains the
the comments
comments of of the
the individual
individual methods
methods there
there purposes:
purposes:

package students;
/**
* Class that represents a course, where a course regarding a year and a subject.
* A student may have completed or attend a particular course.
* It is an assumption that the same subjects only be executed once a year.
* A course can also be associated with a character. If so, it means that
* the student has completed the course.
*/
public class Course
{
// year of when the course is completed or offered
private int year;

// the subject that the course deals


private Subject subject;

// the character tkhat a student has obtained in the subject


private int score = Integer.MIN_VALUE;

/**
* Creates a course for a concrete subjects and a given year.
* @param year The year for the course
* @param subject The subject for this course
* @throws Exception If the year is illegal or the subject is null
*/
public Course(int year, Subject subject) throws Exception
{
if (!courseOk(year, subject)) throw new Exception("Illegal course");
this.year = year;
this.subject = subject;
}

/**
* A cource is identified by the subjects id and the year
* @return ID composed of the year of the subject's id separated by a hyphen
*/
public String getId()
{

22
22
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

return year + "-" + subject.getId();


}
/**
* @return The year where the course is held.
*/
public int getYear()
{
return year;
}
/**
* @return true, if the student has completed the course
*/
public boolean completed()
{
return score > Integer.MIN_VALUE;
}

/**
* @return The character that the student has achieved
* @throws Exception If a student has not obtained a character
*/
public int getScore() throws Exception
{
if (score == Integer.MIN_VALUE)
throw new Exception("The student has not completed the course");
return score;
}

/**
* Assigns this course a score.
* @param score The score that is the obtained
* @throws Exception If the score is illegal
*/
public void setScore(int score) throws Exception
{
if (!scoreOk(score)) throw new Exception("Illegal ckaracter");
this.score = score;
}

/**
* Assigns this course a character.
* @param score The score that is the obtained
* @throws Exception If the score is illegal
*/
public void setScore(String score) throws Exception
{
try
{

23
23
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

int number = Integer.parseInt(score);


if (!scoreOk(number)) throw new Exception("Illegal score");
this.score = number;
}
catch (Exception ex)
{
throw new Exception("Illegal score");
}
}

/**
* @return The course's subject
*/
public String toString()
{
return subject.toString();
}

/**
* Tests whether the parameters for a course are legal
* @param year The year for the course
* @param subject The subject that this course deals
* @return true, If the year is illegal or the subject is null

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

24
24
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

*/
public static boolean courseOk(int year, Subject subject)
{
return year >= 2000 && year < 2100 && subject != null;
}

// Validates whether a character is legal


private boolean scoreOk(int score)
{
return true;
}
}

The class looks like the class Subject, but there are still things that you should note. The
class has three instance variables, and one of the type Subject. You should therefore note
that the type of an instance variable may well be a user-defined type and here a class. There
is also an instance variable called year that has the type int. There is a variable score, that
should be applied to the score which a student has achieved in the subject. In one way or
another it should be possible to indicate that a student has not yet been given a score, for
example because the course has not been completed. This is solved by assigning the variable
the value Integer.MIN_VALUE which is the least 32-bit integer that can occur. This number
is -2147483648, and one must assume that this score can not occur in a character system.

Note that wee in Java uses the same rules and conventions for method names that wee use
for variables and such should the name of a method to start with a lowercase letter.

The method setScore(), which assigns a course a character is available in two versions. In
Java, a method is identified by its name and its parameters. There may well in the same
class be two methods with the same name as long as they have different parameters, that
is when the parameter lists can be separated either on the parameter types or the number
of parameters. It is sometimes said that the methods can be overloaded. In this case, as
mentioned, there are two versions of the method setScore(), one with an int as a parameter,
while the other has a String. So you can specify a character as both an int and a String, and
the possibility is included only to illustrate the concept of function overloading.

When you assign a course a score it is validated by the method scoreOk(). This method is
trivial, since it always returns true, and it provides little sense. The goal is that the method
at a later time should be changed to perform something interesting, and you can say that
the problem is that the class Course not have knowledge of what is legal scores. There are
several grading systems.

25
25
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes

Now
NowI Ihave
havedefined
definedtwo
twoclasses
classesregarding
regardingstudents,
students,and
andthere
thereisisaaconnection
connectionbetween
betweenthe
the
two classes so that the class Course consist of an object of the class Subject. It is sometimes
two classes so that the class Course consist of an object of the class Subject. It is sometimes
illustrated
illustratedasas

IfIfyou
youhave
havetotocreate
createaaCourse,
Course,youyoumust
mustprovide
provideaayear
yearand
andaaSubject,
Subject,which
whichisisan
anobject
object
that
thatmust
mustalso
alsobebecreated.
created.IfIfyou
youfind
findititappropriate,
appropriate,you
youcan
canadd
addan
anadditional
additionalconstructor
constructor
that creates this object:
that creates this object:

/**
* Creates a course for a concrete subjects and a given year.
* @param year The year for the course
* @param id The subject's id
* @param name The subject's name
* @throws Exception If the year is illegal or id and name are not legal
*/
public Course(int year, String id, String name) throws Exception
{
subject = new Subject(id, name);
if (!courseOk(year, subject)) throw new Exception("Illegal year");
this.year = year;
}

You
Youmust
mustspecifically
specificallynote
notethat
thatififthe
theclass
classSubject
Subjectraises
raisesan
anexception
exception(the
(theconstructor
constructorofof
the
theclass
classSubject)
Subject)when
whenthetheobject
objectisiscreated,
created,then
thenthe
theabove
aboveconstructor
constructorisisinterrupted
interruptedby
by
sending
sendingthe
theexception
exceptionobject
objectfrom
fromthe theclass
classSubject
Subjectonontotothe
thecalling
callingcode.
code.Constructors
Constructors
can thus be overloaded by the exact same rules as for other
can thus be overloaded by the exact same rules as for other methods.methods.

Below
Belowisisaamethod
methodthat
thatcreates
createstwo
twocourses:
courses:

private static void test1()


{
try
{
Course course1 = new Course(2015, new Subject("MAT6", "Matematik 6"));
Course course2 = new Course(2015, "MAT7", "Matematik 7");
course1.setScore(7);
print(course1);
print(course2);
}
catch (Exception ex)

26
26
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

{
System.out.println(ex.getMessage());
}
}

private static void print(Course course) throws Exception


{
System.out.println(course);
if (course.completed())
System.out.println("The course is completed with the result "
+ course.getScore());
}

Note
Note how
how to
to create
create objects
objects of
of the
the type
type Course
Course andand howhow the
the two
two different
different constructors
constructors are
are
used. You should note that the method getScore() may raise an exception.
used. You should note that the method getScore() may raise an exception. Therefore, the Therefore, the
print()
print() method
method maymay raise
raise an
an exception,
exception, and
and ifif itit happens
happens the
the method
method will
will be
be interrupted
interrupted
and
and the Exception object is passed on to the method test1(). Also note how in the
the Exception object is passed on to the method test1(). Also note how in the print()
print()
method
method you refers to methods in the Course class using the dot operator on the course
you refers to methods in the Course class using the dot operator on the course
object, and that the methods works on the specific Course object’s
object, and that the methods works on the specific Course object’s state. state.

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
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

27
27
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

II will
will then
then look
look at
at aa class
class that
that represents
represents aa student.
student. A A student
student must
must inin this
this example
example alone
alone
have
have aa mail
mail address
address and
and aa name,
name, and
and also
also aa student
student could
could have
have aa number
number of of courses
courses that
that
the
the student
student has
has either
either completed
completed oror participates
participates in.
in. This
This can
can be
be illustrated
illustrated as
as follows:
follows:

where
where ** indicates
indicates that
that aa student
student may
may be
be associated
associated with
with many
many Course
Course objects.
objects. The
The class
class isis
shown
shown below,
below, and
and itit takes
takes up
up aa lot
lot particular
particular because
because of
of the
the comments,
comments, butbut to
to emphasize
emphasize
that
that classes
classes should
should be be documented
documented by by comments,
comments, II have
have chosen
chosen to
to retain
retain them,
them, and
and they
they
also
also helps
helps to
to explain
explain the
the meaning
meaning of of class’s
class’s methods:
methods:

package students;

import java.util.*;
/**
* The class represents a student when a student is characterized by a mail
* address.
* As a unique identifier is used, a number that is automatically incremented
* by 1 each time a new object is created.
* A student has a list of courses that the student has completed or
* participate in.
*/
public class Student
{
private static int nummer = 0; // the last used id
private int id; // the students id
private String mail; // the student's mailadresse
private String name; // the student's name
private ArrayList<Course> courses = new ArrayList(); // a list with courses

/**
* Creates a new student from an array of courses.
* @param mail The student's mail address
* @param name The student's name
* @param course An array with courses
* @throws Exception If the mail or the name does not represents legal values
*/
public Student(String mail, String name, Course … course) throws Exception
{
if (!studentOk(mail, name))
throw new Exception("Ulovlig værdier for en studerende");

28
28
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

this.mail = mail;
this.name = name;
for (Course c : course) courses.add(c);
id = ++nummer;
}
static
{
nummer = 1000;
}

/**
* @return The student's id
*/
public int getId()
{
return id;
}

/**
* @return The students mail address
*/
public String getMail()
{
return mail;
}

/**
* Changes the mail address on a student.
* @param mail The student's mail address
* @throws Exception If no legal mail address is specified
*/
public void setMail(String mail) throws Exception
{
if (mail == null || mail.length() == 0)
throw new Exception("Illegal mail adresse");
this.mail = mail;
}

/**
* @return The student's name
*/
public String getName()
{
return name;
}

29
29
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

/**
* Changing the name of a student.
* @param name The student's name
* @throws Exception If no name is specified
*/
public void setName(String name) throws Exception
{
if (name == null || name.length() == 0) throw new Exception("Illigal name");
this.name = name;
}

/**
* @return Number of courses that this student has completed or participated in
*/
public int getCount()
{
return courses.size();
}

/**
* Returns the n'th course for this student
* @param n Index of the desired course
* @return The nth course like this student has completed or participated in

30
30
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

* @throws Exception If the is illegal


*/
public Course getCourse(int n) throws Exception
{
return courses.get(n);
}

/**
* @param id Identifier of a course
* @return Teh course identified by id
* @throws Exception If the course is not found
*/
public Course getKursus(String id) throws Exception
{
for (Course c : courses) if (c.getId().equals(id)) return c;
throw new Exception("Course not found");
}

/**
* Returns the courses that the current student have completed or participated
* in a particular year.
* @param year The year searching for
* @return Course list of discovered courses
*/
public ArrayList<Course> getCourses(int year)
{
ArrayList<Course> list = new ArrayList();
for (Course c : courses) if (c.getYear() == year) list.add(c);
return list;
}

/**
* Adds a course for the students.
* @param course The course to be added
* @throws Exception If the list already have the same course
*/
public void add(Course course) throws Exception
{
for (Course c : courses)
if (course.getId().equals(c.getId()))
throw new Exception("The course is already added");
courses.add(course);
}

/**
* @return Returns the student's id address and name

31
31
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
*/
public String toString()
*/
{
public String toString()
return "[" + id + "] " + name;
{
}
return "[" + id + "] " + name;
}
/**
* Tests whether the mail and name to represent a student.
/**
* @param mail A student's mail address
* Tests whether the mail and name to represent a student.
* @param name A student's name
* @param mail A student's mail address
* @return true, if mail and name represents a legal student
* @param name A student's name
*/
* @return true, if mail and name represents a legal student
public static boolean studentOk(String mail, String name)
*/
{
public static boolean studentOk(String mail, String name)
// the control is simple and should be extended to check whether mail has a
{
// proper format for an email address
// the control is simple and should be extended to check whether mail has a
return mail != null && mail.length() > 0 && name != null && name.length() > 0;
// proper format for an email address
}
return mail != null && mail.length() > 0 && name != null && name.length() > 0;
}
}
}
The
Theclass
classStudent
Studentrepresents
representsaastudent.
student.TheTheclass
classhashasfour
fourinstance
instancevariables,
variables,where
wherethe thefirst
first
isisan
anidentifier
identifier(a number),
number),athe next
nexttwo are ofofthe type String
Stringand isisrespectively the mail
The class Student (a
represents the
student. two
The areclass hasthefour
typeinstance and respectively
variables, where the thefirst
mail
address and andthe student’s
student’sname. The last is of the type ArrayList<Course>, and
andshould be
is address
an identifier the
(a number), name.
the nextThe
twolast
areisofofthe
thetype
typeString
ArrayList<Course>,
and is respectively should
the mailbe
used
usedtotoand
the
thecourses
courses that
thatthe
the student
student has completed ororparticipates in.
in.The
Theclass’s constructor
address the student’s name. The has
last completed
is of the type participates
ArrayList<Course>, class’s constructor
and should be
raises an exception ififthe parameters are not legal. The class’s other methods require no
used to the courses that the student has completed or participates in. The class’s constructorno
raises an exception the parameters are not legal. The class’s other methods require
special
special explanation, but note, however, that the method getCourses() isisoverloaded.
raises an explanation,
exception if butthe note, however,
parameters are that
not the
legal.method getCourses()
The class’s overloaded.
other methods require no
special explanation, but note, however, that the method getCourses() is overloaded.
AnAnobject
objecthas
hasaavariable
variableid,
id,which
whichisisaanumber
numberthat
thatcan
canidentify
identifyaastudent.
student.This
Thisnumber
number
is automatically assigned in the
the constructor starting with 1001
1001aand such that the
the next
Anis object
automatically assigned
has a variable id, in
which constructor
is a numberstarting
that canwith
identify and suchThis
student. thatnumber next
student isisassigned the
thenext number. How
Howitstarting
itexactly works, I Iwill return totowhen I Italk
is student assigned
automatically assigned next
in thenumber.
constructor exactlywith
works,
1001 will
and return
such thatwhen
the nexttalk
about
aboutstatic
staticmembers.
members.
student is assigned the next number. How it exactly works, I will return to when I talk
about static members.
Below
Belowisisaamethod,
method,which
whichcreates
createstwo
twostudents:
students:
Below is a method, which creates two students:
private static void test2()
{
private static void test2()
try
{
{
try
Student stud1 = new Student("svend@mail.dk", "Svend Andersen");
{
Student stud2 = new Student("gorm@mail.dk", "Gorm Madsen",
Student stud1 = new Student("svend@mail.dk", "Svend Andersen");
new Course(2015, new Subject("PRG", "Programming")),
Student stud2 = new Student("gorm@mail.dk", "Gorm Madsen",
new Course(2015, new Subject("OPS", "Operating systems")));
new Course(2015, new Subject("PRG", "Programming")),
stud1.add(new Course(2014, new Subject("DBS", "Database Systems")));
new Course(2015, new Subject("OPS", "Operating systems")));
stud2.add(new Course(2014, new Subject("WEB", "Web applicattions")));
stud1.add(new Course(2014, new Subject("DBS", "Database Systems")));
stud2.add(new Course(2014, new Subject("WEB", "Web applicattions")));

32

32
32
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

stud1.getCourses("2014-DBS").setScore(4);
stud2.getCourses("2014-WEB").setScore(10);
stud2.getCourses("2015-OPS").setScore(2);
print(stud1);
print(stud2);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}

private static void print(Student stud)


{
System.out.println(stud);
for (int i = 0; i < stud.getCount(); ++i)
{
try
{
Course c = stud.getCourse(i);
System.out.println(c + ", " +
(c.completed() ? "Score: " + c.getScore() : "Not completed"));
}

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

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.rug.nl/feb/education

33
33
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

catch (Exception ex)


catch (Exception ex)
{
{
}
}
}
}
}
}

The
Thefirst
firststudent
studentisiscreated
createdwithout
withoutspecifying
specifyingcourses.
courses.The
Theother
otherstudent
studentisiscreated
createdwith
with
The
two first
courses.student
Next, is
thecreated without
program adds specifying
a course courses.
to both The other
students andstudent
finally is created
assigns with
scores
two courses. Next, the program adds a course to both students and finally assigns scores
twothree
for courses. Next, the program adds a course to both method
students and finally theassigns scores
for threecourses,
courses,and
andthethetwo
twostudents
studentsare
areprinted.
printed.The
The methodisisexecuted,
executed, theresult
resultis:is:
for three courses, and the two students are printed. The method is executed, the result is:
[1001] Svend Andersen
[1001] Svend Andersen
Database Systems, Score: 4
Database Systems, Score: 4
[1002] Gorm Madsen
[1002] Gorm Madsen
Programming, Not completed
Programming, Not completed
Operating systems, Score: 2
Operating systems, Score: 2
Web applicattions, Score: 10
Web applicattions, Score: 10

EXERCISE22
EXERCISE
EXERCISE 2
Thisexercise
This exercise is a continuationofofexercise
exercise 1. Startby
by makinga acopy
copy of theproject
project Libraryasas
This exerciseisisa acontinuation
continuation of exercise1.1.Start
Start bymaking
making a copyofofthe
the projectLibrary
Library as
youcan
you cancall
callLibrary1
Library1andandopen
openthe
thecopy
copyininNetBeans.
NetBeans.You
Youmust
mustaddadda aclass
classnamed
namedAuthor.
Author.
you can call Library1 and open the copy in NetBeans. You must add a class named Author.
Theclass
The class shouldhavehave threeinstance
instance variables
The classshould
should havethreethree instancevariables
variables

1.ididwhich
1. which is an integer,that
that canidentify
identify an author
1. id whichisisananinteger,
integer, thatcan
can identifyananauthor
author
2.firstname
2. firstnamefor
forthe
theauthor’s
author’sfirst
firstname
name
2. firstname for the author’s first name
3.lastname
3. lastname forthethe author’slast
last name
3. lastnameforfor theauthor’s
author’s lastname
name

ItIt is a requirementthat
Itisisa arequirement
requirement thatthe
first nameisisnot
that thefirst
the firstname
not null,but
name is notnull,
but it is allowedtotobebeblank.
null, butititisisallowed
blank. Onthe
allowed to be blank.On
the
On the
otherhand,
other hand, an authormust
must havea alast
last name.
other hand,ananauthor
author musthave
have a lastname.
name.

TheTheclass
class shouldhavehave a constructor,whichwhich hastwo
two parameters,respectively
respectively to initialize
The classshould
should havea aconstructor,
constructor, whichhas has twoparameters,
parameters, respectivelytotoinitialize
initialize
firstnameand
firstname andlastname.
lastname.AAauthor’s
author’sididshould
shouldbebeassigned
assignedautomatically,
automatically,sosothat
thatevery
everytime
time
firstname and lastname. A author’s id should be assigned automatically, so that every time
a aanew
newAuthor
Author is createdthe
new Authorisiscreated
the objectget
created theobject
get an id,which
object getananid,
which is onegreater
id, whichisisone
greater thanthe
one greaterthan
the previousone.
than theprevious
one.
previous one.
YouYoucancan solvethis
this a staticvariable:
variable:
You cansolve
solve thisa astatic
static variable:
private static int counter = 0;
private static int counter = 0;

whichisiscounted
which counted upby
by 1 eachtime
time a newAuthor
Author is created.
which is countedupup by11each
each timea anew
new Authorisiscreated.
created.

Regardingthe
Regarding the methods,the must havea aget
the classmust get methodforfor all thethree
three variables,and
and a
Regarding themethods,
methods, theclass class musthave
have a getmethod
method forallallthe
the threevariables,
variables, anda a
setset methodfor
setmethod
for bothfirstname
method forboth
firstname andthe
both firstnameand
the lastname.Finally,
and thelastname.
Finally, theremust
lastname. Finally,there
must be a toString()method
there mustbebea atoString()
method
toString() method
thatreturns
that returns an author’sfirst
first andlast
last nameseparated
separated bya aspace.
space.
that returnsananauthor’s
author’s firstandand lastname
name separatedby by a space.

34
34
JAVA
JAVA3:
JAVA 3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes
Classes

Once
Onceyou
Once youhave
you havewritten
have writtenthe
written theclass,
the class,you
class, youmust
you mustdocument
must documentit
document ititusing
usingJava
using Javacomments.
Java comments.
comments.

In
InInthe
themain
the mainclass,
main class,write
class, writeaaamethod
write methodthat
method thatcan
that canprint
can printan
print anAuthor  
an Author:: :
Author

private static
private static void
void print(Author
print(Author a)
a)

when
whenthe
when themethod
the methodshould
method shouldprint
should printthe
print theauthor’s
the author’sid
author’s ididlisted
listedin
listed ininbrackets,
brackets,as
brackets, asaswell
wellas
well asasthe
theauthor’s
the author’sfirst
author’s first
first
and
andlast
and lastname.
last name.Write
name. Writethe
Write themain()
the main()method
main() methodso
method sosoit
ititperforms
performsthe
performs thefollowing:
the following:
following:

---- creates
createstwo
creates twoauthors
two authors–––you
authors youdecides
you decidesthe
decides thenames
the names
names
---- prints the
printsthe
prints two
thetwo authors
twoauthors
authors
---- change
changethe
change thefirst
the firstname
first nameof
name ofofthethefirst
the firstauthor
first author
author
---- change
changethe
change thelast
the lastname
last nameof
name ofofthetheother
the otherauthor
other author
author
---- prints
printsthe
prints thetwo
the twoauthors
two authorsagain
authors again
again

If
IfIfyou
youexecutes
you executesthe
executes theprogram
the programthe
program theresult
the resultcould
result couldbe:
could be:
be:

[1] Gudrun
[1] Gudrun Jensen
Jensen
[2] Karlo Andersen
[2] Karlo Andersen
[1] Abelone
[1] Abelone Jensen
Jensen
[2] Karlo Kristensen
[2] Karlo Kristensen

EXERCISE
EXERCISE33
Make
Makeaacopy
copyofofthe
theproject
projectLibrary1
Library1and
andcall
callthe
thecopy
copyLibrary2.
Library2.Open
OpenititininNetBeans.
NetBeans.Add
Add
aaclass
classBook
Bookthat
thatrepresents
representsaabook
bookwith
withthe
thefollowing
followingcharacteristics:
characteristics:

--- Isbn,
Isbn,that
thatmust
mustbe bedeclared
declared
--- Title,
Title,that
thatmust
mustbe bedeclared
declared
--- Publisher
Publisheryear,
year,there
theremust
mustbe be00ororlie
liebetween
between1900 1900andand2100,
2100,00indicates
indicatesthat
that
publisher
publisheryear
yearisisunknown
unknown
--- Edition,
Edition,which
whichmust
mustbe bebetween
between00andand15 15(inclusive),
(inclusive),00indicates
indicatesthat
thatthe
theedition
edition
isisunknown
unknown
--- Number
Numberofofpagespagesthat
thatmust
mustbebenon-negative,
non-negative,00indicates
indicatesthat
thatnumber
numberofofpages
pages
are
areunknown
unknown
--- Publisher,
Publisher, there
there must
must be
be aa Publisher
Publisher object
object oror null,
null, where
where null
null means
means that
that the
the
publisher
publisherisisunknown
unknown
--- AAnumber
numberofofauthors,
authors,there
theremust
mustAuthor
Authorobjects
objects(the(thenumber
numberafafauthors
authorsmust
mustbe be
00ififno
noauthors
authorsareareknown)
known)

3535
35
JAVA
JAVA 3:
3: OBJECT-ORIENTED PROGRAMMING
OBJECT-ORIENTED PROGRAMMING Classes
Classes

The
The class
class must
must have
have four constructors with
four constructors with the
the following
following signatures:
signatures:

public Book(String isbn, String title) throws Exception


{

}

public Book(String isbn, String title, int released) throws Exception


{

}

public Book(String isbn, String title, Publisher publisher) throws Exception


{

}

public Book(String isbn, String title, int


released, int edition, int pages,
Publisher publisher) throws Exception
{

}

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.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

36

36
JAVA
JAVA3:
JAVA 3:OBJECT-ORIENTED
3: OBJECT-ORIENTEDPROGRAMMING
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes
Classes

There
Theremust
There
There mustbe
must
must beget
be
be getmethods
get
get methodsfor
methods
methods forall
for
for allof
all
all ofthe
of
of theabove
the
the abovefields,
above
above fields,and
fields,
fields, andthere
and
and theremust
there
there mustbe
must
must beset
be
be setmethods
set
set methodsto
methods
methods tothe
to
to the
the
the
fields
fields title,
fields title, released,
title, released, edition,
released, edition, pages
edition, pages and
pages and publisher.
and publisher.
publisher.

AsAsfor
As forauthors
for authorsthe
authors theclass
the classshould
class shouldin
should inthe
in thesame
the samemanner
same mannerasas
manner asthe
theclass
the classStudent
class Studenthave
Student havean
have anArrayList<Author>
an ArrayList<Author>
ArrayList<Author>
the
theAuthor
the
the Authorobjects:
Author
Author objects:
objects:
objects:

private
private ArrayList<Author>
ArrayList<Author> authors
authors == new
new ArrayList();
ArrayList();

The
Theclass
The classBook
class Bookshould
Book shouldhave
should haveaaatoString()
have toString()method
toString() methodmust
method mustreturn
must returnthe
return thebook’s
the book’sISBN
book’s ISBNand
ISBN andthe
and thetitle
the title
title
separated
separated by
separated by a space.
by aa space. Finally,
space. Finally, there
Finally, there must
there must be
must be a static
be aa static method:
static method:
method:

public
public static
static boolean
boolean isbnOk(String
isbnOk(String isbn)
isbn)

that
thatvalidates
that validatesan
validates anisbn,
an isbn,when
isbn, whenitititso
when sofar
so faronly
far onlyshould
only shouldtest
should testthat
test thatthe
that theparameter
the parameterisisisnot
parameter notan
not anempty
an emptystring.
empty string.
string.

Once
Onceyou
Once youhave
you havewritten
have writtenthe
written theclass,
the class,you
class, youmust
you mustdocument
must documentitititand
document andits
and itsmethods.
its methods.
methods.

In
Inthe
In themain
the mainclass,
main class,write
class, writeaaamethod
write methodthat
method thatcan
that cancreate
can createand
create andreturn
and returnaaaBook
return Bookobject
Book objectfrom
object frominformation
from information
information
on
onthe
on
on thebook’s
the
the book’sproperties:
book’s
book’s properties:
properties:
properties:

private
private static
static Book
Book create(String
create(String isbn,
isbn, String
String
title,
title, int
int released,
released, int
int edition,
edition,
int
int pages,
pages, Publisher
Publisher publisher,
publisher, Author
Author …… authors)
authors) throws
throws Exception
Exception
{{
}}

You
You must
Youmust then
mustthen write
writeaaamethod
thenwrite method that
methodthat can
thatcan print
printaaabook:
canprint book:
book:

private
private static
private static void
static void print(Book
void print(Book book)
print(Book book) {}
book) {}
{}

when
whenititithas
when has to
hasto print
toprint
print

----- the
the
the book’s
book’s
thebook’s ISBN
ISBN
book’sISBN
ISBN
---- the book’s
thebook’s
the title
book’stitle
title
---- the book’s
thebook’s
the publisher
book’spublisher
publisheryearyear
yearifififknown
known
known
---- the book’s
thebook’s
the edition
editionifififknown
book’sedition known
known
----- the
the
the book’s
book’s
thebook’s number
number
book’snumber
numberof of
of pages
pagesififif
pages
ofpages known
known
ifknown
known
---- the book’s
thebook’s
the publisher
publisherifififknown
book’spublisher known
known
---- the book’s
thebook’s
the authors
authorsifififthere
book’sauthors there
thereare are authors
areauthors
authors

37
37
37
37
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

You
Youmust
mustfinally
finallywrite
writethethemain()
main()method,
method,sosoititperforms
performsthe
thefollowing:
following:
You must finally write the main() method, so it performs the following:
--- create
createaabook
bookusing
usingthe
theabove
abovemethod
methodwherewhereyou
youspecify
specifyvalues
valuesforforall
allthe
thebook’s
book’s
- fields
create a
and book using
including the above
book’s method
author(s)
fields and including the book’s author(s) where you specify values for all the book’s
--- create
fields
createand including
aabook
book wherethe
where youbook’s
you only author(s)the
onlyinitialize
initialize thebook’s
book’sISBN
ISBNand andtitle
title
--- prints
create a
thebook
two where
books
prints the two books you only initialize the book’s ISBN and title
--- change
prints
changethe thetwo
the books year,
publisher
publisher year,edition,
edition,number
numberofofpages
pagesand
andthethepublisher
publisherfor forthe
thelast
last
- book
change andthe publisher
adds the year,
author(s)
book and adds the author(s) edition, number of pages and the publisher for the last
--- prints
book
printsandtheadds
the last the author(s)
lastbook
book again
again
- prints the last book again
The
Theresult
resultcould,
could,for
forinstance
instancebe beasasshown
shownbelow:
below:
The result could, for instance be as shown below:
ISBN: 978-1-59059-855-9
ISBN:
Title: 978-1-59059-855-9
Beginning Fedora From Noice to Professional
Title:
Released: Beginning
2007 Fedora From Noice to Professional
Released:
Edition: 2007
1
Edition:
Pages 1519
Pages
Publisher: 519The new Publisher [123]
Publisher:
Authors: The new Publisher [123]
Authors:
[1] Shashank Sharma
[1]
[2] Shashank Sharma
Keir Thomas
[2] Keir Thomas
ISBN: 978-87-400-1676-5
ISBN:
Title: 978-87-400-1676-5
Spansk Vin
Title:
ISBN: Spansk Vin
978-87-400-1676-5
ISBN: 978-87-400-1676-5
Title: Spansk Vin
Title:
Released: Spansk
2014 Vin
Released:
Edition: 2014
1
Edition:
Pages 1335
Pages
Publisher: 335
Politikkens Forlag [200]
Publisher:
Authors: Politikkens Forlag [200]
Authors:
[3] Thomas Rydberg
[3] Thomas Rydberg

PROBLEM 1
PROBLEM
PROBLEM 1
1
A book is characterized by an ISBN, which is an international numbering on 10 or 13
A book
Adigits. is
bookTheis characterized
characterized by
by an
an ISBN,
ISBN, which
which is
is an
an international
international numbering on 10
10 or 13
system was introduced around 1970, and until 2007 itnumbering
was on 10on
digits, or 13
which
digits.
digits. The system
The system was introduced
was introduced around 1970,
aroundby1970, and until 2007 it was on 10 digits, which
and until 2007 it was on 10 digits, which
was divided into four groups separated hyphens:
was divided into four groups separated by hyphens:
was divided into four groups separated by hyphens:
99-999-9999-9
99-999-9999-9

38
38
JAVA 3:
JAVA 3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

wherein the
wherein the last
last group
group always
always consists
consists of
of aa single
single digit
digit (character)
(character) and
and is
is aa control
control character.
character.
The other three groups are interpreted as follows:

1. the
1. the first group
first group is
is aa country
country code
code
2. the
2. the second group
second group isis the
the publisher
publisher identifier
identifier
3. the
3. third group is the title number

The control
The control character
character is
is calculated
calculated by
by the
the modulus
modulus 11
11 method,
method, using
using the
the weights
weights 10,
10, 9,
9, 8,
8,
7, 6,
7, 6, 5,
5, 4,
4, 3,
3, 2
2 and
and 1.
1. This
This is
is best
best explained
explained with
with an
an example.
example. Consider
Consider aa concrete
concrete ISBN:
ISBN:

1-59059-855-5

To determine the
To the check character
character you determine
determine the
the following
following weighted
weighted sum:
sum:

1 5 9 0 5 9 8 5 5
10 9 8 7 6 5 4 3 2

10 + 45 + 72 + 0 + 30 + 45 + 32 + 15 + 10 = 259

39
39
39
JAVA3:3:OBJECT-ORIENTED
JAVA OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

Younow
You now determinesthe
the restby
by dividingby
by 11and
and youget
get
You nowdetermines
determines therest
rest bydividing
dividing by11
11 andyou
you get

259 %% 11
259 11 = 6
259 % 11 == 66

IfIf
If
thisrest
this
Ifthis
restisis0,0,the
thisrest
thecheck
restisis0,0,the
checkdigit
thecheck
digitisis0.0.IfIfthe
checkdigit
theremainder
digitisis0.0.IfIfthe
remainderisis10,
theremainder
10,XXisisthe
remainderisis10,
thecheck
10,XXisisthe
checkcharracter,
thecheck
charracter,and
checkcharracter,
charracter,and
and
and
otherwise,one
otherwise, oneuses
uses11
11minus
minusthetheremainder
remainderasascheck
checkdigit.
digit.As
Asthe
therest
restthis
thistime
timeisis6,6,you
you
otherwise,one
otherwise, oneuses
uses11
11minus
minusthetheremainder
remainderasascheck
checkdigit.
digit.As
Asthe
therest
restthis
thistime
timeisis6,6,you
you
getcheck
get check1111––66==5.5.
getcheck
get check1111––66==5.5.

Eventuallyititwas
Eventually wasrealized
realizedthat
thatbybythe
theyears
yearsthere
therevould
vouldbebetoo
toofew
fewISBN
ISBNnumbers,
numbers,and
and
Eventuallyititwas
Eventually wasrealized
realizedthat
thatbybythe
theyears
yearsthere
therevould
vouldbebetoo
toofew
fewISBN
ISBNnumbers,
numbers,and
and
thereforeititwas
therefore wasdecided
decidedtotochange
changethe
thesystem
systemfrom
from2007.
2007.From
Fromthat
thattime
timethe
thenumbers
numbersare
are
thereforeititwas
therefore wasdecided
decidedtotochange
changethe
thesystem
systemfrom
from2007.
2007.From
Fromthat
thattime
timethe
thenumbers
numbersare
are
precededby
preceded byaa3-digit
3-digitprefix,
prefix,and
andthe
thenumbers
numbersthus
thuscame
cametotoconsist
consistofofanother
anothergroup,
group,that
that
precededby
preceded bya a3-digit
3-digitprefix,
prefix,and
andthe
thenumbers
numbersthus
thuscame
cametotoconsist
consistofofanother
anothergroup,
group,that
that
always
always has
has 3 digits:
has333digits:
alwayshas
always digits:
digits:

999-99-999-9999-9
999-99-999-9999-9
999-99-999-9999-9

So
Sofar
So faronly
onlyof ofthe
thenumbers
numbers978 978and
and979979are
areused
usedas asprefixes,
prefixes,but
butininthe
thefuture
futurethere
therewill
will
Sofar
faronly
onlyofofthethenumbers
numbers978 978and
and979979are
areused
usedasasprefixes,
prefixes,but
butininthe
thefuture
futurethere
therewill
will
probably
probablybe
probably beother
be otheropportunities.
other opportunities.In
opportunities. Inaddition
In additionto
addition totoincreasing
increasingthe
increasing thenumbers
the numberswith
numbers withthis
with thisprefix
this prefixthe
prefix the
the
probably be other opportunities. In addition to increasing the numbers with this prefix the
calculation
calculationof
calculation ofthe
thecontrol
controlcharacter
characterwas
wasalso
alsochanged,
changed,so sothat
thatas
asweights
weightsusing
usingalternating
alternating
calculationofofthe thecontrol
controlcharacter
characterwas
wasalso
alsochanged,
changed,sosothat thatasasweights
weightsusing
usingalternating
alternating
values
values
values ofof1 1 and
and 3,
3,and
and the
thecontrol
control character
character isisthen
then the
themodulus
modulus 10
10 of
of the
the weighted
weighted sum.
sum.
valuesofof11and and3,3,and
andthe thecontrol
controlcharacter
characterisisthen
thenthethemodulus
modulus10 10ofofthe
theweighted
weightedsum.sum.
Again,
Again,it
Again, itis
it isiseasiest
easiestto
easiest toillustere
to illusterethe
illustere thecalculations
the calculationswith
calculations withan
with ananexample.
example.Consider
example. Consider
Consider
Again, it is easiest to illustere the calculations with an example. Consider

978-1-59059-855-9
978-1-59059-855-9
978-1-59059-855-9

Youcalculate
You calculatethe
thefollowing
followingweighted
weightedsum:
sum:
You calculate the following weighted sum:

99
9 77
7 88
8 11
1 55
5 99
9 00
0 55
5 99
9 88
8 55
5 55
5
11
1 33
3 11
1 33
3 11
1 33
3 11
1 33
3 11
1 33
3 11
1 33
3
99 + 21 ++ 88 ++ 33 ++ 55 ++ 27
9 ++ 21
27 + 0 + 15 ++ 99 ++ 24
21 + 8 + 3 + 5 + 27 ++ 00 ++ 15
24 + 5 + 15 == 141
15 + 9 + 24 ++ 55 ++ 15
141
15 = 141

Thenyou
Then youcalculate
calculaterest
restat
atdivision
divisionby
by10:
10:
Thenyou
Then youcalculate
calculaterest
restatatdivision
divisionby
by10:
10:

141%
141 %10
10===111
141%%10
141 10 = 1

IfIf
If thisremainder
this remainderis
thisremainder
Ifthis
is0,0,it
remainderisis0,
itisiscontrol
0,ititis
controlcharacter.
iscontrol
character.Or
controlcharacter.
Oris
character.Or
isthe
thecheck
Orisisthe
checkdigit
thecheck
digit10
checkdigit
10minus
digit10
minusthe
10minus
theremainder,
minusthe
remainder,
theremainder,
remainder,
and
and
and inin this
this case,
case, ititisis 10
10 – – 11== 9.
9.
andininthis
thiscase,
case,ititisis10
10––11==9.9.

Youmust
You mustnow nowreturn
returntotothe
theproject
projectLibrary
Libraryandandthe
theclass
classBook.
Book.Start
Startbybycreating
creatingaaacopy
copy
Youmust
You mustnow nowreturn
returntotothe
theproject
projectLibrary
Libraryandandthe
theclass
classBook.
Book.Start
Startbybycreating
creating acopy
copy
of the
ofofthe
of the project
project Library2
Library2 and
and call
call the
the copy
copy Library3.
Library3. Open
Open the
the copy
copy in NetBeans.
ininNetBeans.
NetBeans. The
The class
class
theproject
projectLibrary2
Library2andandcall
callthe
thecopy
copyLibrary3.
Library3.Open
Openthe thecopy
copyin NetBeans.The
Theclass
class
Book
Book
Book has
has aa static
static method
method isbnOk()
isbnOk() toto validate
validate whether
whether a a string
string is
is a a legal
legal ISBN.
ISBN. The
The control
control
Bookhashasa astatic
staticmethod
methodisbnOk()
isbnOk()totovalidate
validatewhether
whethera astring
stringisisa alegal
legalISBN.
ISBN.TheThecontrol
control
isis trivial,
trivial,
isistrivial, but
but you
you must
must now
now change
change the
the code
code to
to validate
validate an
an ISBN
ISBN folowing
folowing the
the above
above rules.
rules.
trivial,but
butyou
youmust
mustnownowchange
changethe thecode
codetotovalidate
validateananISBN
ISBNfolowing
folowingthetheabove
aboverules.
rules.

40
40
40
40
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

You
Youmust mustalso
alsowrite
writeaatest
testmethod
methodthat thattests
testswhether
whetherthe
thecontrol
controlmethod
methodvalidates
validatescorrectly.
correctly.
You must also write a test method that tests whether the control method validates correctly.
ItIt isis important
important that
that you
you test
test with
with multiple
multiple numbers,
numbers, so
so you
you get
get all
all the
the cases,
cases, and
and itit isis
It is important that you test with multiple numbers, so you get all the cases, and it is
important
important that that you
you also
also test
test illegal
illegal numbers.
numbers.
important that you also test illegal numbers.

2.2 METHODS
2.2 METHODS
2.2 METHODS
In
Inthe
theexplanation
explanationof ofclasses
classesIIhave
havealready
alreadydealt
dealtwith
withmethods,
methods,but butthere
thereare
areaafewfewconcepts
concepts
In the explanation of classes I have already dealt with methods, but there are a few concepts
that
that you
you should
should be be aware
aware of.
of. As
As mentioned,
mentioned, aa methodmethod isis identified
identified by by its
its name
name and and the
the
that you should be aware of. As mentioned, a method is identified by its name and the
parameter
parameter list. list. The
The parameters
parameters that that you
you specify
specify in in the
the method
method definition,
definition, are are called
called the
the
parameter list. The parameters that you specify in the method definition, are called the
formal parameters and they defines the values to be transferred to a
formal parameters and they defines the values to be transferred to a method. The values thatmethod. The values that
formal parameters and they defines the values to be transferred to a method. The values that
you
youtransfer
transferwhenwhenthe themethod
methodisiscalled,
called,isisreferred
referredto toasasthe
theactual
actualparameters.
parameters.AboveAboveIIhavehave
you transfer when the method is called, is referred to as the actual parameters. Above I have
shown
shownhow howto tospecify
specifythat
thataamethod
methodhas hasaavariable
variablenumber
numberof ofparameters,
parameters,which
whichisisreally
reallyjust
just
shown how to specify that a method has a variable number of parameters, which is really just
aa question
question thatthat the
the compiler
compiler creates
creates an an array
array asas the
the actual
actual parameter.
parameter. Methods
Methods parameters
parameters
a question that the compiler creates an array as the actual parameter. Methods parameters
can
can generally be of any type, but you should be aware that primitive types and reference
generally be of any type, but you should be aware that primitive types and reference
can generally be of any type, but you should be aware that primitive types and reference
types
types are treated differently. For primitive types the transmitted values are directly copied,
are treated differently. For primitive types the transmitted values are directly copied,
types are treated differently. For primitive types the transmitted values are directly copied,
and
and that
that is,
is, that
that the
the stack
stack creates
creates aa copy
copy of of the
the parameters
parameters and and the
the actual
actual parameters
parameters are are
and that is, that the stack creates a copy of the parameters and the actual parameters are
copied
copied to to these
these copies.
copies. This
This means
means thatthat ifif aa method
method isis changing
changing the the value
value of of aa parameter
parameter
copied to these copies. This means that if a method is changing the value of a parameter
that
that has a primitive type, then it is the value of the copy on the stack that is changed,and
has a primitive type, then it is the value of the copy on the stack that is changed, and
that has a primitive type, then it is the value of the copy on the stack that is changed, and
after the method is terminated, then the values of the calling
after the method is terminated, then the values of the calling code are unchanged. Wee code are unchanged. Wee
after the method is terminated, then the values of the calling code are unchanged. Wee
therefore
thereforealso alsocall
callaaparameter
parameterof ofaaprimitive
primitivetype typefor
foraavalue
valueparameter.
parameter.IfIfyou youfor forexample
example
therefore also call a parameter of a primitive type for a value parameter. If you for example
consider
consider the the following
following method
method
consider the following method
public ArrayList<Course> getCourses(int year)
public ArrayList<Course> getCourses(int year)

so isis its
so its parameter aa primitive
primitive type, and
and if the method
method changes the
the value ofof year, itit would
would
so is its parameter
parameter a primitive type,
type, and ifif the
the method changes
changes the value
value of year,
year, it would
only have
only have effect in
in the method,
method, but thethe change would
would not have
have effect in
in the code
code where
only have effect
effect in the
the method, but
but the change
change would notnot have effect
effect in the
the code where
where
the method
the method was was called.
called.
the method was called.

Referenceparameters
Reference parameters arein in principletransferred
transferred inthethe sameway, way, wheretherethere onthe
the stack
Reference parametersare are inprinciple
principle transferredin in thesame
same way,where where thereon on thestack
stack
isis created aa copy
created copy of
of the
the parameter
parameter andand the
the current
current value
value isis copied
copied toto this.
is created a copy of the parameter and the current value is copied to this. However, you
this. However,
However, youyou
should be
should be aware ofof what isis being
being created and
and copied. In In the casecase of aa reference
reference parameter
should be aware
aware of what
what is being created
created and copied.
copied. In thethe case of of a reference parameter
parameter
what
what is created on the stack is a reference, and what is copied is the reference to the current
whatisiscreated
createdononthe
thestack
stackisisaareference,
reference,and
andwhat
whatisiscopied
copiedisisthethereference
referenceto tothe
thecurrent
current
object.
object. As an example the following method has a reference parameter:
object. AsAs an
an example
example the
the following
following method
method has
has aa reference
reference parameter:
parameter:
public void add(Course course) throws Exception
public void add(Course course) throws Exception

4141
41
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

If
If the
the method
method creates
creates aa new
new Course
Course object
object and
and sets
sets the
the parameter
parameter course
course to
to refer
refer to
to this
this
object,
object, itit is
is still
still the
the copy
copy onon the
the stack
stack that
that change,
change, and
and the
the calling
calling code
code will
will still
still refer
refer to
to
the old object. If the method not creates a new Course object it could use the
the old object. If the method not creates a new Course object it could use the course object’scourse object’s
methods
methods to to change
change the the object’s
object’s state,
state, as
as an
an example
example itit could
could assign
assign the
the object
object aa new
new score.
score.
If
If you
you do
do thethe object
object that
that is
is changed
changed isis the
the object
object referenced
referenced on
on the
the stack,
stack, that
that is
is the
the same
same
as
as the
the object
object that
that the
the calling
calling code
code refers.
refers.

The
The effect
effect of,
of, that
that aa method
method changes
changes the
the value
value of
of aa parameter,
parameter, is
is thus
thus different
different depending
depending on
on
whether
whether itit is
is aa reference
reference parameter
parameter or
or value
value parameter.
parameter. AA good
good example
example isis aa swap
swap method,
method,
and
and thus
thus aa method
method thatthat must
must reverses
reverses the
the two
two values.
values. Consider
Consider thethe following
following method
method

public static void swap(int a, int b)


{
int t = a;
a = b;
b = t;
}

42
42
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

which
which has two parameters that are value types. IfIf the method isis executed as follows:
which has
has two
two parameters
parameters that
that are
are value
value types.
types. If the
the method
method is executed
executed as
as follows:
follows:

int[] arr = { 2, 3};


int[] arr = { 2, 3};
swap(arr[0], arr[1]);
swap(arr[0], arr[1]);
System.out.println(arr[0] + " " + arr[1]);
System.out.println(arr[0] + " " + arr[1]);

the
the last
the last statement
last statement prints
statement prints
prints

2 3
2 3

and the
and the two
the two numbers
two numbers are
numbers are not
are not reversed.
not reversed. The
reversed. The first
The first statement
first statement creates
statement creates an
creates an array:
an array:
array:
and

When
When thethe next
the next statement
next statement calls
statement calls the
calls the method
the method swap(),
method swap(), and
swap(), and the
and the variables
the variables arr[0]
variables arr[0] and
arr[0] and arr[1]
and arr[1] are
arr[1] are
are
When
transferred as
transferred as the
as the actual
the actual parameters.
actual parameters.
parameters. The The method
The method swap()
method swap() has
swap() has two
has two parameters
two parameters
parameters andand a local
and aa local
local
transferred
variable, and
variable, and has
and has therefore
has therefore three
therefore three fields
three fields that
fields that are
that are allocated
are allocated on
allocated on the
on the stack,
the stack, and
stack, and the
and the values
the values of
values of the
of the
the
variable,
actual parameters
actual parameters
parameters are are copied
are copied to
copied to this:
to this:
this:
actual

The swap()
The swap() method
swap() method works
method works
works in in that
that itit
in that copies
it copies
copies thethe value
the value of
value of the
of the parameter
parameter aaa to
the parameter to the
to the local
the local variable
local variable
variable
The
t, and then copy the value of b to a. Finally the value of t is copied to b, and then the
t,t, and
and then
then copy
copy the
the value
value ofof bb to
to a. a. Finally
Finally the
the value
value of
of tt isis copied
copied toto b,
b, and
and then
then the
the
contents
contents of of the
of the stack
the stack is as
stack isis as shown
as shown below.
shown below.
below. ThisThis means
This means that
means that the
that the two
the two values
two values are
values are reversed,
are reversed, but
but itit
reversed, but it
contents
happened
happened on on the
on the stack,
the stack,
stack, andand after
and after the
after the method
the method is terminated
method isis terminated the
terminated the three
the three elements
three elements
elements are are removed
are removed
removed
happened
from
from thethe stack,
the stack, and
stack, and the
and the changes
the changes
changes are are lost.
are lost. This
lost. This means
This means that
means that the
that the array
the array in
array in the
in the calling
the calling code
calling code
code
from
is unchanged.
isis unchanged.
unchanged.

43
43
43
JAVA
JAVA3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

The
Thequestion
The questionisis
question ishow,
how,inin
how, inJava
Javatoto
Java towrite
writeaaaswap()
write swap()method
swap() methodtoto
method toswap
swaptwo
swap twoprimitive
two primitivevalues,
primitive values,and
values, and
and
ititcan
it cannot
can notactually
not actually be
actually be done
be done directly.
done directly. It
directly. It is
It is necessary
is necessary to
necessary toembed
to embed the
embed the values
the values in
values ina an
in aa anobject
objectofof
an object of
another
anotherreference
another reference type.
reference type. One
type. One solution
One solution would
solution would be:
would be:
be:

public static
public static void
void swap(int[]
swap(int[] a)
a)
{
{
int t
int t == a[0];
a[0];
a[0] = a[1];
a[0] = a[1];
a[1] =
a[1] = t;
t;
}
}

Here,
Here,
Here,the theparameter
the parameterisis
parameter isananarray,
an array,which
array, whichisis
which isaaareference
referencetype.
reference type.The
type. Thealgorithm
The algorithmisis
algorithm isthe
thesame,
the same,and
same, and
and
itit
itisis clear
isclear the
clearthe method
themethod reverses
methodreverses the
reversesthe values
valuesofof
thevalues a[0]
ofa[0] and
a[0]and a[1],
anda[1], but
butitit
a[1],but itisis not
isnot values
notvalues on
valueson the
onthe stack.
thestack.
stack.
Consider
Consider the
the following
following statements
statements where
where arr
arr is
is
Consider the following statements where arr is as above: as
as above:
above:

swap(arr);
swap(arr);
System.out.println(arr[0]
System.out.println(arr[0] +
+ "
" "
" +
+ arr[1]);
arr[1]);

If
If they
they are
are performed
performed you
you get
get the
the results
results
If they are performed you get the results
3
322
32
and
and the
the numbers
numbers are
are therefore
therefore reversed.
reversed. When
When the
the method
method swap()
swap() isis called,
called, there
there is
is this
this
and the
time numbers
only one are
value therefore
to copy toreversed.
the When
stack, the
which is method
the swap()
reference to is
thecalled,
array there
arr: is this
time only one value to copy to the stack, which is the reference to the array arr:
time only one value to copy to the stack, which is the reference to the array arr:

There
There is
is still
still created
created aa local
local variable,
variable, but
but when
when the
the method
method is
is performed,
performed, it
it is
is the
the array
array
There is
referencestill
on created
the a
stack local
the variable,
swap() but
method when
works the
on: method is performed, it is the array
reference on the stack the swap() method works on:
reference on the stack the swap() method works on:

The
The result
result of
of all
all this
this is
is that
that in
in practice
practice it
it may
may be
be important
important toto have
have in
in mind,
mind, where
where aa
The result of
parameter is all this is
is aa primitive that
primitive type in
type orpractice it may
or aa reference be
reference type, important
type, because to have
because reference in mind,
reference types
types can where
result ain
can result in
parameter
parameter
undesirableis a primitive type or a reference type, because reference types can result in
undesirable side
side effects.
effects.
undesirable side effects.

44
44
44
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

Another
Another important
Another important thing
important thing about
thing about reference
about reference types
types isis
reference types that
is that what
what isis
that what placed
is placed on
placed on the
on the stack
stack isis
the stack always
is always
always
a reference.
aa reference. Above
reference. Above I have
Above II have shown
have shown a method
shown aa method that
method that prints
that prints a course:
prints aa course:
course:

private
private static
static void
void print(Course
print(Course cource)
cource) throws
throws Exception
Exception
{
{
}
}

IfIf
If the
the method
the method isis
method is executed
executed
executed

print(c1);
print(c1);

itit
it isis
is aaa reference
reference to
reference to aaa Course
to Course object
Course object that
object that isis
that is placed
placed on
placed on the
on the stack
the stack and
stack and not
and not aaa Course
not Course object.
Course object. ItIt
object. It isis
is
important
important for
for a
a Course
Course object
object fills
fills much
much more
more than
than a
a reference.
reference. It
It is
important for a Course object fills much more than a reference. It is thus highly effectiveis thus
thus highly
highly effective
effective
to
to transfer
to transfer objects
transfer objects as
objects as parameters
as parameters to
parameters to methods.
to methods.
methods.

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

45
45
45
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

Methods
Methodshave havea atype
typeororthey
theyare
arevoid.
void.The
Thefact
factthat
thata amethod
methodisisvoid
voidmeans
meansthatthatititdoes
does
not have a value, and it is therefore not required to have a return statement.
not have a value, and it is therefore not required to have a return statement. As an example As an example
you
youhavehavethe themethod
methodadd()add()ininthe
theclass
classStudent.
Student.AAvoidvoidmethod
methodmay maywell
wellhave
haveananempty
empty
return
return statement, which then has the effect that the method is terminated. If a methodhas
statement, which then has the effect that the method is terminated. If a method has
a atype,
type,ititmust
musthave
havea areturn
returnstatement
statementthatthatreturns
returnsa avalue
valueofofthe
thesame
sametype
typeasasthe
themethod’s
method’s
type.
type. It is important to note that the method can only return one value, but thetype
It is important to note that the method can only return one value, but the typeofof
this
thisvalue
valueininturnturncan
canbebeanything,
anything,including
includinga aclass
classtype
typeororananarray.
array.As
Asananexample,
example,the the
method returns getCourses() in the class Student return an ArrayList<Course>,
method returns getCourses() in the class Student return an ArrayList<Course>, and precise, and precise,
ititisisa areference
referencetotosuch
suchananobject.
object.

As
Ascan
canbebeseen
seenfrom
fromthetheabove,
above,a amethod’s
method’sparameters
parametersare
arecreated
createdwhen
whenthethemethod
methodisis
called
calledand
andinitialized
initializedbybythe
thecalling
callingcode.
code.The
Theparameters
parametersare areremoved
removedagain
againwhen
whenthe the
method
methodterminates,
terminates,andandthey
theylive
liveonly
onlywhile
whilethethemethod
methodexecutes
executesand
andthey
theycancanonly
onlybebe
used
usedororreferenced
referenced from
from the
the method
method itself.
itself.Wee
Wee say
say that
that the
the parameters
parameters scope
scope are
are the
the
method’s statements.
method’s statements.

The
Thesame
sameapplies
appliestotothethevariables
variablesasasa amethod
methodmight
mightcreate.
create.They
Theyare arecalled
calledlocal
localvariables.
variables.
They
They are created when the method is called, and removed again when it terminates.Their
are created when the method is called, and removed again when it terminates. Their
scope
scope is also limited to the method’s statements. A local variable can be created anywhereinin
is also limited to the method’s statements. A local variable can be created anywhere
the
themethod,
method,but butthey
theyareareallallcreated,
created,however
howeverwhen
whenthethemethod
methodisiscalled,
called,but
butififa avariable
variable
isisreferenced
referencedby bya astatement
statementbeforebeforeititisisdefined,
defined,the
thecompiler
compilerfails.
fails.InInconclusion,
conclusion,a amethod
method
can refer to
can refer to

1.
1.instance
instancevariables
variablesininthe
themethods
methodsclass
class
2.
2.parameters
parameters
3.
3. localvariables
local variables

wherein,
wherein,the
thelast
lasttwo
twohave
havetheir
theirscope
scopelimited
limitedtotothe
themethod
methoditself.
itself.ByBycontrast,
contrast,the
thescope
scopeofof
ananinstance
instancevariable
variableisislimited
limitedtotothe
theobject,
object,sosothat
thatthe
thevariable
variablelive
liveasaslong
longasasthe
theobject
objectdoes.
does.

2.3 OBJECTS
2.3 OBJECTS
Seen
Seenfrom
fromthe theprogrammer
programmerananapplication
applicationconsist
consistofofa afamily
familyofofclasses,
classes,but
butfrom
fromthe
therunning
running
program it consists of a family of objects that are created on basis of the program’s
program it consists of a family of objects that are created on basis of the program’s classes. classes.
AAclass
classisisa adefinition
definitionofofananobject
objectininthe
theform
formofofinstance
instancevariables
variablesthatthatdefine
definewhich
whichdata
data
the
theobject
objectmustmustconsist
consistof,
of,asaswell
wellasasmethods
methodsdefines
defineswhat whatone
onecancanbebedone
donewith
withananobject.
object.
IfIfyou have a class such as Subject, you can define a variable whose type
you have a class such as Subject, you can define a variable whose type is Subject: is Subject:

Subject s1;

46
46
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes

s1s1isisa avariable
variableasasallallthe
theother
othervariables,
variables,butbutitithas
hasnot
not(yet)
(yet)a avalue.
value.The
Thevariable
variablecan
cancontain
contain
a areference
referencethatthatyou
youcan canthink
thinkofofasasa apointer
pointerthatthatcan
canpoint
pointtoto(refer
(referto)
to)ananobject.
object.IfIfthe
the
variable
variablenot notrefer
refertotoananobject,
object,itsitsvalue
valueisisnull,
null,which
whichmerely
merelyindicates
indicatesthat
thatitithas
hasno
novalue.
value.
Objects are created with new as
Objects are created with new as follows: follows:

s1 = new Subject("MAT7", "Matematics 7, Algebra");

That
Thatisisnew
newfollowed
followedby bythe
theclass
classname
nameand anda aparameter
parameterlistlistthat
thatmatches
matchesthe theparameters
parametersofof
a aconstructor.
constructor.InInthis
thiscase,
case,the
theclass
classhas
hasa aconstructor
constructorthat
thattakes
takestwo
twoString
Stringparameters,
parameters,and
and
ananobject
objectcancanbebecreated,
created,asasshown
shownabove.
above.Sometimes
Sometimeswee weesay
saythat
thatthe
thestatment
statmentinstantiates
instantiates
ananobject.
object.This
Thismeans
meansthat
thatwhen
whenthe thevariable
variables1s1isisdefined,
defined,there
thereisisa avariable
variablecreated
createdonon
the
thestack:
stack:

and
andafter
afterthe
theobject
objectisiscreated,
created,the
thepicture
pictureisisthe
thefollowing:
following:

When
Whenananobject
objectisiscreated,
created,thetheclass’s
class’sconstructor
constructorisisperformed,
performed,and andififthere
thereare
areseveral,
several,ititisis
the
theconstructor
constructorwhose
whoseparameters
parametersmatch
matchthetheparameters
parameterstransferred
transferredwith
withnew.
new.This
Thismeans
means
that
thatthe
thespace
spaceallocated
allocatedtotothe theobject’s
object’sinstance
instancevariables
variablestypical
typicalare
areinitialized
initializedwith
withvalues
values
ininthe
theconstructor.
constructor.InInfact,
fact,the
theabove
aboveimage
imageisisnot
notquite
quitecorrect,
correct,for
fora aString
Stringisisananobject,
object,
and
andthe
thetwo
twoinstance
instancevariables
variablesshould
shouldtherefore
thereforebebedesigned
designedasaspointers
pointerstotoString
Stringobjects.
objects.
I Ihave
havenot
notdone
donethatthatpartly
partlybecause
becausestrings
stringsininananapplication
applicationininmany
manyways
waysareareused
usedasasifif
they
theywere
wereprimitive
primitivevalues,
values,and andpartly
partlybecause
becausethethedrawing
drawingbetter
bettermatches
matchesthe theway
wayyouyou
think
thinkofofa aSubject
Subjectobject.
object.

4747
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

The object is created on the heap, which is a memory area in which the runtime system
can continuously create new objects. When creating an object, the heap manager allocates
space for object’s variables, then the constructor is executed. The object then lives as long
there is a reference to it, but when it is no longer the case, either because the variable that
references the object is removed, or manually is set to null, so the object is removed by the
garbage collector, and the memory that the object applied, is released and can be used for
new objects. The garbage collector is a program that runs in the background and at intervals
remove the objects that no longer have references.

2.4 VISIBILITY
Visibility tells where a class or its members may be used. As for classes, it’s simple, when
a class is defined either public or else you specify no visibility. A public class can be used
anywhere, and any other class can refer to a public class. However, if you do not specify
any visibility, the class can only be used by classes in the same package.

48
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

Regarding the classes members that can be variables, constructors and methods, there are
four possibilities:

-- private
-- public
-- protected
-- no visibility

The meaning of the first two has already been explained and protected is a between thing
where a protected member can be referenced from other classes in the same package and
from derived classes. I have previously briefly explained inheritance, including derived
classes, but the topic is described in more detail in a later chapter in this book, where I
will also demonstrate the use of protected. Finally, there is the possibility of not indicating
any visibility which means that a member can be referenced only within the same package.

It is the programmer of a class that defines visibilty for the class’s members. In principle,
one could make everything public, but it would also increase the risk that a variable or
method was used in an unintended way. Therefore, you should open as little up for the
class’s members as possible. As mentioned earlier, do you usually defines all variables private,
and so equips a class with the necessary public methods, and for the sake of derived classes
you can also be considered to define methods and exceptionally variables as protected.

2.5 STATICAL MEMBERS


Both variables and methods can be static. A static variable is a variable that is shared between
all objects of a class. When creating an object of a class on the heap, there is not allocated
place for static variables, but they are created somewhere in memory where everyone has
access to them, and if they have public visibility, it is not only objects of the class, which
have access to them.

As an example of using a static variable, the class Student has an id, which is a unique number
that identifies a student. When you create objects, it is often necessary that these objects
can be identified by a unique key, and to ensure uniqueness, this number is automatically
incremented by 1 each time a student is created. It is possible because the class has a
static variable that contains the number of the last student created. You must note that it
is necessary that this variable is static, since it would otherwise be created each time, you
creates a Student object. It is, in this way of identifying objects using an auto-generated
number, a technique which is sometimes used in databases. In this context, the solution is
a little searched when the number is not saved anywhere and students will then possibly
get new numbers the next time the program is excuted, and the purpose is indeed only to
show an example of a static variable.

49
JAVA
JAVA3:
JAVA 3:OBJECT-ORIENTED
3: OBJECT-ORIENTEDPROGRAMMING
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes
Classes

There
There are
There are many
are many other
many other examples
other examples of
examples of static
of static variables,
static variables, and
variables, and as
and asas an
an example
an example III can
example can mention
can mention the
mention the
the
class
class Cube
class Cube from
Cube from the
from the book
the book Java
book Java 1,
Java 1, which
1, which had
which had aaa random
had random number
random number generator,
number generator, which
generator, which was
which was also
was also
also
defined
definedas
defined asasaaastatic
staticvariable.
static variable.There
variable. Therewere
There werethe
were thereason
the reasonthat
reason thatall
that allCube
all Cubeobjects
Cube objectsshould
objects shoulduse
should usethe
use thesame
the same
same
random number
randomnumber
random generator
numbergenerator when
generatorwhen it is initialized
whenititisisinitialized by
initializedby reading
byreading
readingthe the hardware
thehardware clock.
hardwareclock. If each
clock.IfIfeach Cube
eachCube
Cube
object
objecthad
object hadits
had itsown
its ownrandom
own randomnumber
random numbergenerator,
number generator,these
generator, thesewould
these wouldpossibly
would possiblybe
possibly beinitialized
be initializedwith
initialized withthe
with the
the
same
samevalue,
same value,thereby
value, therebygenerating
thereby generatingthe
generating thesame
the samesequence
same sequenceof
sequence ofrandom
of randomnumbers.
random numbers.
numbers.

Classes
Classes can
Classes can also
can also have
also have static
have static methods,
static methods, and
methods, and in
and in fact
in fact III have
fact have already
have already used
already used many
used many examples.
many examples. As
examples. As
As
an
anexample
an examplethe
example themethod
the methodstudentOk()
method studentOk()in
studentOk() inthe
in theclass
the classStudent.
class Student.When
Student. Whenaaaclass
When classhas
class hasaaastatic
has staticmethod,
static method,
method,
it
itit can
can be
can be used
be used without
used without having
without having an
having an object
an object as
object asas the
the method
the method can
method can be
can be referred
be referred to
referred to with
to with the
with the name
the name
name
of
ofthe
of theclass:
the class:
class:

if (Student.student("poul.klausen@mail.dk",
if (Student.student("poul.klausen@mail.dk", "Poul
"Poul Klausen")
Klausen")
{{
}}

In
In general
In general is
general isis aaa static
static method
static method written
method written as
written asas other
other methods,
other methods, and
methods, and can
and can have
can have both
have both parameters
both parameters
parameters
and have
and have
and a return
have aa return value,
return value, and
value, and the
and the same
the same rules
same rules apply
rules apply regarding
apply regarding visibility,
regarding visibility, but
visibility, but a static
staticmethod
but aa static method
method
can
can not
can not reference
not reference instance
reference instance variables
instance variables ––– it
variables itit is
isis not
not associated
not associated with
associated with aaa specific
with specific object.
specific object.You
object. You must
You must
must
specifically
specificallynote
specifically notethat
note thatwithin
that withinthe
within theclass
the classwhere
class wherethe
where themethod
the methodis
method isisdefined,
defined,it
defined, ititcan
canbe
can bereferenced
be referencedin
referenced in
in
the same
the same
the way
same way as any
way asas any other
any other of
other of the
of the class’s
the class’s methods.
class’s methods.
methods.

A
AA class
class may
class may also
may also have
also have aaa static
have static initialize
static initialize block
initialize block that
block that can
that can be
can be used
be used to
used to initialize
to initialize static
initialize static variables,
static variables,
variables,
for
forexample
for examplehas
example hasthe
has theclass
the classStudent
class the
Student the
Student following
the following block:
following block:
block:

static
static
{{
nummer == 1000;
nummer 1000;
}}

because
because by by one
one reason
reason or or another
another II wants
wants that
that the
the first
first student
student must
must have
have the
the key
key 1001.
1001.
In
In this
this case
case there
there isis no
no justification
justification for
for the
the block,
block, then
then youyou asas well
well could
could initialized
initialized the
the
variable
variable directly,
directly, butbut inin other
other contexts
contexts itit may
may be be important
important toto initialize
initialize static
static variables
variables
otherwise
otherwisethan thanby bysimple
simpleassignment,
assignment,forforexample
exampleby byreading
readingthethedata
dataininaafile.
file.You
Youshould
should
also
alsonote
notethat
thatthe
thesyntax
syntaxisissimple,
simple,and
andthat
thataaclass
classcan
canhave
haveall
allthethestatic
staticinitialize
initializeblocks,
blocks,
asas you
you wish.
wish. IfIf there
there are
are more
more the
the runtime
runtime system
system guarantees,
guarantees, that
that they
they are
are performed
performed inin
the
theorder
orderininwhich
whichthey theyappear
appearininthe
thecode.
code.

50
50
50
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

If you considers a main class, NetBeans creates the following class:

package students;

public class Students


{
public static void main(String[] args)
{
}
}

which alone has a method with the name main(). When the program is executed, the
runtime system search for a method with this name and where appropriate executes the
method. As the runtime system does not create an object of the class Students, the method
must be static. If the main() method wants to execute a method in the same class, it must
generally be static, and the same applies if you in a static method in the main class refers
to the variables in the class:

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

51
51
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

package students;

import java.util.*;

public class Students


{
private static Random rand = new Random();

public static void main(String[] args)


{
test00();
}

private static void test00()


{
System.out.println(rand.nextDouble());
}
}

That’s
That’s why
why II until
until this
this place
place has has always
always defined
defined members
members in
in the
the main
main class
class as
as static.
static. IfIf you
you
do
do not
not want
want that
that –– and
and itit isis not
not necessary
necessary –– you
you must
must write
write something
something like
like the
the following:
following:

package students;

import java.util.*;

public class Students


{
private Random rand = new Random();

public static void main(String[] args)


{
Students obj = new Students();
obj.test00();
}

private void test00()


{
System.out.println(rand.nextDouble());
}
}

52
52
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes

This
Thismeans
meansthat
thatininmain()
main()method
methodcreates
createsananobject
objectofofthe
theclass
classitself,
itself,and
andusing
usingthis
thisobject
object
ititcan
canthen
thenrefer
refertotonon-static
non-staticmethods
methodsthatthatyou
youcan
canuseuseordinary
ordinaryinstance
instancevariables.
variables.There
There
are
arerarely
rarelyany
anygood
goodreason
reasonfor
forthis
thisstep,
step,and
andtypically
typicallythe
themain-class
main-classwill
willconsists
consistsonly
onlyofof
static
staticvariables
variablesand
andstatic
staticmethods.
methods.

2.6
2.6 THE
THECURRENCYPROGRAM
CURRENCYPROGRAM
I Iwill
willconclude
concludethisthischapter
chapteron onclasses
classeswith
withaaprogram
programthat
thatcan
canconvert
convertan anamount
amountininoneone
currency
currencytotoan anamount
amountininanother
anothercurrency.
currency.The
Theprogram
programconsists
consistsofofseveral
severalclasses,
classes,but
but
basically
basicallythere
thereisisnothing
nothingnew newregarding
regardingclasses,
classes,but
butthe
theprogram
programintroduces
introducesthetheconcept
conceptofof
design
designpatterns
patternsandandininrespect
respectofoftwo
twosimple
simplepatterns.
patterns.AAdesign
designpattern
patternisisaacertain
certainway
waytoto
solve
solvecertain
certainproblems
problemsthatthatare
aregeneral
generalininnature
natureand
andappearing
appearingininmany
manydifferent
differentsituations.
situations.
ItItisisnatural
naturaltotoseek
seekaastandard
standardforforhow
howtotouseuseproven
provenmethods
methodsforforsolving
solvingsuch
suchaaproblem,
problem,
and
andthat’s
that’swhat
whataadesign
designpattern
patternis.is.InInthe
theexample
exampleI Ipresents
presentsthe
thepatterns
patterns

1.
1.aasingleton
singleton
2.
2.an
aniterator
iteratorpattern
pattern

The
Theprogram
programhas
hasaasimple
simplemodel
modelclass,
class,which
whichisiscalled
calledCurrency
Currencythat
thatrepresents
representsaacurrency
currency
with
withthree
threeproperties:
properties:

--- currency
currencycode
code(that
(thatisisaacode
codeon
on33characters)
characters)
--- currency
currencyname
name(that
(thatmust
mustnot
notbe
beblank)
blank)
--- currency
currencyrate
ratethat
thatshould
shouldbe beaanon-negative
non-negativenumber
number

The
Thecode
codeofofthe
theclass
classisisshown
shownbelow
belowincl.
incl.the
themost
mostimportant
importantcomments
commentsand
anddo
donot
notrequire
require
further
furtherexplanation:
explanation:

package currencyprogram;

/**
* Class that represents a currency when the currency rate is relative to
* Danish crowns.
*/
public class Currency
{
private String code; // currency code
private String name; // currency name
private double rate; // currency rate

5353
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

public Currency(String code, String name) throws Exception


{
this(code, name, 0);
}

public Currency(String code, String name, double rate) throws Exception


{
if (!valutaOk(code, name, rate)) throw new Exception("Illegal currency");
this.code = code;
this.name = name;
this.rate = rate;
}

public String getCode()


{
return code;
}

public String getName()


{
return name;
}

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

54
54
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

public void setName(String name) throws Exception


{
if (name == null || name.length() == 0)
throw new Exception("Illegal currency name");
this.name = name;
}

public double getRate()


{
return rate;
}

public void setRate(double rate) throws Exception


{
if (rate < 0) throw new Exception("Illegal currency rate");
this.rate = rate;
}

public String toString()


{
return code + ": " + name;
}

/**
* Validates the values of a currency where the code must be three characters,
* the name must not be blank and the currency rate must non-negative.
* @param code Currency code
* @param name Currency name
* @param rate Currency rate
* @return true, If the three values results in a legal currency, else false.
*/
public static boolean valutaOk(String code, String name, double rate)
{
return code != null && code.length() == 3 && name != null && name.length() > 0
&& rate >= 0;
}
}

You should note that the above class is a typical model class that describes an object in the
You should note that the above class is a typical model class that describes an object in the
program’s problem area.
program’s problem area.

55
55
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Classes
Classes

THE
THE SINGLETON
SINGLETON PATTERN
PATTERN

The
The next
next class
class isis called
called CurrencyTable,
CurrencyTable, andand isis aa class
class that
that defines
defines the
the Currency
Currency objects
objects that
that
the
the program
program knows
knows and and hashas to
to work
work with.
with. The
The program
program must
must have
have anan object
object of
of the
the type
type
CurrencyTable,
CurrencyTable, and
and itit isis an
an object,
object, which
which in
in principle
principle should
should always
always be
be there
there and
and be
be available
available
no
no matter
matter where
where in in the
the program
program you you are.
are. Since
Since itit isis very
very often
often that
that aa situation
situation arises
arises that
that
aa program
program must
must use use anan object
object of
of aa particular
particular type,
type, and
and you
you want
want toto ensure
ensure

1.
1. the
the object
object isis always
always there,
there, without
without explicitly
explicitly being
being created
created
2.
2. the
the object
object isis available
available to
to all
all other
other objects
objects in
in the
the program
program
3.
3. there
there certainly
certainly exists
exists only
only one
one object
object of
of that
that type
type

there
there has
has been
been defined
defined aa particular
particular design
design pattern
pattern for
for how
how the
the class
class to
to such
such an
an object
object should
should
be
be written.
written. This
This design
design pattern
pattern isis called
called aa singleton.
singleton. The
The class
class can
can be
be written
written as
as follows:
follows:

package currencyprogram;

import java.util.*;

/**
* Class which represents a currency table. The class is implemented as a
* singleton.
* Data for the currencies is laid out in a table at the end of the code.
*/
public class CurrencyTable implements Iterable<Currency>
{
private static CurrencyTable instance = null; // an instance of the class

private ArrayList<Currency> table = new ArrayList(); // ArrayList to currencies

// Private constructor to ensure that the class can not be instantiated


// from other classes.
private CurrencyTable()
{
init();
}

public static CurrencyTable getInstance()


{
if (instance == null)
{
synchronized (CurrencyTable.class)
{
if (instance == null) instance = new CurrencyTable();

56
56
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

}
}
return instance;
}

public Currency getCurrency(String code) throws Exception


{
for (Currency c : table) if (c.getCode().equals(code)) return c;
throw new Exception("Illegal currency");
}

public Iterator<Currency> iterator()


{
return table.iterator();
}

/**
* Updating the currency table with a currency. If this currency is already
* in the table the name and rate are updated. Otherwise, add a new currency
* to the table.
* @param currency The currency
* @return true, if the table was updated correctly
*/

57

57
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

public boolean update(Currency currency)


{
for (Currency c : this)
if (c.getCode().equals(currency.getCode()))
{
try
{
c.setName(currency.getName());
c.setRate(currency.getRate());
return true;
}
catch (Exception ex)
{
return false;
}
}
table.add(currency);
return true;
}

private void init()


{
for (String line : rates)
{
StringTokenizer tk = new StringTokenizer(line, ";");
if (tk.countTokens() == 3)
{
try
{
String name = tk.nextToken();
String code = tk.nextToken();
double rate = Double.parseDouble(tk.nextToken());
table.add(new Currency(code, name, rate));
}
catch (Exception ex)
{
System.out.println(ex.getMessage() + "\n" + line);
}
}
else System.out.println("Error: " + line);
}
}

private static String[] rates =


{
"Danske kroner;DKK;100.00",
"Euro;EUR;746.00",

58
58
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

"Amerikanske dollar;USD;674.44",
"Britiske pund;GBP;1034.10",
"Svenske kroner;SEK;79.31",
"Norske kroner;NOK;79.68",
"Schweiziske franc;CHF;685.66",
"Japanske yen;JPY;5.6065",
"Australske dollar;AUD;487.61",
"Brasilianske real;BRL;171.98",
"Bulgarske lev;BGN;381.43",
"Canadiske dollar;CAD;510.19",
"Filippinske peso;PHP;14.40",
"Hongkong dollar;HKD;87.02",
"Indiske rupee;INR;10.38",
"Indonesiske rupiah;IDR;0.0494",
"Israelske shekel;ILS;174.48",
"Kinesiske Yuan renminbi;CNY;106.17",
"Kroatiske kuna;HRK;97.87",
"Malaysiske ringgit;MYR;157.78",
"Mexicanske peso;MXN;40.65",
"New Zealandske dollar;NZD;458.77",
"Polske zloty;PLN;173.82",
"Rumænske lei;RON;168.13",
"Russiske rubel;RUB;10.42",
"Singapore dollar;SGD;483.72",
"Sydafrikanske rand;ZAR;49.08",
"Sydkoreanske won;KRW;0.5933",
"Thailandske baht;THB;19.00",
"Tjekkiske koruna;CZK;27.53",
"Tyrkiske lira;TRY;231.78",
"Ungarske forint;HUF;2.385"
};
}

This
This time
time there
there are
are more
more details
details to
to note.
note. The
The class
class has
has an
an instance
instance variable,
variable, which
which isis called
called
table
table and is an ArrayList<Currency> and should be used for the Currency objects. The
and is an ArrayList<Currency> and should be used for the Currency objects. The
class
class also has a static variable named instance that is initialized to null. This variable is an
also has a static variable named instance that is initialized to null. This variable is an
important part of the singleton pattern. The class has a constructor, but
important part of the singleton pattern. The class has a constructor, but you should note you should note
that
that the
the constructor
constructor isis defined
defined private,
private, and
and when
when the
the class
class has
has no
no other
other constructors,
constructors, itit
means
means that
that other
other objects
objects can
can not
not instantiate
instantiate objects
objects ofof this
this class.
class. It
It isis another
another important
important
part of the singleton pattern.
part of the singleton pattern.

The
The ArrayList
ArrayList must
must bebe initialized
initialized with
with Currency
Currency objects,
objects, and
and itit requires
requires currency
currency data
data in
in the
the
form of a rate list. It can, for example be found
form of a rate list. It can, for example be found on on

http://www.nationalbanken.dk/da/statistik/valutakurs/Sider/Default.aspx
http://www.nationalbanken.dk/da/statistik/valutakurs/Sider/Default.aspx

59
59
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

and an example is laid out in the bottom of the class as an array of strings. The method
init() uses this the array to create Currency objects, and the init() method is called from
the private constructor. It is of course a little pseudo, since it is not current exchange rates,
but if you wants you can update the table.

The class has a static method called getInstance(), which returns the static variable instance.
It is the last and perhaps most important part of the singleton pattern. The method works
in that way that it tests whether the variable instance is null. If so, it creates a CurrencyTable
object and assigns the result to instance. It is possible, for the method getInstance() is a
member of the class CurrencyTable and can therefore refer to the private constructor. Finally
the method returns the variable instance, and thus a reference to a CurrencyTable object.
Other objects can refer to the CurrencyTable object by this reference, and when the object
can not be created otherwise, there is exactly one object referenced. You should note that
the line that instantiates the object is placed in a synchronized block. Preliminary simply
accept it, but it is important for programs that creates multiple threads.

60
JAVA
JAVA3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING Classes
PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

THE
THEITERATOR
ITERATORPATTERN
PATTERN
THE
THE ITERATOR
ITERATOR PATTERN
PATTERN
InIn
In terms
termsofof thetheother
othermethods
methodsinin the
theclass,
class,there
thereisis nothing
nothingtoto explain
explainexcept
exceptthe
themethod
method
In terms
terms ofof the
the other
other methods
methods in in the
the class,
class, there
there isis nothing
nothing to to explain
explain except
except the
the method
method
iterator().
iterator().
iterator(). The
The
The class
class
classisis
isanan
anexample
example
example ofof
ofaaacollection
collection
collection and,
and,
and, inin
inthis
this
this case
case
case aaacollection
collection
collection ofof
of Currency
Currency
Currency
iterator(). The class is an example of a collection and, in this case a collection of Currency
objects.
objects.
objects. That
Thatkindkindofof collections
collectionswith
withobjects
objectsofofaacertain
certainkind kindoccur
occurveryveryoften
ofteninin practice.
practice.
objects. That
That kind
kind of
of collections
collections with
with objects
objects of
of aa certain
certain kindkind occur
occur very
very often
often in
in practice.
practice.
One
One
One ofof
of the
the
theoperations
operations
operations that
that
thatalmost
almost
almost always
always
always isis
isneeded
needed
needed isis
isbeing
being
being able
able
able toto
toiterate
iterate
iterate over
over
overthe
the
the collection
collection
collection
One of the operations that almost always is needed is being able to iterate over the collection
with
with
with aaloop.
loop.This
Thisrequires
requiresaccess
accesstoto the
theobjects
objectsand
anditit isisoften
oftenresolved
resolvedby bymeans
meansofof aapattern
pattern
with aa loop.
loop. This
This requires
requires access
access to
to the
the objects
objects and
and it it is
is often
often resolved
resolved by by means
means of
of aa pattern
pattern
which
which
which we
we
we call
call
call the
the
theiterator
iterator
iterator pattern.
pattern.
pattern. The
The
The class
class
class CurrencyTable
CurrencyTable
CurrencyTable implements
implements
implements this
this
thispattern
pattern
pattern asas
as follows:
follows:
follows:
which we call the iterator pattern. The class CurrencyTable implements this pattern as follows:
The
The
The class
classimplements
implementsan
aninterface,
interface,which
whichhere
hereisiscalled
calledIterable<Currency>.
Iterable<Currency>.This
Thismeans
meansthat
that
The class
class implements
implements an
an interface,
interface, which
which here
here is
is called
called Iterable<Currency>.
Iterable<Currency>. This
This means
means that
that
the
the
theclass
class
class must
must
mustimplements
implements
implements a method
aa method
methodwith
with
withthe
the
the following
following
following signature:
signature:
signature:
the class must implements a method with the following signature:
public
public Iterator<Currency> iterator()
public Iterator<Currency>
Iterator<Currency> iterator()
iterator()

where
where
where Iterator<Currency>isis
Iterator<Currency> aninterface
an interfacethat
thatdefines
definesmethods,
methods,soso youcan
you caniterate
iterateover
overthe
the
where Iterator<Currency>
Iterator<Currency> is is an
an interface
interface that
that defines
defines methods,
methods, so so you
you can
can iterate
iterate over
over the
the
collection
collection
collection ofof
of Currency
Currency
Currency objects.
objects.
objects. InIn
In this
this
this case
case
case itit
it isis
is particularly
particularly
particularly simple,
simple,
simple, since
since
since an
an
an ArrayList
ArrayList
ArrayList has
has
has
collection of Currency objects. In this case it is particularly simple, since an ArrayList has
such
such
such aniterator,
an iterator,and
andthe
themethod
methodcan cantherefore
thereforebe bewritten
writtenasas follows:
follows:
such an
an iterator,
iterator, and
and the
the method
method can can therefore
therefore be be written
written asas follows:
follows:
public
public Iterator<Currency> iterator()
public Iterator<Currency>
Iterator<Currency> iterator()
iterator()
{
{
{
return
return table.iterator();
return table.iterator();
table.iterator();
}
}
}

How
How
How totoeven
evenwrite
writean
aniterator
iteratorI IIwill
willreturn
returntotolater,
later,but
butthe
theresult
resultofofthe
theiterator
iteratorpattern
patternisis
How to to even
even write
write an
an iterator
iterator I will
will return
return to
to later,
later, but
but the
the result
result of
of the
the iterator
iterator pattern
pattern is
is
that
that
thatyou
you
you can
can
canuse
use
usethe
the
theextended
extended
extended forfor
forconstruction:
construction:
construction:
that you can use the extended for construction:
for
for (Currency c : CurrencyTable.getInstance()) { … }
for (Currency
(Currency c
c :
: CurrencyTable.getInstance())
CurrencyTable.getInstance()) {
{ …
… }
}

In reality it is nothing but a short way of writing


InIn reality
realityitit
Inreality itisis nothing
isnothing but
butaaashort
nothingbut short way
wayofof
shortway writing
ofwriting
writing
for
for (Iterator<Currency> itr = CurrencyTable.getInstance().iterator();
for (Iterator<Currency>
(Iterator<Currency> itr
itr =
= CurrencyTable.getInstance().iterator();
CurrencyTable.getInstance().iterator();
itr.hasNext();
itr.hasNext(); )
)
itr.hasNext(); )
{
{
{
Currency
Currency c = itr.next();
Currency cc =
= itr.next();
itr.next();



}
}
}

The
The two
two classes
classes Currency
Currency and
and CurrencyTable
CurrencyTable are
are the
the program’s
program’s model.
model.
Thetwo
The twoclasses
classesCurrency
Currencyand
andCurrencyTable
CurrencyTableare
arethe
theprogram’s
program’smodel.
model.

6161
61
61
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Classes
Classes

THE
THECONTROLLER
CONTROLLER

The
Theprogram
programhas
hasaacontroller
controllerclass
classthat
thatby
byusing
usingthe
theabove
abovemodel
modelclasses
classesmust
mustperform
performthe
the
currency
currencyconversion,
conversion,including
includingvalidation
validationofofparameters
parametersfrom
fromthe
theuser
userinterface:
interface:

package currencyprogram;
import java.util.*;
import java.io.*;
public class Controller
{
public double calculate(String amount, Currency from, Currency to)
throws Exception
{
try
{
return calculate(Double.parseDouble(amount), from, to);
}
catch (Exception ex)
{
throw new Exception("Illegal amount");
}
}

public double calculate(double amount, Currency from, Currency to)


throws Exception
{
if (from == null || to == null) throw new Exception("No currency");
return amount * from.getRate() / to.getRate();
}

public ArrayList<String> update(File file)


{
ArrayList<String> errors = new ArrayList();
try
{
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
StringTokenizer tk = new StringTokenizer(line, ";");
if (tk.countTokens() == 3)
{
try
{
String name = tk.nextToken();
String code = tk.nextToken();
double rate = Double.parseDouble(tk.nextToken());
CurrencyTable.getInstance().update(new Currency(code, name, rate));
}

6262
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

catch (Exception ex)


{
errors.add(line);
}
}
else errors.add(line);
}
reader.close();
}
catch (Exception ex)
{
errors.add(ex.getMessage());
}
return errors;
}
}

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

63
63
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

There are two overloadings of the method calculate(), which is the method that will perform
the conversion. The difference is only the type of the first parameter, wherein the first converts
this from String to a double. Furthermore, there is a method update(), which parameter is
a File object. The file will represent a text file that contains a list of currencies when the
file must have the same format as the table been laid out in the class CurrencyTable. The
method updates the model corresponding to the content of the file. The method returns
an ArrayList which contains the lines from the file that could not be successfully parsed
into a Currency.

MAINCONSOLE

Regarding the program itself it is really two programs. The first is a console application
that works as follows:

The program starts to print an overview of the current currencies. In turn, there is a loop
in which the user for each iteration must

1. Enter the currency code for the currency to be converted from


2. Enter the currency code for the currency to be converted to
3. Enter the amount to be converted

and then the program prints the result of the conversion. This dialogue is repeated until
the user just types Enter for the first currency code. The program is represented by the class
MainConsole. I will not show the code here, but when you study the code, notice how I
use that class CurrencyTable is a singleton, and that it implements the iterator pattern.

You should note that compared to other console applications that I’ve looked at the code
is moved from the main class of its own class.

MAINVIEW

The other program is a GUI program that opens the window shown on the next page. To
make a currency calculation the user must enter the amount and select two currencies and
then click the Calculate button. The view then calls the controller to do the calculation
and use the result to update a field with the calculated value. If the user clicks the Clear
button, all fields will be cleared, and the combo box’s has no selection.

If the user clicks the Update button the program opens a file dialog so the user can browse
the file system for a semikolon delimited file with currencies rates. The file is sent to the
controller that use the file to update the model’s CurrrenceTable.

64
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

Again, I will not show the code, since it contains nothing new, but the window class is
called MainView.

THE DESIGN

The goal of the two versions of the program is to demonstrate why it is important to separate
an application in well-defined modules or layers. In this case, the program’s data arre defined
by two model classes that is Currency and CurrencyTable, while the data processing is carried
out in the class Controller. The difference between the two programs is alone the view layer
that in the one case is a console window, while in the second case it is a GUI window.

The relationship between the program’s classes can be illustrated as follows, where the arrows
shows which classes know who

That is the model layer’s classes do not know neither the controller layer or view layer and
the controller layer knows nothing about the view layer. The result is that you can replace
the view layer without it affects the rest of the program.

65
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

PROBLEM 2
In the book Java 1 I write a program that could create lottery rows and validates these rows
again when the week’s lottery is ready. The program was written as a command where you
defines by parameters as arguments on the command line that tells what the command
shoul do. You must now write a similar program, but such that the program this time has
a graphical user interface. When you opens the program, you should get a simple window
where you can choose between the program’s two functions:

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

66
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

If one here click on the first button, the program should open the following window, that
is used to create a new lottery and thus generate new lottery rows:

The lottery rows appears in a list box whose content can then be saved to a file.

If you click on the second button, the program shoul open the window below that is used
to validate a lottery against the week’s lottery numbers. The window has a text box to enter
the week’s lottery numbes and another field to shows the result of a control, and there are
two list boxes to the right, which respectively should show the validated rows and possible
rows with error.

67
JAVA 3: OBJECT-ORIENTED PROGRAMMING Classes

You should solve the task by the largest possible extent of reuse of class/code from the
solution in Java 1. The class’s LottoNumber, LottoGame and LottoRow should be used as
the are. You should write a controller to each of the two windows, and the code for these
controller class’s should be found in the class LottoCoupon. After you have written the
controller class’s you can remove the class LottoCoupon from the project.

68
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces

3 INTERFACES
This chapter describes interfaces and in the next chapter I describes inheritance that is two
other object-oriented concepts already briefly mentioned in Java 1, and in fact I has in
Java 2 used both concepts without explicitly draw attention to it. An interface defines the
properties that a class must have, while inheritance is a question about how to extends a
class with new properties in terms of new instance variables or methods. Immediately the
two thing do not seems having much to do with each other, but they have largely, and
therefore I treated both concepts subsequent.

To illustere both concepts I need some examples, and I want to use the same examples as
in the previous chapter, namely classes concerning students, and classes concerning books
in a library, and much of what follows will also address how these classes can be modified.

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

69
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
InterFaCes

3.1 INTERFACES
3.1 INTERFACES
Technically, an interface is a type, and it is a reference type. You can therefore do basically
the same with an interface as with a class, except that an interface can not be instantiated.
You can not create an object whose type is an interface, but otherwise an interface may be
used as a type for parameters, return values and variables.

Conceptually, an interface is a contract, and an interface can tell that an object has a specific
property. The interface specifies only what you can do with the object, but not how that
behavior is implemented, and that’s exactly what you want to achieve. Who that has to use
the object, only know it through the defining interface (that is the contract), but do not
know anything about how the class that underlies the object is made. So long this class
comply with the contract – and does not change the interface – the class can be changed
without it affects the code that uses the object.

Typically, an interface has only signatures of methods (but there are other options, as
explained below). An interface is defined by almost the same syntax as a class, but with the
difference that the word class is replaced by the word interface. I will, as mentioned, often
use the convention that I let the name of an interface start with a big I. In the previous
chapter I defined a the class Subject, representing a teaching subject and thus a concept
that can be included in a program concerning education. The concept can be defined as
follows (see the project Students3):

package students;
/**
* Defines a subject for an education.
*/
public interface ISubject
{
public String getId();

/**
* @return The subjects name
*/
public String getName();
/**
* Changes the subject's name. The subject must have a name, and if the parameter
* does not specify a name the method raises a exception.
* @param name The subjects name
* @throws Exception If the name is null or blank
*/
public void setName(String name) throws Exception;
}

70
JAVA 3:
JAVA
JAVA 3: OBJECT-ORIENTED
3: OBJECT-ORIENTED PROGRAMMING
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING InterFaCes
Interfaces
InterFaCes

The interface
The
The interface isis
interface is called
called ISubject,
called ISubject, and
ISubject, and the
and the only
the only thing
only thing you
thing you can
you can read
can read isis
read is that
that aaa concept
that concept that
concept that isis
that is aaa
ISubject, has
ISubject,
ISubject, has three
has three methods
three methods where
methods where the
where the comments
the comments explains
comments explains what
explains what these
what these methods
these methods do.
methods do.
do.

Once you
Once
Once you have
you have the
have the interface,
the interface, aaa class
interface, class can
class can implement
can implement this
implement this interface:
this interface:
interface:

public class
public class Subject
Subject implements
implements ISubject
ISubject
{
{

and itit
and
and it isis
is the
the only
the only change
only change in
change in the
in the the
the the class
the class Subject,
class Subject, because
Subject, because the
because the class
the class has
class has (implements)
has (implements) the
(implements) the
the
three methods
three
three methods defined
methods defined by
defined by the
by the interface.
the interface. So
interface. So the
So the question
the question isis
question is what
what you
what you have
you have achieved
have achieved with
achieved with
with
that and
that
that and so
and so far
so far nothing,
far nothing, but
nothing, but III will
but will make
will make some
make some changes
some changes in
changes in the
in the Course
the Course class.
Course class. ItIt
class. It has
has aaa variable
has variable
variable
of the
of
of the type
the type Subject,
type Subject, and
Subject, and III will
and will change
will change the
change the definition
the definition of
definition of this
of this variable,
this variable, so
variable, so that
so that itit
that it instead
instead has
instead has
has
the type
the
the type ISubject:
type ISubject:
ISubject:

private ISubject
private ISubject subject;
subject;

When aaa class


When
When class implements
class implements an
implements an interface,
an interface, the
interface, the class’s
the class’s type
class’s type isis
type is special
special the
special the type
the type of
type of this
of this interface,
this interface,
interface,
and therefore
and
and therefore itit
therefore it makes
makes sense
makes sense to
sense to say
to say that
say that aaa Subject
that Subject object
Subject object isis
object is also
also an
also an ISubject.
an ISubject. III have
ISubject. have also
have also
also
changed all
changed
changed all the
all the parameters
the parameters of
parameters of constructors
of constructors and
constructors and methods
and methods whose
methods whose type
whose type isis
type is Subject,
Subject, as
Subject, as their
as their type
their type
type
now are
now
now are ISubject.
are ISubject. You
ISubject. You should
You should note
should note that
note that the
that the program
the program still
program still can
still can be
can be translated
be translated and
translated and run.
and run. The
run. The
The
result isis
result
result is that
that the
that the class
the class Course
class Course no
Course no longer
no longer knows
longer knows the
knows the class
the class Subject,
class Subject, but
Subject, but itit
but it knows
knows only
knows only subject
only subject
subject
objects through
objects
objects through the
through the defining
the defining interface
defining interface ISubject.
interface ISubject. AA
ISubject. A Course
Course know
Course know what
know what itit
what it can
can with
can with aaa subject
with subject
subject
(it knows
(it
(it knows the
knows the contract),
the contract), but
contract), but not
but not how
not how aaa subject
how subject isis
subject is implemented.
implemented. The
implemented. The two
The two classes
two classes are
classes are now
are now
now
more loosely
more
more loosely coupled
loosely coupled than
coupled than they
than they were
they were before,
were before, and
before, and that
and that means
that means that
means that you
that you get
you get aaa program
get program that
program that
that
is easier
isis easier to
easier to maintain,
to maintain, as
maintain, as you
as you can
you can change
can change the
change the class
the class Subject
class Subject without
Subject without itit
without it matters
matters for
matters for classes
for classes that
classes that
that
use Subject
use
use Subject objects.
Subject objects.
objects.

The fact
The
The fact that
fact that in
that in this
in this way
this way defines
way defines the
defines the classes
the classes by
classes by means
by means of
means of an
of an interface,
an interface, and
interface, and other
and other classes
other classes
classes
only know
only
only know aaa class
know class through
class through its
through its interface
its interface isis
interface is aaa principle
principle or
principle or pattern,
or pattern, commonly
pattern, commonly referred
commonly referred to
referred to as
to as
as
programming to
programming
programming to an
to an interface.
an interface.
interface.

An interface
An
An interface in
interface in addition
in addition to
addition to signatures
to signatures of
signatures of methods
of methods can
methods can also
can also contain
also contain static
contain static variables
static variables and
variables and static
and static
static
methods ––
methods
methods – they
they are
they are not
are not attached
not attached to
attached to an
to an object.
an object. The
object. The class
The class Subject
class Subject has
Subject has aaa method
has method subjectOk(),
method subjectOk(),
subjectOk(),
which tests
which
which tests whether
tests whether the
whether the values
the values in
values in aaa subject
in subject are
subject are legal.
are legal. ItIt
legal. It isis
is aaa static
static method
static method and
method and does
and does not
does not depend
not depend
depend
on aaa Subject
on
on Subject object,
Subject object, and
object, and itit
and it can
can therefore
can therefore be
therefore be moved
be moved to
moved to the
to the interface.
the interface. This
interface. This means,
This means, however,
means, however,
however,
that in
that
that in the
in the class
the class Subject,
class Subject, the
Subject, the reference
the reference to
reference to the
to the method
the method (there
method (there are
(there are two)
are two) must
two) must be
must be changed
be changed to
changed to
to

ISubject.subjectOk(....)
ISubject.subjectOk(....)

where you
where
where you in
you in front
in front of
front of the
of the method’s
the method’s name
method’s name has
name has to
has to write
to write name
write name the
name the type
the type that
type that defines
that defines the
defines the method.
the method.
method.

71
71
71
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes
Interfaces

In the same way a Course can be defined by an interface:

package students;

/**
* Defines a course for a specified year for a specific subject.
* A course is associated with a particular student, and a course represent
* a subject that a student has completed.
* It is an assumption that the same subject only can be taking once a year.
*/
public interface ICourse

{
/**
* A cource is identified by the subjects id and the year
* @return Course ID composed of the year, the subject's id separated by a hyphen
*/
public String getId();

/**
* @return The year where the course is held.
*/
public int getYear();

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

72
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

/**
* @return true, if the student has completed the course
*/
public boolean completed();

/**
* @return The character that the student has achieved
* @throws Exception If a student has not obtained a character
*/
public int getScore() throws Exception;

/**
* Assigns this course a score.
* @param score The score that is the obtained
* @throws Exception If the score is illegal
*/
public void setScore(int score) throws Exception;

/**
* Assigns this course a character.
* @param score The score that is the obtained
* @throws Exception If the score is illegal
*/
public void setScore(String score) throws Exception;

/**
* @return Returns the subject for this course
*/
public ISubject getSubject();

/**
* Tests whether the parameters for a course are legal
* @param year The year for the course
* @param subject The subject that this course deals
* @return true, If the year is illegal or the subject is null
*/
public static boolean courseOk(int year, ISubject subject)
{
return year >= 2000 && year < 2100 && subject != null;
}
}

There is not much to explain, but you should note two things:
There is not much to explain, but you should note two things:

1. there is defined a new method getSubject(), which is not part of the class Course
1. there is defined a new method getSubject(), which is not part of the class Course
2. the method toString() is not defined, and it was nor defined in the interface ISubject
2. the method toString() is not defined, and it was nor defined in the interface ISubject

73
73
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Interfaces
InterFaCes

The
The class
class Course
Course must
must implements
implements the
the interface
interface ICourse,
ICourse, and
and because
because of of the
the first
first of
of the
the above
above
observations,
observations, itit isis necessary
necessary to
to add
add aa new
new method.
method. AA class
class that
that implements
implements an an interface
interface
must
must implement
implement all all the
the methods
methods that
that the
the interface
interface defines.
defines. Below
Below ii show
show the the class
class Course
Course
that now implements the interface ICourse where I have deleted
that now implements the interface ICourse where I have deleted all comments: all comments:

package students;

public class Course implements ICourse


{
private int year;
private ISubject subject;
private int score = Integer.MIN_VALUE;

public Course(int year, ISubject subject) throws Exception


{
if (!ICourse.courseOk(year, subject)) throw new Exception("Illegal course");
this.year = year;
this.subject = subject;
}

public Course(int year, String id, String name) throws Exception


{
subject = new Subject(id, name);
if (!ICourse.courseOk(year, subject)) throw
new Exception("Illegal year");
this.year = year;
}

public String getId()


{
return year + "-" + subject.getId();
}

public int getYear()


{
return year;
}

public ISubject getSubject()


{
return subject;
}

74
74
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

public boolean completed()


{
return score > Integer.MIN_VALUE;
}

public int getScore() throws Exception


{
if (score == Integer.MIN_VALUE)
throw new Exception("The student has not completed the course");
return score;
}

public void setScore(int score) throws Exception


{
if (!scoreOk(score)) throw new Exception("Illegal ckaracter");
this.score = score;
}
360°
public void setScore(String score) throws Exception
{
try
{
int number = Integer.parseInt(score);
thinking .

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


75
75
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

if
if (!scoreOk(number))
(!scoreOk(number)) throw
throw new
new Exception("Illegal
Exception("Illegal score");
score");
this.score = number;
this.score = number;
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
throw
throw new
new Exception("Illegal
Exception("Illegal score");
score");
}
}
}
}

public
public String
String toString()
toString()
{
{
return
return subject.toString();
subject.toString();
}
}
private
private boolean
boolean scoreOk(int
scoreOk(int score)
score)
{
{
return
return true;
true;
}
}
}
}

You
You should
should note:
note:

--- implements
implements and
and then
then the
the syntax
syntax toto implements
implements anan interface
interface
--- there
there is added a new method getSubject() that returns aa ISubject
is added a new method getSubject() that returns ISubject
--- that
that the method courseOk() is removed and moved to the interface
the method courseOk() is removed and moved to the interface
--- that the reference to courseOk() in the constructor is changed
that the reference to courseOk() in the constructor is changed

After
After these
these changes,
changes, the
the program
program can
can be
be translated
translated and
and run.
run.

If
If you
you have
have toto complies
complies with
with the
the principle
principle of
of programming
programming to to an
an interface,
interface, the
the class
class Student
Student
must
must be altered so that all instances of the type Course are changed to ICourse, but then
be altered so that all instances of the type Course are changed to ICourse, but then
the
the class Student is also decoupled from the class Course and know only a course by the
class Student is also decoupled from the class Course and know only a course by the
defining interface ICourse.
defining interface ICourse.

An
An interface
interface can
can in
in the
the same
same way
way as as aa class
class be
be public
public or
or it
it can
can be
be specified
specified without
without visibility.
visibility.
In
In the latter case, the interface is known only within the package to which it belongs. In
the latter case, the interface is known only within the package to which it belongs. In
the above examples, everywhere I have defined methods in an interface
the above examples, everywhere I have defined methods in an interface as public, but they as public, but they
are
are by
by default,
default, even
even ifif you
you do
do not
not write
write it.
it. II prefer
prefer always
always to to write
write the
the word
word public,
public, as
as it
it
clarifies the methods visibility. If an interface defines data (contains variables and
clarifies the methods visibility. If an interface defines data (contains variables and see possiblysee possibly
the
the interface
interface IPoint)
IPoint) these
these are
are always
always

public
public static
static final
final

76
76
76
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Interfaces
InterFaCes
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

whether
whether you
you write
write itit or
or not.
not. Again,
Again, II prefer
prefer to
to write
write itit all,
all, thus
thus clarifying
clarifying that
that itit isis aa
whether
public you write
public constantly.
constantly. it or not. Again, I prefer to write it all, thus clarifying that it is a
public constantly.
II would
would then
then add
add aa small
small change
change toto the
the class
class Student.
Student. The
The class
class has
has aa static
static method
method studentOk(),
studentOk(),
I would
which then add
which validates
validates thea small
the name change
name and to
and emailthe class
email addressStudent.
address of The class
of aa student
student to has a
to test static
test where method
where aa student
studentstudentOk(),
isis legal.
legal.
which
The validates
The controls
controls are the
are quite name and
quite trivial, email
trivial, since
since theaddress
the method of
method onlya student
only tests to test
tests whether
whether thewhere a
the value student is
value isis specified
specified legal.
for
for
The controls
both
both the
the name
name areand
quite
and trivial,
address.
address. sincenow
II will
will theextend
now methodthe
extend only
the tests whether
control,
control, so
so the the value
the method
method alsoistests
also specified
tests whether
whether for
both
the the address
the mail
mail name
addressand in address.
in the I will
the correct
correct now extend the control, so the method also tests whether
format:
format:
the mail address in the correct format:
public static boolean studentOk(String mail, String name)
{
public static boolean studentOk(String mail, String name)
{ return mailOk(mail) && name != null && name.length() > 0;
} return mailOk(mail) && name != null && name.length() > 0;
}
private static boolean mailOk(String mail)
{
private static boolean mailOk(String mail)
{ if (mail == null || mail.length() == 0) return false;
String
if (mail
pattern
== null
= || mail.length() == 0) return false;
"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}
String pattern =
\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}
Pattern p = Pattern.compile(pattern);
\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
Matcher p
Pattern m = Pattern.compile(pattern);
p.matcher(mail);
return m.matches();
Matcher m = p.matcher(mail);
} return m.matches();
}
Here, the method mailOk() is a method to validate whether a string may be a mail address.
Here,
Here, the
You must method
the at
method mailOk()
mailOk()
this place isis aa method
just accept method to
to validate
that method validate whether
whether
does, but aa string
it happensstring may
may be
by using be aa mail
mail address.
a so-called address.
regular
You
You must at this place just accept that method does, but it happens by using
expressions, as discussed later in Java 4. You should note that the method is private,regular
must at this place just accept that method does, but it happens by using a
a so-called
so-called regular
since
expressions,
expressions,
the control of as discussed
as an
discussed later
address later in Java
is notina Java 4. You
4. You
natural should
should
property note
of note that the
that the
a student. method
It ismethod is
thus a is private,
private,
helper since
since
method.
the control of an address is not a natural property of a student. It is thus
the control of an address is not a natural property of a student. It is thus a helper method. a helper method.
I’ve also changed the method setMail():
I’ve
I’ve also
also changed
changed the
the method
method setMail():
setMail():
public void setMail(String mail) throws Exception
{
public void setMail(String mail) throws Exception
{ if (!studentOk(mail, navn)) throw new Exception("Illegal mail address");
this.mail
if (!studentOk(mail,
= mail; navn)) throw new Exception("Illegal mail address");
} this.mail = mail;
}
Note that I here directly could have used mailOk(), but for the sake of the next I have not.
Note that
Note that II here
here directly
directly could
could have
have used
used mailOk(),
mailOk(), but
but for
for the
the sake
sake of
of the
the next
next II have
have not.
not.

77
77

77
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Interfaces
InterFaCes

Also aa student
Also student can
can bebe defined
defined by
by an
an interface
interface IStudent,
IStudent, but
but II will
will not
not show
show the
the entire
entire code
code
here
here since
since it
it does
does not
not contain
contain anything
anything new.
new. However,
However, there
there is
is one
one thing
thing which
which creates
creates aa
challenge.
challenge. II want
want toto move
move the
the method
method studentOk()
studentOk() toto the
the interface,
interface, and
and since
since it
it is
is aa static
static
method, you can immediately do it, but the private method maikOk()
method, you can immediately do it, but the private method maikOk() should be moved should be moved
to, and
to, and it
it gives
gives aa problem
problem since
since an
an interface
interface can
can not
not have
have aa private
private method.
method.

An
An interface
interface may
may have
have anan inner
inner class,
class, and
and although
although it
it is
is aa subject
subject which
which first
first addressed
addressed
later, it’s just a question that there is a class within an interface. The method studentOk()
later, it’s just a question that there is a class within an interface. The method studentOk()
can thus
can thus bebe moved
moved to
to the
the interface
interface as
as follows:
follows:

package students;

import java.util.*;
import java.util.regex.*;
/**
* The interface defines a student when a student is characterized by an
* identifier, a name and a mail address.
* A student also has a list of courses that the student has completed or
* participate in.
*/

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? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

78
78
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Interfaces
InterFaCes
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

public interface IStudent


public interface IStudent
{
{

/**
/**
* Tester om mail og navn kan repræsentere en studerende.
* Tester om mail og navn kan repræsentere en studerende.
* @param mail En studerendes mailadresse
* @param mail En studerendes mailadresse
* @param navn En studerendes navn
* @param navn En studerendes navn
* @return true, hvis mail og navn repræsenterer en lovlig studerende
* @return true, hvis mail og navn repræsenterer en lovlig studerende
*/
*/
public static boolean studentOk(String mail, String navn)
public static boolean studentOk(String mail, String navn)
{
{
return Email.mailOk(mail) && navn != null && navn.length() > 0;
return Email.mailOk(mail) && navn != null && navn.length() > 0;
}
}

class Email
class Email
{
{
private static boolean mailOk(String mail)
private static boolean mailOk(String mail)
{
{
String pattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]
String pattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]
{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
Pattern p = Pattern.compile(pattern);
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(mail);
Matcher m = p.matcher(mail);
return m.matches();
return m.matches();
}
}
}
}
}
}

Theimportant
The importantofofthis
thisexample
exampleisistotoshow
showthat
thatan
aninterface
interfacecan
canhave
havean
aninner
innerclass.
class.
The important of this example is to show that an interface can have an inner class.

Classes can
Classes can implement
implement an an interface,
interface, which
which asas stated
stated corresponds
corresponds toto the the class
class comply
comply aa
Classes can implement an interface, which as stated corresponds to the class comply a
contract.Classes,
contract. Classes,however,
however,can
canimplements
implementsmultiple
multipleinterfaces
interfacesand
andthusthuscomply
complywith withseveral
several
contract. Classes, however, can implements multiple interfaces and thus comply with several
contracts.IfIfthe
contracts. theclass
classimplements
implementsseveral
severalinterfaces
interfacesthethesyntax
syntaxisistotolist
listthem
themasasaacomma
comma
contracts. If the class implements several interfaces the syntax is to list them as a comma
separated list
separated list after
after the
the word
word implements.
implements. As
As anan example,
example, the
the following
following interface
interface defines
defines
separated list after the word implements. As an example, the following interface defines
pointsininthe
points theECTSECTSsystem:
system:
points in the ECTS system:
package students;
package students;
/**
/**
* Defines how many ECTS assigned to a subject.
* Defines how many ECTS assigned to a subject.
*/
*/
public interface IPoint
public interface IPoint

{
{
/**
/**
* Number of points a year
* Number of points a year
*/
*/
public static final int AAR = 60;
public static final int AAR = 60;

7979
79
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA3:
JAVA 3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING InterFaCes
InterFaCes

/**
/**
** @return
@return The
The subject's
subject's ECTS
ECTS
*/
*/
public
public intint getECTS();
getECTS();

/**
/**
** Changes
Changes the
the subtect's
subtect's ECTS
ECTS
* @param ects The subject's
* @param ects The subject's ECTS ECTS
** @throws
@throws Exception
Exception The
The number
number must
must not
not be
be negative
negative
*/
*/
public void
public void setECTS(int
setECTS(int ects)
ects) throws
throws Exception;
Exception;
}}

The
The interface
The interface is
interface isis not
not particularly
not particularly interesting,
particularly interesting, as
interesting, asas it
itit only
only in
only in principle
in principle defines
principle defines an
defines an integer,
an integer, but
integer, but
but
you
you might
you might assume
might assume that
assume that aaa subject
that subject must
subject must have
must have attached
have attached an
attached an ECTS,
an ECTS, and
ECTS, and the
and the class
the class Subjects
class Subjects could
Subjects could
could
then
then be
then be written
be written as
written as follows
as follows (where
follows (where III again
(where again has
again has removed
has removed all
removed all comments):
all comments):
comments):

package students;
package students;

public class
public class Subject
Subject implements
implements ISubject,
ISubject, IPoint
IPoint
{{
private String
private String id;
id; // the
// the subject
subject id
id
private String name; // the subject's
private String name; // the subject's name name
private int
private int ects
ects == 0;
0; //// the
the subtect's
subtect's ECTS
ECTS

public Subject(String
public Subject(String id,
id, String
String name)
name) throws
throws Exception
Exception
{{
this(id, name,
this(id, name, 0);
0);
}}

public Subject(String
public Subject(String id, id, String
String name,
name, int
int ects)
ects) throws
throws Exception
Exception
{{
if (!ISubject.subjectOk(id,
if (!ISubject.subjectOk(id, name))
name))
throw new Exception("The subject
throw new Exception("The subject must must have
have both
both an
an ID
ID and
and aa name");
name");
if (ects
if (ects << 0)
0) throw
throw new
new Exception("ECTS
Exception("ECTS must
must be
be non-negative");
non-negative");
this.id =
this.id = id;id;
this.name == name;
this.name name;
this.ects = ects;
this.ects = ects;
}}

public String
public String getId()
getId()
{{
return id;
return id;
}}

80
80
80
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

public String getName()


{
return name;
}

public void setName(String name) throws Exception


{
if (!ISubject.subjectOk(id, name))
throw new Exception("The subject must have a name");
this.name = name;
}

public int getECTS()


{
return ects;
}

public void setECTS(int ects) throws Exception


{
if (ects < 0) throw new Exception("ECTS must be non-negative");
this.ects = ects;
}

AXA Global
Graduate Program
Find out more and apply

81
81
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

public String toString()


{
return name;
}
}

The
Theclass
classnow
nowimplements
implementstwo twointerfaces,
interfaces,and
andmust
musttherefore
thereforeimplement
implementthe thetwo
twomethods,
methods,
the
the new interface defines. Also, I have expanded the class with a new constructor. Youshould
new interface defines. Also, I have expanded the class with a new constructor. You should
note
note the use of this where til old constructor calls the new constructor. You shouldnote,
the use of this where til old constructor calls the new constructor. You should note,
that
thatafter
afterthe
theclass
classSubject
Subjectisischanged
changedthetheprogram
programcan canstill
stillbebetranslated
translatedand
andexecuted.
executed.AA
Subject
Subjectobject
objectstill
stillhas
hasthe
thetype
typeISubject,
ISubject,but
butititalso
alsohashasthe
thetype
typeIPoint,
IPoint,but
butititisisnot
notused.
used.

EXERCISE
EXERCISE44
Start
Startby
bycreating
creatinga acopy
copyofofthe
theproject
projectLibrary3
Library3and
andcall
callthe
thecopy
copyfor
forLibrary4.
Library4.Open
Openthe
the
copy in NetBeans.
copy in NetBeans.

For
Foreach
eachofofthe
thethree
threeclasses
classesPublisher,
Publisher,Author
AuthorandandBook,
Book,you
youmust
mustwrite
writeananinterface,
interface,and
and
the respective classes must implement the interfaces. Note also that it means that
the respective classes must implement the interfaces. Note also that it means that the methodthe method
isbnOk()
isbnOk()should
shouldbebemoved
movedtotothetheinterface
interfaceIBook.
IBook.After
Afterthe
thethree
threeclasses
classesare
aredefined
definedusing
using
interfaces,
interfaces,and
andyouyoumust
mustmodify
modifythe
theclasses
classescode,
code,sosothe
thethree
threeclasses
classesisisasasloosely
looselycoupled
coupled
asaspossible, and you should change the main class for something like the
possible, and you should change the main class for something like the following: following:

public static void main(String[] args)


{
try
{
IBook b1 = create("978-1-59059-855-9",
"Beginning Fedora From Noice to Professional", 2007, 1, 519,
new Publisher(123, "Apress"), new Author("Shashank", "Sharma"),
new Author("Keir", "Thomas"));
IBook b2 = new Book("978-87-400-1676-5", "Spansk Vin");
print(b1);
print(b2);
b2.setReleased(2014);
b2.setEdition(1);
b2.setPages(335);
b2.setPublisher(new Publisher(200, "Politikkens Forlag"));
b2.getAuthors().add(new Author("Thomas", "Rydberg"));
print(b2);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}

82
82
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

private static void print(IAuthor a) { … }

private static void print(IBook book) { … }

private static IBook create(String isbn, String title, int released, int edition,
int pages, IPublisher publisher, IAuthor … authors) throws Exception { … }

3.2 MORE
3.2 MORE STUDENTS
STUDENTS
Above, II have
Above, have introduced
introduced interfaces
interfaces that
that defines
defines the
the properties
properties ofof an
an existing
existing class,
class, but
but inin
practice, you
practice, you usually
usually go
go the
the other
other way
way and
and defines
defines an
an interface
interface that
that defines
defines aa concept
concept in in the
the
program area
program area of
of concern,
concern, and
and then
then you
you (or
(or let
let others
others do
do it)
it) can
can write
write aa class
class that
that implements
implements
that interface.
that interface. Above,
Above, II have
have introduced
introduced definitions
definitions of of students
students and
and courses
courses inin the
the form
form of of
IStudent and
IStudent and ICourse
ICourse and
and then
then itit might
might be
be natural
natural toto define
define aa team
team of
of students,
students, where
where the
the
team must
team must have
have aa name
name and
and otherwise
otherwise isis simply
simply aa collection
collection ofof students:
students:

package students;

import java.util.*;

/**
* Interface, that defines a team of students.
*/
public interface ITeam extends Iterable<IStudent>
{

/**
* @return Name of the team
*/
public String getName();

/**
* Add students to the team
* @param stud The students to be added
*/
public void add(IStudent … stud);

/**
* Remove a student from the team.
* @param id Id on the student to be removed
* @return true, if the student was found and removed
*/
public boolean remove(int id);

83
83
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

/**
* Returns a student with a paticular id.
* @param id The id for the student to be returned
* @return The student identified by id
* @throws Exception If the student is not found
*/
public IStudent getStudent(int id) throws Exception;

/**
* Returns all students, where the name contains the value of the parameter.
* @param navn The search value
* @return All students where the name contains the search value
*/
public ArrayList<IStudent> findStudents(String name);

/**
* Returns all students, that has completed in a particular course a year.
* @param id Id of the subject
* @param aar Year
* @return All students who matches the search values
*/
public ArrayList<IStudent> findStudents(String id, int year);
}

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

84
84
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Interfaces
InterFaCes

There
Thereisisnot
notmuch
muchtotosay
sayabout
aboutthe
theinterface
interfacewhen
whenthethecomments
commentsexplaining
explainingthe
themeaning
meaning
ofofeach
eachmethod,
method,but
butyou
youshould
shouldnote
notethat
thatan
aninterface
interfacecancaninherit
inheritanother
anotherinterface,
interface,and
and
ininthis
thiscase
casethe
theinterface
interfaceITeam
ITeaminherits
inheritsthe
theinterface
interfaceIterable<Student>.
Iterable<Student>.This
Thismeans
meansthat
thataa
class
classthat
thatimplements
implementsthetheinterface,
interface,also
alsohas
hastotoimplement
implementthe theiterator
iteratorpattern.
pattern.Below
Belowisisaa
class
classthat
thatimplements
implementsthetheinterface
interfaceITeam:
ITeam:

package students;

import java.util.*;

public class Team implements ITeam


{
private String name; // the name
private ArrayList<IStudent> list = new ArrayList(); // the students

public Team(String name)


{
this.name = name;
}

public Iterator<IStudent> iterator()


{
return list.iterator();
}

public String getName()


{
return name;
}

public void add(IStudent … stud)


{
for (IStudent s : stud) list.add(s);
}

public boolean remove(int id)


{
for (int i = 0; i < list.size(); ++i)
if (list.get(i).getId() == id)
{
list.remove(i);
return true;
}
return false;
}

8585
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Interfaces
InterFaCes
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

public IStudent getStudent(int id) throws Exception


public IStudent getStudent(int id) throws Exception
{
{
for (IStudent s : list) if (s.getId() == id) return s;
for (IStudent s : list) if (s.getId() == id) return s;
throw new Exception("Student not found");
throw new Exception("Student not found");
}
}

public ArrayList<IStudent> findStudents(String name)


public ArrayList<IStudent> findStudents(String name)
{
{
ArrayList<IStudent> lst = new ArrayList();
ArrayList<IStudent> lst = new ArrayList();
for (IStudent s : list) if (s.getName().contains(name)) lst.add(s);
for (IStudent s : list) if (s.getName().contains(name)) lst.add(s);
return lst;
return lst;
}
}

public ArrayList<IStudent> findStudents(String id, int year)


public ArrayList<IStudent> findStudents(String id, int year)
{
{
ArrayList<IStudent> lst = new ArrayList();
ArrayList<IStudent> lst = new ArrayList();
for (IStudent s : list) for (ICourse c : s.getCourses(year))
for (IStudent s : list) for (ICourse c : s.getCourses(year))
if (c.completed() && c.getSubject().getId().equals(id)) lst.add(s);
if (c.completed() && c.getSubject().getId().equals(id)) lst.add(s);
return lst;
return lst;
}
}
}
}

There
There is
is not
not much
much toto explain,
explain, but
but you
you should
should note
note that
that the
the class
class implements
implements the
the iterator
iterator
pattern, and that the class does not know the class Student, but only know a student through
pattern, and that the class does not know the class Student, but only know a student through
the
the interface
interface IStudent.
IStudent.

As
As the
the last
last concept
concept in
in this
this family
family of
of types
types regarding
regarding students
students and
and education
education II will
will look
look at
at an
an
institution, but this time I will not define an interface. The class should instead
institution, but this time I will not define an interface. The class should instead be written be written
as
as aa singleton,
singleton, and
and the
the program
program therefore
therefore needs
needs toto know
know the
the actual
actual class,
class, why
why aa defining
defining
interface is not quite as interesting. The class is called Institution:
interface is not quite as interesting. The class is called Institution:

package students;
package students;

import java.util.*;
import java.util.*;

public class Institution implements Iterable<ITeam>


public class Institution implements Iterable<ITeam>
{
{
private static Institution instance = null;
private static Institution instance = null;
public final static String NAVN = "The Linux University";
public final static String NAVN = "The Linux University";

private ArrayList<ITeam> list = new ArrayList();


private ArrayList<ITeam> list = new ArrayList();

private Institution()
private Institution()
{
{
}
}

86
86
86
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

public static Institution getInstance()


{
if (instance == null)
{
synchronized (Institution.class)
{
if (instance == null) instance = new Institution();
}
}
return instance;
}

public ITeam getTeam(String name) throws Exception


{
for (ITeam t : list) if (t.getName().equals(name)) return t;
throw new Exception("There is no team with the name " + name);
}

public void add(ITeam … teams)


{
for (ITeam t : teams) list.add(t);
}

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
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

87
87
JAVA 3:
JAVA 3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING InterFaCes
Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

public Iterator<ITeam> iterator()


public
{ Iterator<ITeam> iterator()
public Iterator<ITeam> iterator()
{ return list.iterator();
{
} return list.iterator();
return list.iterator();
}}}
}
}
The class
The class isislargely
largelyself-explanatory,
self-explanatory,but butyouyou must
must notenote
thatthat
it isitwritten
is written
as a as a singleton,
singleton, and
The
and class
the is
patternlargely
is self-explanatory,
implemented in but
exactlyyou
the must
same note
way that
as I it
haveis written
shown as
in a singleton,
the currency
Thepattern
the class isis largely self-explanatory,
implemented butsame
in exactly the you way
must as Inote
havethat
shown it is
in written as a converter.
the currency singleton,
and the
converter. pattern
Alsothe is
note implemented
that in exactly
the classinimplements the same way as I have shown in the currency
and
Also the
notepattern
that isclass
implemented
implements exactly
the the the
iterator same iterator
pattern way
andaspattern
I have
note and notein
shown
finally that finally
the the that the
currency
class knows
converter.
class the
knows Also
onlynote that
thethat the
other class implements the iterator pattern and note finally that the
converter.
only Also
other note
program theprogram
class
classes classes
therethrough
implements
through there
the iterator
defining defining
pattern and
interfaces. interfaces.
note finally that the
class knows only the other program classes through there defining interfaces.
class knows only the other program classes through there defining interfaces.
Finally, II shows
Finally, shows the the test
test program.
program. TheThe main
main class
class already
already has
has aa print()
print() method,
method, which
which prints
prints
Finally, I
an IStudent.shows
IStudent. the test program. The main class already has a print() method, which prints
Finally,
an I showsII have
have added
the added
test the following
program.
the following
The main method to print
printhas
class already
method to an aInstitution:
an Institution:
print() method, which prints
an IStudent. I have added the following method to print an Institution:
an IStudent. I have added the following method to print an Institution:
private static void print()
private
{ static void print()
private static void print()
{ try
{
try
{
try
{ System.out.println(Institution.NAME);
{
System.out.println(Institution.NAME);
System.out.println();
System.out.println(Institution.NAME);
System.out.println();
for (ITeam team : Institution.getInstance())
System.out.println();
for
{ (ITeam team : Institution.getInstance())
for (ITeam team : Institution.getInstance())
{ System.out.println(team.getName());
{
System.out.println(team.getName());
for (IStudent stud : team)
System.out.println(team.getName());
for (IStudent stud : team)
{
for (IStudent stud : team)
{ System.out.println();
{
System.out.println();
print(stud);
System.out.println();
} print(stud);
print(stud);
}
System.out.println();
}
} System.out.println();
System.out.println();
}}}
}
catch (Exception ex)
}
catch (Exception ex)
{
catch (Exception ex)
{ System.out.println(ex.getMessage());
{
} System.out.println(ex.getMessage());
System.out.println(ex.getMessage());
}}}
}
You should note that both print() methods not dependents
} on the specific classes. The
You should
main() note
method that both print() methods not dependents on the specific classes. The
You should
You should noteis that
note as follows:
that both print()
both print() methods
methods not
not dependents
dependents on
on the
the specific
specific classes.
classes. The
The
main() method is as follows:
main() method
main() method isis as
as follows:
follows:
public static void main(String[] args)
public
{ static void main(String[] args)
public static void main(String[] args)
{ Institution.getInstance().add(
{
Institution.getInstance().add(
createTeam("Team-A 2015",
Institution.getInstance().add(
createTeam("Team-A 2015",
createStudent("olga.jensen@mail.dk", "Olga Jensen",
createTeam("Team-A 2015",
createStudent("olga.jensen@mail.dk", "OlgatoJensen",
createCourse(2015, "PRG", "Introduction Java", 5, 7),
createStudent("olga.jensen@mail.dk", "Olga Jensen",
createCourse(2015, "PRG", "Introduction to Java", 5, 7),
createCourse(2015, "PRG", "Introduction to Java", 5, 7),

88
88
88
88
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes
createCourse(2015, "OPS", "Operating Systems", 15, 2),
createCourse(2015, "SYS", "System Development", 5, 2)
createCourse(2015, "OPS", "Operating Systems", 15, 2),
),
createCourse(2015, "SYS", "System Development", 5, 2)
createStudent("harald.andersen@mail.dk", "Harald Andersen",
),
createCourse(2015, "PRG", "Introduction to Java", 5, 4),
createStudent("harald.andersen@mail.dk", "Harald Andersen",
createCourse(2015, "NET", "Computer Networks", 10, 12)
createCourse(2015, "PRG", "Introduction to Java", 5, 4),
)
createCourse(2015, "NET", "Computer Networks", 10, 12)
),
)
createTeam("Team-B 2015",
),
createStudent("svend.hansen@mail.dk", "Svend Hansen",
createTeam("Team-B 2015",
createCourse(2015, "OPS", "Operating Systems", 15, 10),
createStudent("svend.hansen@mail.dk", "Svend Hansen",
createCourse(2015, "RRG", "Introduction to Java", 5, 0),
createCourse(2015, "OPS", "Operating Systems", 15, 10),
createCourse(2015, "DBS", "Database Systems", 20, 7)
createCourse(2015, "RRG", "Introduction to Java", 5, 0),
),
createCourse(2015, "DBS", "Database Systems", 20, 7)
createStudent("svend.frederiksen@mail.dk", "Svend Frederiksen",
),
createCourse(2015, "OPS", "Operationg Systems", 15, 2),
createStudent("svend.frederiksen@mail.dk", "Svend Frederiksen",
createCourse(2015, "NETL", "Computer Networks", 10, 10)
createCourse(2015, "OPS", "Operationg Systems", 15, 2),
)
createCourse(2015, "NETL", "Computer Networks", 10, 10)
)
)
);
)
print();
);
}
print();
}
adding two teams to the institution where each team has two students. Finally the method
adding two teams to the institution where each team has two students. Finally the method
prints
addingthe
twoinstitution. Theinstitution
teams to the method uses some
where eachhelper
team methods to create Finally
has two students. objects:the method
prints the institution. The method uses some helper methods to create objects:
prints the institution. The method uses some helper methods to create objects:
private static ITeam createTeam(String name, IStudent … studs)
{
private static ITeam createTeam(String name, IStudent … studs)
ITeam team = new Team(name);
{
team.add(studs);
ITeam team = new Team(name);
return team;
team.add(studs);
}
return team;
}
private static IStudent createStudent(String mail, String name, ICourse … course)
{
private static IStudent createStudent(String mail, String name, ICourse … course)
try
{
{
try
return new Student(mail, name, course);
{
}
return new Student(mail, name, course);
catch (Exception ex)
}
{
catch (Exception ex)
return null;
{
}
return null;
}
}
private static ICourse createCourse(int year, String id, String name, int ects,
}
int score)
private static ICourse createCourse(int year, String id, String name, int ects,
{
int score)
{

89
89
89
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

try
{
try
{ ICourse course = new Course(year, id, name);
course.setScore(score);
ICourse course = new Course(year, id, name);
((IPoint)course.getSubject()).setECTS(ects);
course.setScore(score);
return course;
((IPoint)course.getSubject()).setECTS(ects);
} return course;
catch
} (Exception ex)
{
catch (Exception ex)
{ return null;
} return null;
}}
}
If you run the program you get the following result:
If you run the program you get the following result:
If you run the program you get the following result:
The Linux University
The Linux University
Team-A 2015
Team-A 2015
[1001] Olga Jensen
Introduction to Java, Score: 7
[1001] Olga Jensen
Operating Systems,
Introduction Score:
to Java, 2 7
Score:
System Development,
Operating Score: 22
Systems, Score:
System Development, Score: 2

90
90
90
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

[1002]
JAVA Harald Andersen
3: OBJECT-ORIENTED PROGRAMMING Interfaces
Introduction to Java, Score: 4
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes
Computer Networks, Score: 12
Team-B 2015
[1002] Harald Andersen
Introduction to Java, Score: 4
[1003] Svend Hansen
Computer Networks, Score: 12
Operating Systems, Score: 10
Team-B 2015
Introduction to Java, Score: 0
Database Systems, Score: 7
[1003] Svend Hansen
Operating Systems, Score: 10
[1004] Svend Frederiksen
Introduction to Java, Score: 0
Operationg Systems, Score: 2
Database Systems, Score: 7
Computer Networks, Score: 10

[1004] Svend Frederiksen


EXERCISE 5
Operationg Systems, Score: 2
Computer Networks, Score: 10
Make a copy of the project Library4and call the copy Library5. Open the copy in NetBeans.
You must write an interface defining a book list:
EXERCISE 5
package library;
Make a copy of the project Library4 and call the copy Library5. Open the copy in NetBeans.
You must write an interface defining a book list:
import java.util.*;

package library;
/**
* Defines a book list
import java.util.*;
*/
public interface IBooklist extends Iterable<IBook>
{/**
* Defines a book list
/**
*/
* Method, that adds books to the book list.
public interface
* If the IBooklist
list already extends
contains Iterable<IBook>
a book with
{
the same ISBN, the book should be
/**
* ignored.
** @param
Method,books
that The
addsbooks
bookstotobethe book list.
added
* If the list already contains a book with
*/
the
publicsamevoid
ISBN, the book… should
add(IBook books);be
* ignored.
* @param books The books to be added
/**
*/
* Method that creates a book and adds it to the list. The book is created on the
public void add(IBook … books);
* basis of et variabelt antal strenge, som fortolkes på følgende måde i den
* nævnte rækkefølge:
/**
* ISBN
** Method
title that creates a book and adds it to the list. The book is created on the
** basis
releaseof year
et variabelt antal strenge, som fortolkes på følgende måde i den
* nævnte
* edition rækkefølge:
** pages
ISBN
* title
* release year
* edition
* pages

91

91

91
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

* publisher name
* an number of pairs of authors' first and last name
* Only the first two arguments are required.
* Publisher's number extracted from the ISBN (see problem 1).
* @param elem Values to the book
* @throws Exception If the passed values are not legal book data
*/
public void add(String … elem) throws Exception;

/**
* Return the book with a certain isbn.
* @param isbn ISBN of the book to be returned
* @return The book idenfificeret of isbn
* @throws Exception If the book is not found
*/
public IBook getBog(String isbn) throws Exception;

/**
* Search books in the book list and returns a list of the books that matches the
* search values.
* The list is searched combined so that a book matching the search values if it
* matches all search values.
* If a String is null or blank, the criterion is ignored. The same applies to an
* int that is 0.
* By searching on strings that should not be distinction between uppercase and
* lowercase letters, and a criterion matches if the book value contains the
* search string.
* Especially by searching the author a book match if it has a single author,
* whose first and last name contains the values searched.
* @param isbn The book's ISBN, which matches the book if it is null, blank or
* the book's ISBN contains the value
* @param title The book's title, which matches the book if it is null, blank or
* book title contains the value
* @param year The book's publication, matching the book if 0 or release year is
* equal to the value
* @param edition The book's edition that matches the book if 0 or the book's
* edition is equal to the value
* @param publisher The name of the publisher, which matches the book if it is
* null, blank or publisher's name contains the value
* @param firstname Matches if null, blank or the book has an author whose first
* name contains the value
* @param lastname Matches if null, blank or the book has an author whose last
* name contains the value
* @return All books that matches the search values
*/
public ArrayList<IBook> find(String isbn, String title, int year, int edition,
String publisher, String firstname, String lastname);
}

92
92
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces

Write
Write aa class
class Booklist
Booklist that
that implements
implements the
the interface.
interface. When
When you
you have
have written
written the
the class,
class, you
you
must writes a test method. You can define
must writes a test method. You can define the following array in the main program, which
the following array in the main program, which
contains data for
contains data for 10
10 books:
books:

private static String[][] data = {


{ "978-1-59059-855-9", "Beginning Fedora From Novice to Professional",
"2007", "1", "519", "Apress", "Shashank", "Sharma", "Keir", "Thomas" },
{ "978-0-13-275727-0",
"A practical guide to Fedora and Red Hat Enterprise Linux", "2011",
"6", "519", "Prentice Hall", "Mark G.", "Sobell" },
{ "978-1-4842-0067-4", "Beginning Fedora Desktop: Fedora 20 Edition",
"2014", "1", "459", "Apress", "Richard", "Petersen" },
{ "978-0-470-48504-0", "Fedora 11 and Red Hat Enterprise Linux Bible",
"2011", "1", "1076", "Wiley Publishing", "Christopher", "Negus",
"Eric", "Foster-Johnson" },
{ "978-1-118-99987-5", "Linux Bible", "2015", "9", "859",
"John Wiley & Sons", "Christopher", "Negus" },
{ "0-534-95054-X", "Understanding Data Coomunications & Networks",
"1999", "2", "711", "Cole Publishing", "William A.", "Shay" },
{ "978-0-13-255317-9", "Computer Networks", "2011", "5", "952",
"Prentice Hall", "Andrew S.", "Tanenbaum", "David J.", "Wetherall" },
{ "0-13-148521-0", "Structured Computer Organization", "2006", "5",
"777", "Prentice Hall", "Andrew S.", "Tanenbaum" },

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

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.rug.nl/feb/education

93
93
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

{ "978-0-321-54622-7", "Data Structures & Problem Solving Using Java",


"2010", "4", "1011", "Addison-Wesley", "Mark Allen", "Weiss" },
{ "978-0-321-63700-0", "LINQ To Objects Using C# 4.0", "2010", "1",
"312", "Addison-Wesley", "Troy", "Magennis" },
};

Next,
Next,write
writeaatest
testmethod
methodon
onthe
thebasis
basisofofthese
thesedata
datathat
thatcreates
createsaabook
booklist
listwith
with10
10books
books
and
andprint
printthe
thebooks
bookswhose
whosetitle
titlecontains
containsthetheword
wordFedora.
Fedora.

3.3 FACTORIES
3.3 FACTORIES
The
Theprogram
programStudents
Studentsnow
nowconsists
consistsofofclasses
classeswhere
wherethethecoupling
couplingbetween
betweenthe theclasses
classesare
are
defined
definedbybyinterfaces.
interfaces.None
Noneofofthetheclasses
classesknow
knowabout
aboutthetheother
otherclasses
classesexistence,
existence,including
including
how
howthese
theseclasses
classesare
areimplemented,
implemented,but butthey
theyknow
knowwhat
whatyou
youcancando dowith
withobjects
objectsofofthe
the
specific
specificclasses,
classes,since
sincethey
theyknow
knowthe thecontracts.
contracts.Software
Softwareconsists
consistsofofmodules
modules(which
(whichhere
herecan
can
bebetranslated
translatedinto
intoclasses),
classes),and
andititisisaagoal
goaltotowrite
writesoftware
softwarethat
thatconsists
consistsofofasasloosely
looselycoupled
coupled
modules
modulesasaspossible.
possible.ToToprogram
programtotoan aninterface
interfaceisisan
animportant
importantstep stepininthat
thatdirection,
direction,but
but
somewhere,
somewhere,the thespecific
specificobjects
objectsmustmustbe becreated,
created,and
andininthe
theabove
abovetesttestprogram
programisisdonedone
ininthe
theparticular
particularhelp
helpmethods.
methods.However,
However,ititisisalso
alsothe
theonly
onlyplace
placewhere
wheretotoreferences
referencesthe
the
concrete
concreteclasses.
classes.

You
Youcancanmove
movethe
thecode
codethat
thatcreates
createsthe
theobjects
objectstotoaaspecial
specialclass,
class,which
whichisiscalled
calledaafactory
factory
class
class(a(aclass
classwhich
whichproduces
producesobjects).
objects).I’ve
I’veadded
addedthethefollowing
followingclass
classtotothe
theprogram:
program:

package students;

public abstract class Factory


{
public static ISubject createSubject(String id, String name) throws Exception
{
return new Subject(id, name);
}

public static ISubject createSubject(String id, String name, int ects)


throws Exception
{
return new Subject(id, name);
}

public static ICourse createCourse(int year, ISubject subject) throws Exception


{
return new Course(year, subject);
}

94
94
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

public static ICourse createCourse(int year, String id, String name)


throws Exception
{
return new Course(year, createSubject(id, name));
}

public static IStudent createStudent(String mail, String name,


ICourse … course) throws Exception
{
return new Student(mail, name, course);
}

public static ITeam createTeam(String name, IStudent … studs)


{
ITeam team = new Team(name);
team.add(studs);
return team;
}
}

The class consists only of static methods that creates objects of a concrete type, but returns
the objects as an interface types. The class is defined abstract, and this means that the class
can not be instantiated.

With the class Factory available, the test program can be written as follows, where I have
not shown the printing methods, as they are not changed:

public static void main(String[] args)


{
try
{
Institution.getInstance().add(
Factory.createTeam("Team-A 2015",
Factory.createStudent("olga.jensen@mail.dk", "Olga Jensen",
createCourse(2015, "PRG", "Introduction to Java", 5, 7),
createCourse(2015, "OPS", "Operating Systems", 15, 2),
createCourse(2015, "SYS", "System Development", 5, 2)
),
Factory.createStudent("harald.andersen@mail.dk", "Harald Andersen",
createCourse(2015, "PRG", "Introduction to Java", 5, 4),
createCourse(2015, "NET", "Computer Networks", 10, 12)
)
),
Factory.createTeam("Team-B 2015",
Factory.createStudent("svend.hansen@mail.dk", "Svend Hansen",

95
95
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

createCourse(2015, "OPS", "Operating Systems", 15, 10),


createCourse(2015, "RRG", "Introduction to Java", 5, 0),
createCourse(2015, "DBS", "Database Systems", 20, 7)
),
Factory.createStudent("svend.frederiksen@mail.dk", "Svend Frederiksen",
createCourse(2015, "OPS", "Operationg Systems", 15, 2),
createCourse(2015, "NETL", "Computer Networks", 10, 10)
)
)
);
print();
}
catch (Exception ex)
{
System.out.println(ex);
}
}

private static ICourse createCourse(int year,


String id, String name, int ects,
int score) throws Exception
{

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.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

96
96
JAVA 3: OBJECT-ORIENTED PROGRAMMING Interfaces
JAVA 3: OBJECT-ORIENTED PROGRAMMING InterFaCes

ICourse course =
Factory.createCourse(year, Factory.createSubject(id, name, ects));
course.setScore(score);
return course;
}

Then there are no coupling between the program and the concrete classes. In this case,
the class Factory is trivial with simple methods that do nothing but to encapsulate a new
operation, but other factory classes may be more complex, for example, to read data from
a file or database.

EXERCISE 6
Create a copy of the project Library5 and call the copy Library6. Open the copy in NetBeans
and create the following factory class:

public class Factory


{
public static IPublisher createPublisher(int nummer, String name)
throws Exception
{

}

public static IAuthor createAuthor(String firstname, String lastname)


throws Exception
{

}

public static IBook createBook(String … elem) throws Exception


{

}

public static IBooklist createBooklist()


{

}
}

Here are three of the methods trivial, but the method that creates a book is relatively
Here are three of the methods trivial, but the method that creates a book is relatively
complex. You can get the most of the required code from the class Booklist.
complex. You can get the most of the required code from the class Booklist.

After writing the class, change the main program, so all objects in the class Library are
After writing the class, change the main program, so all objects in the class Library are
created by calls to the Factory class. You must also change the class Booklist, so that it also
created by calls to the Factory class. You must also change the class Booklist, so that it also
applies the Factory class.
applies the Factory class.

97
97
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance
InherItanCe

4 INHERITANCE
4 INHERITANCE
If you have a class and you want another class, similar to the first, but expanded with new
variables or methods, or you may want one or more methods to work in a different way,
the new class can inherit the first. As explained in Java 1, the class that inherits, is called for
a derived class, while the class it is inherited from is called the base class. Other words for
the same are respectively subclasses and superclass. I will in this section illustrate inheritance
through classes, which represent loans in a bank. To make it simple, I will assume that a
loan is characterized by the formation expenses and an amount that I together will call
the loan’s principal, an interest rate which I would assume is constant throughout the loan
period, and a number of periods, which is the number of payments to repay the loan. It
thus corresponds to the same requirements as I assumed in the loan calculation program in
the book Java 2. Under these conditions a loan is defined as the following class:

package loanprogram;
public class Loan
{
private double principal; // the amount borrowed inc. costs
private double interestRate; // interest rate as a number between 0 and 1
private int periods; // the number of periods or number of payments

public Loan(double principal, double interestRate, int periods)


{
this.principal = principal;
this.interestRate = interestRate;
this.periods = periods;
}

public double getPrincipal()


{
return principal;
}

public double getInterestRate()


{
return interestRate;
}

public int getPeriods()


{
return periods;
}

98
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance
JAVA 3: OBJECT-ORIENTED PROGRAMMING InherItanCe

public double repayment(int n)


{
return 0;
}

public double interest(int n)


{
return 0;
}

public double payment(int n)


{
return 0;
}

public double outstanding(int n)


{
return 0;
}
}

99
99
{{
{{
return
return 0;
0;
JAVAreturn
JAVA return
3: 0;
0;
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Inheritance
InherItanCe
}}
}}

public double
public double outstanding(int
double outstanding(int
outstanding(int n)
The
The first
first three
public
public three
doublemethods
methods should
outstanding(intben)
should be n)
self-explanatory,
self-explanatory, and
n) and the
the last
last four
four returns
returns
{{
{{
return
return
return 0;
return 0;
0;
0;
}}
}}1.
1. repaid
repaid by
by the
the payment
payment of of the
the nth
nth payment
payment
}}
}}
2.
2. interest
interest by
by the
the payment
payment of of the
the nth
nth payment
payment
The 3.
first
Thefirst
first the
the nte
3.three
three nte payment
payment
methods
methods should be
shouldbe self-explanatory,
beself-explanatory, and
self-explanatory,and the
andthe last
thelast four
lastfour returns
fourreturns
returns
The
The first three
three methods
methods should
should be self-explanatory, and the last four returns
4.
4. the
the remaining
remaining debt
debt immediately
immediately after
after the
the payment
payment of of the
the nth
nth payment
payment
1. repaid
1. repaid
1.
1. repaid by
repaidby
by the
bythe
the payment
thepayment
payment of
paymentof
of the
ofthe
the nth
thenth
nthpayment
nth payment
payment
payment
IfIf you2.
2.
2. interest
interest
2. interest
you look
look
interest at by
by
atby
by the
the
the
the
the payment
thelast
payment
last four
paymentfourof
payment of
of the
methods,
methods,
of the
the nth
thenth
nth payment
nthpayment
payment
they
they are
payment are all
all trivial
trivial and
and returns
returns allall 0.
0. AA loan
loan can
can be
be
repaid
repaid 3.
3. in
3.
3. the
in
the
the nte
theseveral
several
nte
nte payment
ntepayment
payment
ways,
paymentways, andand to to write
write thethe code
code forfor the
the last
last four
four methods,
methods, itit requires
requires that
that you
you
know
know 4.
4.
4. the
the
4. what
what
the remaining
remaining
itit isis for
theremaining
remaining debt
debt
debt immediately
aa kind
fordebt immediately
kind loan
loan in
immediately
immediately after
after the
the
question.
in after
question.
after the payment
payment
That of
That know
the payment
payment of
know
of the
the
of the nth
nth
the
the nth
nth payment
payment
class
class Loan
thepayment
payment Loan not,
not, and
and therefore
therefore
itit isis not
not able
able to to implement
implement these these methods
methods in in aa meaningful
meaningful way. way. ItIt may
may onon the
the other
other hand
hand
If
If
If
If you
you look
look at
at the
the last
last four
four methods,
methods, they
they are
are all
all trivial
trivial and
and returns
returns all
all 0.
0. A
A loan
loan can
can be
be repaid
repaid in
in
beyou
be you look
look at
possible
possible atinthe
in the last
last four
aa derived
derived fourclass.
methods,
methods, they
class. they are
are all
all trivial
trivial and
and returns
returns all
all 0.
0. AA loan
loan can
can be
be repaid
repaid in
in
several
several
several ways,
severalways,
ways,and
ways, and
and to
andto
to write
towrite
write the
writethe
the code
thecode
codefor
code for
for the
forthe
the last
thelast
last four
lastfour
four methods,
methods,ititititrequires
fourmethods,
methods, requires
requiresthat
requires that
that you
thatyou
you know
youknow
knowwhat
know what
whatititititis
what is
is for
foraaaa
isfor
for
kind
kind
kind loan
kind loan
loan in
loan in
in question.
in question.
question. That
question. That
That know
That know
know the
know the
the class
the class
class Loan
Loan not,
class Loan
Loan not,
not, and
not, and
and therefore
therefore itititit is
and therefore
therefore is
is not
is not
not able
not able
able to
able to
to implement
to implement
implement these
implement these
these
these
The
The most
methodsmost
methodsinin common
common
inaaaameaningful
meaningfulloan
loan
way.
meaningfulway. is
is
way.It an
ItItan annuity
may
Itmay annuity
mayonon the
onthe that
that
other
theother is
is
hand
otherhand characterized
characterized
handbebe possible
bepossible
possiblein inby
by the
the
inaaaaderived
derived fact
fact that
that
class.
derivedclass.
class. you
you forfor each
each
methods
methods in meaningful way. may on the other hand be possible in derived class.
payment
payment pays pays the the samesame everyevery time.
time. When
When you you all all the
the time
time have have to to pay
pay interest
interest on on what what
is
is outstanding,
The
The
The
The outstanding,
most
most
most common
mostcommon
common
common ititloan
means
means
loan
loan
loan is
is
is an
isan
an
anthat
that the
annuity
annuity
annuity
annuity relationship
the that
relationship
that
that
that is
is
is characterized
ischaracterized between
characterized
characterizedbetween by
by
by the
the
bythe
the
the repayment
thefact
factrepayment
fact
fact that
that
that you
thatyou
youfor
you and
forand
for
for eachthe
each
each
each interest
thepayment
payment
payment
paymentinterestpays are
are
pays
pays
pays
the
the
the
the same
changed
changed
same
same every
sameevery
every
every time.
time.When
throughout
throughout
time.
time. When
When
the
When you
the repaid
repaid
you
you all
youall
all the
allperiod.
the
the time
thetime
period.timeIf
time Ifhave
have to
to
bb isisto
have
have thepay
the
to pay
pay interest
size
pay interest
size of
of the
interest on
on
theon
interest loan
on what
loanwhat
what
what is
(the
(the
is
is outstanding,
isoutstanding,
outstanding,
loan
loan principal), ititititmeans
principal),
outstanding, means
means that
that
rr isisthat
means the
the
that
the
the
the
the relationship
relationship
interest
interest rate
rate each
relationship
relationship between
between
each
between
betweenperiodethe
periodethe
the repayment
repayment
and and
and nn isis the
the repayment
repayment and the
the
andnumber
the
and number
the interest
interest
the interest
interestof are
are changed
changed
periods,
ofare
periods,
are changed
changed the
thethroughout
throughout
payment
paymentthe
throughout
throughout the
the
can
can
the repaid
repaid
be period. IfIf bbbb
period.
period.
be determined
repaid
repaid determined
period. If
If
is
is
is
is the
the
usingthe
using size
the size
size
size
theof
the of
of
of the
the
the
following
followingloan
the loan
loan (the
loanformula:
(the
(the loan
(the loan
loan
formula: principal), rrrr is
principal),
loan principal),
principal), is
is the
is the
the interest
the interest
interest rate
interest rate
rate each
rate each
each periode
each periode
periode and
periode and nnnn is
and
and is
is the
is the
the number
the number
number of
number of
of
of
periods,
periods,
periods, the
periods,the
the payment
thepayment
payment can
paymentcan
can be
canbe
be determined
bedetermined
determined using
determinedusing
using the
usingthe
the following
thefollowing
following formula:
followingformula:
formula:
formula:

𝑏𝑏𝑏𝑏
𝑏𝑏𝑏𝑏𝑏𝑏𝑏𝑏
𝑏𝑏𝑏𝑏
𝑏𝑏𝑏𝑏𝑏𝑏𝑏𝑏
𝑦𝑦 𝑦𝑦𝑦𝑦
𝑦𝑦𝑦𝑦𝑦𝑦 ==
=
= 11−
11−
− (1
(1+
−(1
(1 +
++𝑟𝑟) 𝑟𝑟) −𝑛𝑛
−𝑛𝑛𝑛𝑛
𝑏𝑏𝑏𝑏)−𝑛𝑛
𝑏𝑏𝑏𝑏) −𝑛𝑛𝑛𝑛

The
The
The outstanding
Theoutstanding
outstanding
outstanding debt
debt
debt
debt after
after
after
after you
youyou
you have
havehave
have paid
paid
paidpaid
the the
kth
thekth
kth kth
kthpayment
thepayment
payment
payment can becan
be
canbe can be
becalculated
calculated
calculated
calculated using using
the
usingtheusing
the the
theformula
formula
formula formula
The
The outstanding
outstanding debt
debt after
after you
you have
have paid
paid the
the kth payment
payment can
can be calculated
calculated using
using the formula
formula

𝑘𝑘𝑘𝑘𝑘𝑘
(1
(1(1+
(1 +
+ 𝑏𝑏𝑏𝑏)𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘𝑘−
𝑟𝑟)
+𝑟𝑟)
𝑏𝑏𝑏𝑏) −
−1111

𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟
𝑏𝑏𝑏𝑏𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟
𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟
𝑏𝑏𝑏𝑏𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟 ==
= 𝑏𝑏(1
𝑏𝑏𝑏𝑏(1
= 𝑏𝑏(1
𝑏𝑏𝑏𝑏(1+ +
+ 𝑟𝑟)
+𝑟𝑟) 𝑘𝑘𝑘𝑘𝑘𝑘 −
𝑏𝑏𝑏𝑏)
𝑏𝑏𝑏𝑏) − − 𝑦𝑦𝑦𝑦𝑦𝑦
−𝑦𝑦𝑦𝑦𝑦𝑦
𝑟𝑟𝑟𝑟𝑏𝑏𝑏𝑏𝑏𝑏𝑏𝑏
So
Soititititis
So
So isisthe kind
thekind of
kindof loan
ofloan that
thatIIIIlooked
loanthat looked
lookedat at in
atin Java
inJava 2.
Java2.
2.
So ititisisisthe
So the
thekind
the of
kind
kind loan
of that
of loan
loan looked
that
that at in
II looked
looked Java
at 2.
at in
in Java
Java 2.
2.

IIIIwill
will
will now
willnow
now write
writeaaaaclass
nowwrite
write class
class that
classthat
that represents
thatrepresents
represents an
representsan
an annuity
anannuity
annuity when
annuitywhen
when the
whenthe
the class
theclass
class will
classwill
will inherit
willinherit
inherit the
inheritthe
the class
theclass Loan:
Loan:
classLoan:
class Loan:
II will
will now
now write
write aa class
class that
that represents
represents an
an annuity
annuity when
when the
the class
class will
will inherit
inherit the
the class
class Loan:
Loan:
package
package
package loanprogram;
package loanprogram;
loanprogram;
loanprogram;
package loanprogram;
public
public
public class
public class
class Annuity
class Annuity
Annuity extends
Annuity extends
extends Loan
extends Loan
Loan
Loan
{{
{{
public
publicclass
public Annuity principal,
Annuity(double
Annuity(double extends
principal,Loan
double interestRate,
double interestRate, int
interestRate, int periods)
int periods)
periods)
public
public Annuity(double
Annuity(double principal,
principal, double
double interestRate, int periods)
{ {{
{{
public Annuity(double
super(principal,
super(principal,
super(principal,
super(principal, principal,
interestRate,
interestRate,
interestRate,
interestRate, double interestRate, int periods)
periods);
periods);
periods);
periods);
}
{}
}}
super(principal, interestRate, periods);
public
public
public double
public double
double payment(int
double payment(int
payment(int n)
payment(int n)
n)
n)
}
{{
{{

68
68
68
68

100
100
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING InherItanCe
InherItanCe

public
public double
double payment(int
payment(int n)
n)
{
{
return
return getPrincipal()
getPrincipal() *
*
getInterestRate()
getInterestRate() / (1 –
/ (1 – Math.pow(1
Math.pow(1 +
+ getInterestRate(),
getInterestRate(), -getPeriods()));
-getPeriods()));
}
}

public
public double
double outstanding(int
outstanding(int n)
n)
{
{
return
return getPrincipal()
getPrincipal() * * Math.pow(1
Math.pow(1 +
+ getInterestRate(),
getInterestRate(), n)
n) –

payment(0) * (Math.pow(1 + getInterestRate(), n) – 1) / getInterestRate();
payment(0) * (Math.pow(1 + getInterestRate(), n) – 1) / getInterestRate();
}
}

public
public double
double interest(int
interest(int n)
n)
{
{
return
return outstanding(n
outstanding(n –
– 1)
1) *
* getInterestRate();
getInterestRate();
}
}

public
public double
double repayment(int
repayment(int n)
n)
{
{
return
return payment(n)
payment(n) –
– interest(n);
interest(n);
}
}
}
}

You should
You should note
note that
that the
the class
class inherits
inherits Loan,
Loan, andand how
how toto specify
specify that
that with
with extends.
extends. The
The class
class
consists only
consists only of
of aa constructor
constructor and and the
the four
four methods
methods which
which should
should work
work in in aa different
different way.
way.
Wee say
Wee say that
that the
the class
class overrides
overrides the
the four
four methods
methods from from the
the base
base class.
class. That
That the
the class
class inherits
inherits
means it
means it beyond
beyond whatwhat it
it itself
itself defines
defines also
also can
can use
use public
public variables
variables and
and methods
methods from from the
the
base class.
base class. Because
Because aa derived
derived class
class can
can only
only refer
refer to
to what
what in
in the
the base
base class
class is
is defined
defined asas public,
public,
it can
it can therefore
therefore notnot reference
reference the
the base
base class’s
class’s variables,
variables, but
but itit must
must use
use to
to the
the get-methods.
get-methods.

When creating
When creating an
an annuity
annuity object,
object, the
the instance
instance variables
variables must
must be
be initialized,
initialized, but
but they
they
are in
are in the
the base
base class,
class, and
and are
are initialized
initialized using
using the
the base
base class’s
class’s constructor.
constructor. ItIt is
is therefore
therefore
necessary in
necessary in one
one way
way oror another
another toto get
get this
this constructor
constructor performed.
performed. ItIt must
must bebe called
called from
from
the constructor
the constructor ofof the
the class
class Annuity,
Annuity, but
but since
since you
you can
can not
not directly
directly call
call aa constructor,
constructor, itit is
is
necessary with
necessary with aa special
special syntax:
syntax:

super(principal,
super(principal, interestRate,
interestRate, periods);
periods);

that calls
that calls the
the base
base class’s
class’s constructor.
constructor. The
The statement
statement super
super must,
must, be
be the
the first
first statement
statement in
in
the derived
the derived class’s
class’s constructor.
constructor.

101
101
101
JAVA
JAVA3:
3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Inheritance
InherItanCe

The
The biggest
biggest challenge
challenge in
in writing
writing the
the class
class Annuity
Annuity isis to
to implement
implement the
the above
above formulas.
formulas. Here
Here
you
you must
must notice
notice the
the method
method Math.pow(),
Math.pow(), which
which calculates
calculates thethe power
power of
of an
an argument.
argument. With
With
this method available, it is quite simple to write the code to the four calculation
this method available, it is quite simple to write the code to the four calculation methods. methods.

IfIf you
you have
have an
an object
object of
of the
the type
type Annuity:
Annuity:

Annuity loan = new Annuity(10000, 0.015, 10);

then
then you
you can
can write
write aa statement
statement like
like the
the following:
following:

System.out.println(loan.repayment(5));

and
and the
the method
method isis repayment()
repayment() in
in the
the class
class Annuity
Annuity isis performed.
performed. You
You can
can also
also write
write

System.out.println(laan.getPrincipal());

as loan
as loan isis an
an Annuity
Annuity that
that inherits
inherits Loan
Loan and
and method
method getPrincipal()
getPrincipal() isis available.
available.

102
102
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Inheritance
InherItanCe

Sometimes
Sometimes itit can
can be
be conveniently
conveniently directly
directly to
to refer
refer to
to the
the variables
variables in in the
the base
base class
class from
from aa
method
method inin aa derived
derived class,
class, but
but without
without making
making them
them public.
public. This
This isis possible
possible ifif the
the variables
variables
are
are defined
defined protected:
protected:

public class Loan


{
protected double principal; // the amount borrowed inc. costs
protected double interestRate; // interest rate as a number between 0 and 1
protected int periods; // the number of periods

A
A protected
protected variable
variable can
can not
not be
be referenced
referenced outside
outside the
the class’s
class’s package
package (it
(it has
has package
package visibility),
visibility),
but
but itit can
can be
be referenced
referenced from
from derived
derived classes
classes –– even
even ifif they
they belong
belong toto aa different
different package.
package.
As an example the class Annuity now can be written
As an example the class Annuity now can be written as follows:as follows:

package loanprogram;

public class Annuity extends Loan


{
public Annuity(double principal, double interestRate, int periods)
{
super(principal, interestRate, periods);
}

public double payment(int n)


{
return principal * interestRate / (1 – Math.pow(1 + interestRate, -periods));
}

public double outstanding(int n)


{
return principal * Math.pow(1 + interestRate, n) –
payment(0) * (Math.pow(1 + interestRate, n) – 1) / interestRate;
}

public double interest(int n)


{
return outstanding(n – 1) * interestRate;
}

public double repayment(int n)


{
return payment(n) – interest(n);
}
}

103
103
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Inheritance
InherItanCe

InInthis
thiscontext,
context,there
thereare
arenonobig
bigdifferences,
differences,but
butininother
othersituations
situationsititmay
maybebenecessary
necessarytoto
open
openup upthe
theprotection,
protection,sosoderived
derivedclasses
classescan
canreference
referencevariables
variablesininthe
thebase
baseclass.
class.

Note
Notethat
thatthe
themethods
methodsalso
alsocan
canbebeprotected.
protected.

An
Anamortization
amortizationisisa atable
tableshowing
showinga asummary
summaryofofthethepayments
paymentsofofa aloan
loanand
andfor
foreach
each
payment shows the payment, repayment, interest and outstanding debt. The following
payment shows the payment, repayment, interest and outstanding debt. The following classclass
represents
representsananamortization:
amortization:

package loanprogram;

public class Amortization


{
private Loan loan;
public Amortization(Loan loan)
{
this.loan = loan;
}

public void print()


{
System.out.println(
"===================================================================");
System.out.printf("Principal: %12.2f\n", loan.getPrincipal());
System.out.printf("Interest rate: %12.2f %%\n",
loan.getInterestRate() * 100);
System.out.printf("Number of periods: %12d\n\n", loan.getPeriods());
System.out.println(
"Periods Payment Repayment Interest Outstanding");
System.out.println(
"----------------------------------------------------------------------");
for (int n = 1; n <= loan.getPeriods(); ++n)
System.out.printf("%7d%16.2f%17.2f%15.2f%15.2f\n", n, loan.payment(n),
loan.repayment(n), loan.interest(n), loan.outstanding(n));
System.out.println(
"----------------------------------------------------------------------");
}
}

Thereisisnot
There notmuch
muchtotoexplain,
explain,but
butnote
notethat
thatthe
theparameter
parametertotothetheconstructor
constructorhas
hasthe
thetype
type
Loanand
Loan andthe
theclass
classAmortization
Amortizationthus
thusisisnot
notaware
awareofofthe
thespecific
specificloan
loantypes
typessuch
suchasasAnnuity.
Annuity.
I Iwill
willreturn
returntotothat
thatshortly.
shortly.

104
104
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Inheritance
InherItanCe

With
With the
the class
class Amortisation
Amortisation available,
available, you
you can
can perform
perform the
the following
following program:
program:

public static void main(String[] args)


{
new Amortization(new Annuity(10000, 0.015, 10)).print();
}

and
and the
the result
result isis asas shown
shown below:
below:

===================================================================
Principal: 10000,00
Interest rate: 1,50 %
Number of periods: 10
Periods Payment Repayment Interest Outstanding
----------------------------------------------------------------------
1 1084,34 934,34 150,00 9065,66
2 1084,34 948,36 135,98 8117,30
3 1084,34 962,58 121,76 7154,72
4 1084,34 977,02 107,32 6177,70
5 1084,34 991,68 92,67 5186,02
6 1084,34 1006,55 77,79 4179,47
7 1084,34 1021,65 62,69 3157,82

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

105
105
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Inheritance
InherItanCe
JAVA 3: OBJECT-ORIENTED PROGRAMMING InherItanCe

8 1084,34 1036,97 47,37 2120,85


8 1084,34 1036,97 47,37 2120,85
9 1084,34 1052,53 31,81 1068,32
9 1084,34 1052,53 31,81 1068,32
10 1084,34 1068,32 16,02 0,00
10 1084,34 1068,32 16,02 0,00
----------------------------------------------------------------------
----------------------------------------------------------------------

In addition to the result, note that it is the methods in the class Annuity that are performed
In addition to the result, note that it is the methods in the class Annuity that are performed
and it is not obvious. The class Amortization only know the type of Loan that have trivial
and it is not obvious. The class Amortization only know the type of Loan that have trivial
methods, all of which returns 0. Nevertheless, it is the methods of the class Annuity that
methods, all of which returns 0. Nevertheless, it is the methods of the class Annuity that
are executed, and it is, even if the class Amortization only know the type Loan. When such
are executed, and it is, even if the class Amortization only know the type Loan. When such
it is the runtime system that remembers that the object loan actually has the type Annuity
it is the runtime system that remembers that the object loan actually has the type Annuity
and uses therefore the object with the right methods. It is one of the key concepts of object-
and uses therefore the object with the right methods. It is one of the key concepts of object-
oriented programming and is called polymorphism.
oriented programming and is called polymorphism.

If you considers the class Loan, then, as mentioned above the four calculation methods are
If you considers the class Loan, then, as mentioned above the four calculation methods are
trivial and all simply returns 0. These methods are somehow meaningless, and it makes no
trivial and all simply returns 0. These methods are somehow meaningless, and it makes no
sense to create objects whose type is Loan. If you did that, and sent such an object over
sense to create objects whose type is Loan. If you did that, and sent such an object over
a Amortization object, you would get an amortization table, where all numbers are 0. The
a Amortization object, you would get an amortization table, where all numbers are 0. The
problem can be solved by making the four methods abstract:
problem can be solved by making the four methods abstract:
package loanprogram;
package loanprogram;

public abstract class Loan


public abstract class Loan
{
{ protected double principal; // the amount borrowed inc. costs
protected double
double interestRate;
principal; // the amount borrowed inc. costs 0 and 1
protected // interest rate as a number between
protected double interestRate; // interest rate as a number between 0 and 1
protected int periods; // the number of periods
protected int periods; // the number of periods

public Loan(double principal, double interestRate, int periods)


public Loan(double principal, double interestRate, int periods)
{
{ this.principal = principal;
this.principal = principal;
this.interestRate = interestRate;
this.interestRate = interestRate;
this.periods = periods;
} this.periods = periods;
}

public double getPrincipal()


public double getPrincipal()
{
{ return principal;
} return principal;
}

public double getInterestRate()


public double getInterestRate()
{
{ return interestRate;
} return interestRate;
}

106
106
106
JAVA
JAVA3:
3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Inheritance
InherItanCe
JAVA 3: OBJECT-ORIENTED PROGRAMMING InherItanCe
JAVA 3: OBJECT-ORIENTED PROGRAMMING InherItanCe

public int
public int getPeriods()
getPeriods()
public int getPeriods()
{
{
{ return periods;
return
return periods;
periods;
}
}
}

public abstract double


public double repayment(int n);
n);
public abstract
abstract double repayment(int
repayment(int n);

public abstract double


public double interest(int n);
n);
public abstract
abstract double interest(int
interest(int n);

public abstract double


public double payment(int n);
n);
public abstract
abstract double payment(int
payment(int n);

public abstract double


public double outstanding(int n);
n);
public abstract
abstract double outstanding(int
outstanding(int n);

}
}
}

An abstract
An abstract method
method isis just
just a prototype
prototype or
or a signature
signature for
for a method
method inin the
the same
same way
way as as
An abstract method is just aa prototype or aa signature for aa method in the same way as
you defines
you defines methods
methods in in an
an interface.
interface. When
When aa class
class contains
contains abstract
abstract methods,
methods, thethe class
class isis
you defines methods in an interface. When a class contains abstract methods, the class is
abstract, and
abstract, and itit must
must bebe declared
declared as
as an
an abstract
abstract class:
class:
abstract, and it must be declared as an abstract class:
public abstract class
public class Loan
public abstract
abstract class Loan
Loan

An abstract class
An class can not
not be instantiated,
instantiated, and youyou can not
not with new
new create an an object whose
whose
An abstract
abstract class can
can not be
be instantiated, and
and you can
can not with
with new create
create an object
object whose
type is Loan
type Loan but anan abstract class
class can easily
easily be parameter
parameter to aa method.
method. That class
class Loan has
has
type is
is Loan but
but an abstract
abstract class can
can easily be
be parameter to
to a method. That
That class Loan
Loan has
four abstract methods
four methods means that that anyone whowho knows anything
anything that isis aa Loan
Loan knows that
that
four abstract
abstract methods means
means that anyone
anyone who knows
knows anything that
that is a Loan knows
knows that
the object in
the in question, has
has the four
four methods that
that the abstract
abstract class specify.
specify.
the object
object in question,
question, has the
the four methods
methods that thethe abstract class
class specify.

If the class
If class Loan isis changed
changed to anan abstract class
class as shown
shown above, the
the program can
can still be
be
If the
the class Loan
Loan is changed to to an abstract
abstract class as
as shown above,
above, the program
program can still
still be
translated and run,
translated run, and itit gives
gives the same
same result.
translated and
and run, andand it gives the
the same result.
result.

One way
One
One way to
to think
think of
of abstract
abstract classes
classes isis that
that you
you have
have toto write
write aa class
class Loan
Loan and
and know
know what
what
One way
way to
to think
think of
of abstract
abstract classes
classes is
is that
that you
you have
have to
to write
write aa class
class Loan
Loan and
and know
know what
what
properties and
properties
properties and methods
methods aa Loan
Loan must
must have,have, but
but some
some ofof the
the methods
methods you you are
are not
not able
able
properties and
and methods
methods aa Loan
Loan must
must have, have, but
but some
some of of the
the methods
methods you you are
are not
not able
able
to implement,
to
to implement, because
because youyou do
do not
not have
have sufficient
sufficient knowledge.
knowledge. These
These methods
methods can
can then
then
to implement,
implement, because
because you
you dodo not
not have
have sufficient
sufficient knowledge.
knowledge. TheseThese methods
methods cancan then
then
defined abstract
defined
defined abstract and
and postpone
postpone implementation
implementation to to the
the specific
specific derived
derived classes
classes who
who have
have the
the
defined abstract
abstract and
and postpone
postpone implementation
implementation to to the
the specific
specific derived
derived classes
classes who
who have
have the
the
necessary knowledge.
necessary
necessary knowledge.
necessary knowledge.
knowledge.

III will
will write
write another
another class
class that
that will
will represent
represent aa mix
mix loan.
loan. ItIt is
is aa loan
loan where
where in in the
the first
first periods
periods
I will
will write
write another
another class
class that
that will
will represent
represent aa mix
mix loan.
loan. It
It isis aa loan
loan where
where inin the
the first
first periods
periods
there
there isis no
there no repayment,
repayment, and and where
where you
you must
must paypay interest
interest only.
only. After
After the
the periods
periods without
without
there isis no
no repayment,
repayment, and and where
where youyou must
must paypay interest
interest only.
only. After
After the
the periods
periods without
without
repayment
repayment the
repayment the loan
loan isis an
an annuity,
annuity, but
but with
with aa fewer
fewer periods.
periods. The The class
class may,
may, for for example
example bebe
repayment the the loan
loan is
is anan annuity,
annuity, but
but with
with aa fewer
fewer periods.
periods. The The class
class may,
may, forfor example
example be be
written
written as
written as follows:
follows:
written as as follows:
follows:
package loanprogram;
package
package loanprogram;
loanprogram;

107
107
107
107
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance
JAVA 3: OBJECT-ORIENTED PROGRAMMING InherItanCe

public class MixLoan extends Loan


{
private int free;
private Loan loan;

public MixLoan(double principal, double interestRate, int periods, int free)


{
super(principal, interestRate, periods);
this.free = free;
loan = new Annuity(principal, interestRate, periods – free);
}

public int getFree()


{
return free;
}

public double payment(int n)


{
return n <= free ? principal * interestRate : loan.payment(n – free);
}

108
108
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Inheritance
InherItanCe
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING InherItanCe
InherItanCe

public double interest(int n)


public
public double
double interest(int
interest(int n)
n)
{
{
{ return n <= free ? principal * interestRate : loan.interest(n – free);
return n <= free ? principal * interestRate : loan.interest(n – free);
} return n <= free ? principal * interestRate : loan.interest(n – free);
}
}

public double repayment(int n)


public
public double
double repayment(int
repayment(int n)
n)
{
{
{ return n <= free ? 0 : loan.repayment(n – free);
return n <= free ? 0 : loan.repayment(n – free);
} return n <= free ? 0 : loan.repayment(n – free);
}
}

public double outstanding(int n)


public
public double
double outstanding(int
outstanding(int n)
n)
{
{
{ return n <= free ? principal : loan.outstanding(n – free);
return n <= free ? principal :
: loan.outstanding(n
loan.outstanding(n –
– free);
} return n <= free ? principal free);
}
}}
}
}

You should note that a derived class can add new variables (in this case two) and new
Youshould
You
You should note
shouldnote that
thataaaderived
notethat derived class
derivedclass can
classcan add
canadd new
addnew variables
newvariables (in
variables(in this
(inthis case
thiscase two)
casetwo) and
two)and new
andnew
new
methods (here the method getFree() that returns the number of periods without repayment).
methods
methods (here
methods(here the
(herethe method
themethod getFree()
methodgetFree() that
getFree()that returns
thatreturns the
returnsthe number
numberofof
thenumber periods
ofperiods without
periodswithout repayment).
withoutrepayment).
repayment).
The implementation of the four abstract methods are simple and are not further explained.
The
The implementation of the four abstract methods are simple and are not further
The implementation of the four abstract methods are simple and are not furtherexplained.
implementation of the four abstract methods are simple and are not further explained.
explained.
You can test the class in main():
You
You can
Youcan test
cantest the
testthe class
theclass in main():
classininmain():
main():
public static void main(String[] args)
public
public static
static void
void main(String[]
main(String[] args)
args)
{
{
{ new Amortization(new MixLoan(10000, 0.015, 10, 3)).print();
new Amortization(new MixLoan(10000, 0.015, 10, 3)).print();
} new Amortization(new MixLoan(10000, 0.015, 10, 3)).print();
}
}

AsAs another example of aaa loan,


loan, one
one can
can consider
consider aaa serial
serial loan
loan thatthat isis a loan where the
As another
As another example
another example ofof
example of a loan,
loan, one
one can
can consider
consider a serial
serial loan
loan thatthat isis aaa loan
loan where
loan where the
where the
the
repayment
repayment
repayment isis
is the
the
the same
same
same for
for
for every
every
every time.
time.
time. This
This
This means
means
means that
that
that payment
payment
payment is
is
is greatest
greatest
greatest atat
at the
the
the beginning
beginning
beginning
repayment is the same for every time. This means that payment is greatest at the beginning
and
and decreases through the loan period. Just asan
anAnnuity
Annuitythe theproject
projecthashasaaaclass
classSerial
Serialthat
that
anddecreases
and decreasesthrough
decreases throughthe
through theloan
the loanperiod.
loan period.Just
period. Justasas
Just as an
an Annuity
Annuity thethe project
project has
has a class
class Serial
Serial that
that
is
isis a derived class that inherits Loan and thus a concrete class. I will not show the code here.
isaaaderived
derivedclass
derived classthat
class thatinherits
that inheritsLoan
inherits Loanand
Loan andthus
and thusaaaconcrete
thus concreteclass.
concrete class.I IIwill
class. willnot
will notshow
not showthe
show thecode
the codehere.
code here.
here.

The
The
The abstractclass
abstract classLoan
Loancan
canbe
bedefined
definedby
byan
aninterface:
interface:
The abstract
abstract class
class Loan
Loan can
can be
be defined
defined by
by an
an interface:
interface:
package loanprogram;
package
package loanprogram;
loanprogram;

public interface ILoan


public
public interface
interface ILoan
ILoan
{
{
{ public double getPrincipal();
public
public double getPrincipal();
public double
double getPrincipal();
getInterestRate();
public
public double getInterestRate();
public double getInterestRate();
int getPeriods();
public
public int getPeriods();
public int getPeriods();
double repayment(int n);
public
public double repayment(int n);
public double repayment(int
double n);
interest(int n);
public
public double interest(int n);
public double
double interest(int n);
payment(int n);
public
public double
double payment(int
payment(int n);
n);
public double outstanding(int n);
public double outstanding(int n);
} public double outstanding(int n);
}
}

109
109
109
109
JAVA
JAVA3:
3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Inheritance
InherItanCe

An
An interface
interface consists
consists only
only in in principle
principle of
of abstract
abstract methods,
methods, but but itit isis not
not necessary
necessary to
to write
write
the
the word
word abstract,
abstract, but
but itit isis allowed.
allowed. The
The word
word abstract
abstract isis default.
default.

The
The class
class Loan
Loan must
must then
then implement
implement thethe interface
interface ILoan.
ILoan. This
This means
means that
that you
you can
can delete
delete
the
the four
four abstract
abstract methods,
methods, since
since they
they are
are defined
defined in in the
the interface,
interface, but
but the
the class
class must
must still
still
be
be abstract
abstract because
because itit does
does not
not implement
implement allall of
of the
the interface
interface methods:
methods:

package loanprogram;

public abstract class Loan implements ILoan


{
protected double principal; // the amount borrowed inc. costs
protected double interestRate; // interest rate as a number between 0 and 1
protected int periods; // the number of periods

public Loan(double principal, double interestRate, int periods)


{
this.principal = principal;
this.interestRate = interestRate;
this.periods = periods;
}

public double getPrincipal()


{
return principal;
}

public double getInterestRate()


{
return interestRate;
}

public int getPeriods()


{
return periods;
}
}

ItItisisthen
thenpossible
possible(and
(andyou youshould
shoulddo dothat)
that)to
tochange
changethe
theclass
classAmortization,
Amortization,where
wherethe
thetype
type
of the
of the variable
variable loan
loan isis changed
changed to
to ILoan,
ILoan, and
and the
the same
same for
for the
the parameter
parameter in
in the
the constructor.
constructor.

110
110
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance

EXERCISE 7
In problem 1 in the book Java 2 you have written a loan calculation program that calculates
the payment of an annuity and shows an amortization table. In this exercise you must create
an expansion of this program so that it also can perform loan calculations for a mix loan
and a serial loan.

Start by creating a copy of the project LoanCalculator from Java 2 and open the copy in
NetBeans. Copy the types

-- ILoan
-- Loan
-- Annuity
-- MixLaan
-- Serial

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

111
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance

from the above project. Next, edit the user interface as shown below. There is added a
combo box to select the type of the loan and a combo box for selecting the number of
free years. If it not is a mix loan, the value of the last combo box just should be ignored.
Finally, the texts of the two final fields are changed such they now respectively shows the
first payment and the overall payment for the first year (the payment is not longer necessarily
constant). You must then modify the model (quite a bit) so that it uses the loan types from
LoanProgram and you must also modify the controller a bit.

PROBLEM 2
The concept of a number sequence is known from mathematics and is a sekvense of numbers.
One example is the sequence of even numbers:

0, 2, 4, 6, 8, 10, …

where you constantly determines the next number by adding 2. In the same way you can
consider the sequence of powers of 2 and the factorials which are

1, 2, 4, 8, 16, 32, 64, 128, …

1, 1, 2, 6, 24, 120, 720, 5040, …

112
1, 2, 4, 8, 16, 32, 64, 128, ...

JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance


1, 1, 2, 6, 24, 120, 720, 5040, ...

AtAt the powersofof2 you


the powers 2 you always
always gostep
go one oneforward
step forward by multiplying
by multiplying bythe2,factorials
by 2, while at while atyou
thego
a step forward
factorials byamultiplying
you go by by
step forward the multiplying
next positive by
integer. Morepositive
the next precisely, a number
integer. More sequence is a
precisely,
sequence of numbers
a number sequence is a sequence of numbers

𝑎𝑎0 , 𝑎𝑎1 , 𝑎𝑎2 , . . . , 𝑎𝑎𝑛𝑛 , . ..

where there forfor


any
anynon
non negative integeris isattached
attached a (usually) real number. Taking as
wherewhere
therethere
for any non negative
negative integer
integer a (usually)
is attached a (usually) real number.
real number. Taking
Taking as example
as example the the
example the consisting
sequence
sequence sequence
consisting consisting
of theof ofof
the powers
powers of 2, the
you powers
2,sometimes
you 76ofwrites
sometimes 2, writes
you sometimes write
where there for any non negative integer is attached a (usually) real number. Taking as example the
𝑛𝑛 }
sequence consisting of the powers of 2, you sometimes{2𝑛𝑛 }{2
writes

In Insequence
In this
this this sequence
sequence asasexample
example
as example isis=𝑎𝑎10
is 𝑎𝑎10 = 1024..{2𝑛𝑛 }
1024.

InIn Insequence
Inthis
this
this this problem,
problem,
problem, asyou you
example
youshould should
is write
should write
𝑎𝑎10write
= 1024.
some some
someclasses classes
classes that represent
thatthat represent
represent sequences,
sequences,
sequences, but
butonly
but only onlysequences
sequences
sequences whosewhose
values
values are are integers.
integers.
whose values are integers.
In this problem, you should write some classes that represent sequences, but only sequences whose
values
Some Some
are sequences
integers.
sequences - like - fatorial
like fatorial - is growing
- is –growing very very rapidly,
rapidly, and must
and must sequences
sequences implemented
implemented in Java,
in Java, is is
Somelimited
sequences
in how
– like fatorial
big integers
is growing
yourepresent.
can represent.
very rapidly, and must sequences implemented
limited in how big integers you can SinceSince you here
you here only only
worksworks
with with sequences
sequences with with integer
integer
in Java, is limited in how big integers you can represent. Since you here only works with
Some values,
values,sequences the issize
the size likeis fatorial
- limited limited
by the-byisthe long.long.
type
growing
type youIfrapidly,
Ifvery you again
again andconsider
must
consider the factorial
thesequences
factorial implemented in Java, is
limited in how big integers you can represent. Since you here only workslong.
sequences with integer values, the size is limited by the type withIfsequences
you againwithconsider
integer
the factorial
values, the size is limited by the type 20!
20!long.
= If=you2432902008176640000
again consider the factorial
2432902008176640000

and itand it islargest


is the the largest fatorial
fatorial that canthat
20!becan be represented
=represented by a by
2432902008176640000 a long.
long. Java,Java, however,
however, has ahas a solution
solution in theinform
the form
of a of class a class BigInteger,
BigInteger, whichwhich is a is a software
software implementation
implementation of anofinteger.
an integer. In principle,
In principle, the class
the class
andit represents
and itis is
represents thethe
largestarbitrary
arbitrary
largestfatorial
large large
that canintegers,
thatbe
integers,
fatorial but
can itbut itrepresented
represented
costs
be costsby obviously
a long.
obviously a something
Java,
something
by Java,since
however,
long. since has acalculations
solution
calculations
however, on form
oninavery
has the very
largelarge
solution
of numbers becomes
BigInteger, slow. Nevertheless, theimplementation
class is worth knowing, soexample.
this example.
in athe
class
numbers becomes
form of slow.
a classwhich is a software
Nevertheless,
BigInteger, the class
which isisworth ofimplementation
knowing,
a software an integer.
so this In principle, the class
of an integer. In
represents arbitrary large integers, but it costs obviously something since calculations on very large
principle, the class represents arbitrary large integers, but it costs obviously something since
numbers
In theIn following
the following
becomes slow.
you canyou can think
Nevertheless,
think of atheof a sequence,
class
sequence, as a as
is worth a sequence
knowing,
sequence so
ofthis ofexample.
numbers numbers wherewhere
each each
numbernumber
is is
calculations
identified on very large numbers becomes slow. Nevertheless, the class is worth knowing,
identified by anbyindex,an index, but only
but only one
one of of these
these numbers numbers are visible
are visible and isand theissequence's
the sequence's current
current value.value.
so
InBelowthis
theBelow example.
followingI have youillustrated
canthe thinktheof sequence
a sequence,consistingas a of powers
sequence of 2, and there it isnumber
the number 256
is with
I have illustrated sequence consisting of powers of 2,ofandnumbers
there it where
is the each number
256 with
the index
identified
the index by an8,index,
8, that isthat isbut
visible:
visible: only one of these numbers are visible and is the sequence's current value.
In theI following
Below have illustrated you can think of consisting
the sequence a sequence, of as a sequence
powers of 2, and of there
numbers where
it is the each256
number number
with
the index 8, thatby
is identified is visible:
an index, but only one of these numbers are visible and is the sequence’s
current value. Below I have illustrated the sequence consisting of powers of 2, and there it
is the number 256 with the index 8, that is visible:

Create
Create a project
a project calledcalled Sequences.
Sequences. Add Add the following
the following interface,
interface, wherewhere the comments
the comments explains
explains what what
the the
methods
methods should
should do: do:
Create a project called Sequences. Add the following interface, where the comments explains what the
package sequences;
methods
package should do:
sequences;

import
import java.math.*;
java.math.*;
package sequences;

/** /**
import* java.math.*;
Defines a number sequence
* Defines a number sequence withwith integer
integer numbers
numbers where
where the first
the first index
index is 0.
is 0.
*/ */
/** public interface ISequence
public interface ISequence
* Defines
{ a number sequence with integer numbers where the first index is 0.
{
*/
/** /**
public interface
* @return ISequence
* @return NameName of sequence
of the the sequence 113
{ */
*/
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance
InherItanCe

Create a project called Sequences. Add the following interface, where the comments explains
what the methods should do:

package sequences;

import java.math.*;

/**
* Defines a number sequence with integer numbers where the first index is 0.
*/
public interface ISequence
{
/**
* @return Name of the sequence
*/
public String getName();
/**
* @return The current index
*/
public int getIndex();

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

114
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance
JAVA 3: OBJECT-ORIENTED PROGRAMMING InherItanCe

/**
* @return The current value
*/
public BigInteger getValue();

/**
* Returns the number in the sequence having the index n. At the same time,
* this number is the actual value.
* @param n The index the sequence must be set to
* @return Sequence's value for the index n
* @throws Exception If the index is less than 0
*/
public BigInteger getValue(int n) throws Exception;

/**
* Steps the sequens one step forward
*/
public void next();

/**
* Step the sequence one step back
* @throws Exception If the index is 0
*/
public void prev() throws Exception;

/**
* Sets the sequence of the first value that is greater than or equal to number.
* This value is then the sequence's current value.
* @param number The number the sequence to be set by
*/
public void next(BigInteger number);

/**
* Sets the sequence of the first value that is less than or equal to number.
* This value is then the sequence's current value.
* @param number The number the sequence to be set by
* @throws Exception If it not is possible to set the sequence at the value
*/
public void prev(BigInteger number) throws Exception;
}

You must observe the import of the package java.math. It’s the package containing the class
You must observe the import of the package java.math. It’s the package containing the class
BigInteger.
BigInteger.

115
115
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Inheritance
InherItanCe

A sequence is characterized by eight methods, and some of these methods does not depend
on a specific sequence. You should then write an abstract class Sequence, which implements
everything that is common to all sequences. This class will then be a common base class
for specific sequences.

As a next step you must implement the sequence consisting of the powers of 2. The class
is a concrete sequence and should be implemented as a class that inherits Sequence.

Once you have written the class, you should write the following test program (in the
main class):

public class Sequences


{
public static void main(String[] args)
{
print(new Power2(), 50);
}

private static void print(ISequence s, int n)


{
try
{
for (int i = 0; i <= n; ++i, s.next()) System.out.println(s);
while (s.getIndex() > 0)
{
s.prev();
System.out.println(s);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

Next,
Next, write
write aa class
class that
that implements
implementsthe
thefatorial,
fatorial,and
andaatest
testclass
classin
inthe
thesame
sameway
wayasasshown
shownabove.
above.

116
116
System.out.println(ex.getMessage());
}
}
}
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance

Next, write a class that implements the fatorial, and a test class in the same way as shown above.
Then, implements and test further three sequences:
Then, implements and test further three sequences:

1. Power, where the1.constructor


Power, where hasthea constructor
parameter, hasthat is a BigInteger.
a parameter, If this parameter
that is a BigInteger. If this parameter is called t
is called t, the sequence represents the numbers: 2 3 4 5
the sequence represents the numbers: 1, 𝑡𝑡, 𝑡𝑡 , 𝑡𝑡 , 𝑡𝑡 , 𝑡𝑡 , . ..
2. Fibonacci, that represents
2. Fibonacci, that represents the fibonacci the fibonacci
numbers: 0, 1, numbers:
1, 2, 3, 5, 0, 8,
1, 1,
13,2, 21,
3, 5,34,
8, 13,
55,21,…34, 55, ...
3. Prime,
3. Prime, that represents thethatprime
represents the prime2,numbers:
numbers: 3, 5, 7,2, 3,11,
5, 7,13,
11, 13,
17,17,19,
19, 23,
23, 29,
29,31, 37, ....

31, 37, ….
With regard to the last sequence you should examine the documentation for the class BigInteger as i
actually has a function that with reasonable probability can test whether an integer is a prime.
With regard to the last sequence you should examine the documentation for the class
After
BigInteger as it actually hasyou have implemented
a function that with these three sequences
reasonable and tested
probability can that
test they work properly,
whether an change the
integer is a prime. class Power2 such it inherits the class Power.

After you have implemented these three sequences and tested that they work properly,
4.1 More about inheritance
change the class Power2 such it inherits the class Power.

Above I have dealt with the most important concerning inheritance, but there are some details back
The kind of inheritance, as discussed above, is called for linear inheritance, which means that a clas
can only inherit one class - a class can have only one base class. On the other hand, a class can have al
the derived classes, as may be needed, and you can inherit in all the levels as you wish. Inheritance
leads to a hierarchy of classes. As an example the classes concerning loans has the following
hierarchy:

79

117
JAVA 3: OBJECT-ORIENTED PROGRAMMING Inheritance

4.1 MORE ABOUT INHERITANCE


Above I have dealt with the most important concerning inheritance, but there are some
details back. The kind of inheritance, as discussed above, is called for linear inheritance,
which means that a class can only inherit one class – a class can have only one base class.
On the other hand, a class can have all the derived classes, as may be needed, and you
can inherit in all the levels as you wish. Inheritance leads to a hierarchy of classes. As an
example the classes concerning loans has the following hierarchy:

ILoan is an interface, but it is included in the type hierarchy in the same manner as classes.
As another example, consider class hierarchy from problem 2:

If a class can inherit several classes, wee talk about multiple inheritance, but Java supports
only linear inheritance. Java does indirectly support multiple inheritance when a class can
implement all the interfaces that are needed. It is not inheritance, but it means that at
design time where you decide which classes a program must consist of, can work with
multiple inheritance. You can design classes that implements multiple interfaces.

118
JAVA 3: OBJECT-ORIENTED PROGRAMMING the Class objeCt
JAVA
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING The
the class
Class Object
objeCt
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING the
the Class
Class objeCt
objeCt

5
5
5 THE CLASS
THE CLASS OBJECT
OBJECT
5 THE CLASS OBJECT
Java has a class called Object, and all classes inherits directly or indirectly this class. If, as
Java
Java
Java has
has
has aa class
class called
called Object,
Object, and
and all
all classes
classes inherits
inherits directly
directly or
or indirectly
indirectly this
this class.
class. If,
If, as
as
an has aa class
Javaexample called
looking
class at Object,
called the classand
Object, and all
all classes
Loan classes inherits
inherits directly
directly or
or indirectly
indirectly this
this class.
class. If,
If, as
as
an
an example
example
an example looking
looking
example looking at
at
looking at the
the
at the class
class
the class Loan
Loan
class Loan
Loan
an
public abstract class Loan implements ILoan
public
public abstract
abstract class
class Loan
Loan implements
implements ILoan
ILoan
public abstract class Loan implements ILoan
the class automatically inherits the class Object. It means that you could have written
the
the
the class
class automatically
automatically inherits
inherits the
the class
class Object.
Object. It
It means
means that
that you
you could
could have
have written
written
the class
class automatically
automatically inherits
inherits the
the class
class Object.
Object. It
It means
means that
that you
you could
could have
have written
written
public abstract class Loan extends Object implements ILoan
public
public abstract class Loan
Loan extends Object implements
implements ILoan
public abstract
abstract class
class Loan extends
extends Object
Object implements ILoan
ILoan
and indeed it is allowed to write – but unnecessary. This means several things, including as
and
and
and indeed
indeed itit isis allowed
allowed toto write
write –– but
but unnecessary.
unnecessary. This
This means
means several
several things,
things, including
including as
as
and indeed
perhaps
indeedthe it is
is allowed
itmost to
to write
important
allowed that –
write –allbut unnecessary.
classes
but in Java are
unnecessary. This means
meansinseveral
Thislinked a largethings,
several hierarchy
things, including
with the
including as
as
perhaps
perhaps
perhaps the
the
the most
most
most important
important
important that
that
that all
all
all classes
classes
classes in
in
in Java
Java
Java are
are
are linked
linked
linked in
in
in aa
a large
large
large hierarchy
hierarchy
hierarchy with
with
with the
the
the
class
perhaps Object
the asmost the important
root. All classes without
that all classesexception
in Java are is an Object
linked in and inherits
a large the properties
hierarchy with the
class
class
class Object
Object
Object as
as the
ashas.the root.
root.
the root. All
All
root. All classes
classes
All classes without
without
classes without exception
exception
without exception
exception is is
is an
an
is an Object
Object
an Object and
and
Object and inherits
inherits
and inherits
inherits thethe
the properties
properties
the properties
properties
as anObject
class Objectas the
as
as an
an Object
Object has.
has.
as an Object has.
The class Object defines a few basic methods that all has a trivial implementation, and it is
The
The
The class
class Object
Object defines
defines aa few
few basic
basic methods
methods that
that all
all has
has aaa trivial
trivial implementation,
implementation, and and itit isis
The class
then up toObject
class defines
defines aa few
the individual
Object basic
classes
few methods
to override
basic methods thethat all
all has
thatmethodshas asotrivial
that implementation,
trivial they get a reasonable
implementation, and it
it is
and use. is
then
then
then upup
up to
to
upI to
to the
the individual
individual
the individual
individual classes
classes
classes to
to override
override
toimportant the
the
override the
the methods
methods
methodsand so
so that
that
so Ithat
that they
they
they get
get
get aa reasonable
reasonable use.
use.
Below
then briefly
the mention the mostto
classes override methods,
methods so willthey the aaclasses
use get reasonable use.
from use.
reasonable the
Below
Below
Below II briefly
briefly mention
mention the
the most
most important
important methods,
methods, and
and I
I will
will use
use the
the classes
classes from
from the
the
Below IIStudents.
project briefly
briefly mention
The classthe
mention most
most isimportant
Subject
the defined inmethods,
important and
and II way
the following
methods, will
will use
use the
the classes
classes from
from the the
project
project
project Students.
Students.
Students. The
The
The class
class
class Subject
Subject
Subject isis
is defined
defined
defined in
in
in the
the
the following
following
following way
way
way
project Students. The class Subject is defined in the following way
public class Subject implements ISubject , IPoint
public
public class
class Subject
Subject implements
implements ISubject
ISubject ,
, IPoint
IPoint
public class Subject implements ISubject , IPoint
where its methods are defined in two interfaces. The class also has a toString() method
where
where
where its
its methods
methods are
are defined
defined in
in two
two interfaces.
interfaces. The
The class
class also
also has
has aaa toString()
toString() method
method
where its
its methods
methods are
are defined
defined in
in two
two interfaces.
interfaces. The
The class
class also
also has
has a toString()
toString() method
method
public String toString()
public
public String toString()
public String
{ String toString()
toString()
{
{ return navn;
{
} return
return navn;
return navn;
navn;
}
}
}
which returns
which returns the
the subject’s
subject’s name
name as
as aa String.
String. If
If you
you now
now remove
remove this
this method
method (comment
(comment itit
which
which returns
returns the
the subject’s
subject’s name
name as
as aa String. If you now remove this method (comment it
out)
which
out) and perform
returns
and perform the
the the following
subject’s as a String. If you now remove this method (comment
method:
namemethod:
following String. If you now remove this method (comment it
it
out)
out) and
and perform
perform the
the following
following method:
method:
out) and perform the following method:
private static void test01()
private
private static void test01()
private static
{ static void
void test01()
test01()
{
{ try
{
try
try
{
try
{
{ ISubject subject = Factory.createSubject("MAT7", "Matematics");
{
ISubject
ISubject subject = Factory.createSubject("MAT7", "Matematics");
ISubject subject
subject == Factory.createSubject("MAT7",
System.out.println(subject);
Factory.createSubject("MAT7", "Matematics");
"Matematics");
System.out.println(subject);
System.out.println(subject); 7");
subject.setName("Matematics
System.out.println(subject);
subject.setName("Matematics
subject.setName("Matematics 7");
subject.setName("Matematics 7");
System.out.println(subject); 7");
} System.out.println(subject);
System.out.println(subject);
System.out.println(subject);
}
}
}

119
119
119
119
119
119
JAVA 3: OBJECT-ORIENTED PROGRAMMING The class Object
JAVA 3: OBJECT-ORIENTED PROGRAMMING the Class objeCt

catch (Exception ex)


{
System.out.println(ex.getMessage());
}
}

you
you get
get the
the result:
result:

students.Subtect@6d06d69c
students.Subject@6d06d69c

120
120
JAVA
JAVA3: OBJECT-ORIENTED PROGRAMMING The class Object
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING the
PROGRAMMING the Class
Class objeCt
objeCt
JAVA 3: OBJECT-ORIENTED PROGRAMMING the Class objeCt

subject
subject is ananobject, and when System.out.println() prints an object, it isisthe result ofofthe
subject isis an object,
object, and and when
when System.out.println()
System.out.println() prints prints an an object,
object, it it is the
the result
result of the
the
subject
object’s
object’s is an
toString()object,
toString() method
methodand when
that
that isisSystem.out.println()
printed.
printed. If
Ifnow
now the
theprints
object’s
object’s an object,
class
classdoes
does it
not is
not the
have
have result of the
a atoString()
toString()
object’s toString() method that is printed. If now the object’s class does not have a toString()
object’s –toString()
method
method such asasthe method class that is printed.
Subject If now thefrom
– ititisistoString() object’s the class
base does
class not
thathave a toString()
is performed,
method – – such
such as the the class
class Subject
Subject – – it is toString()
toString() fromfrom the the base
base class
class that
that isis performed,
performed,
method
and
and in this – case
suchititasis the class Subject
toString() from the – itclass
is toString()
Object. The from theObject
class base has
classa athat is performed,
default toString()
and in
in this
this case
case it is is toString()
toString() fromfrom the the class
class Object.
Object. TheThe classclass Object
Object hashas a default
default toString()
toString()
and
methodin
method this
that case
printsit is
thetoString()
class’s from
name the class
followed Object.
by a The
number. class
The Object
number has a
is default
the toString()
reference to
method that that prints
prints the the class’s
class’s name
name followed
followed by by aa number.
number. The The number
number is is the
the reference
reference toto
method
the
theobject
object that
onon prints
the
the heap
heapthe class’s
specified
specified name followed
asasa ahexadecimal
hexadecimal by a number.
number.
number. Of
OfThe number
course
course ititmakesis
makes the
nonoreference
particularto
particular
the object on the heap specified as a hexadecimal number. Of course it makes no particular
the object
sense, but ititon the heap
means that all specified
objectsas cana hexadecimal
be printed number.
with Of course it makes
System.out.println(), or moreno precisely
particular
sense,
sense, but
but it means
means that that all
all objects
objects can can bebe printed
printed withwith System.out.println(),
System.out.println(), or or more
more precisely
precisely
sense,
that one buthasitameans that all objects
representation ofofany can be printed
object with
asasa atext. ItItisSystem.out.println(),
then up totothe or more precisely
programmer of the
that
that one has a representation of any object as a text. It is then up to the programmer of
one has a representation any object text. is then up the programmer of the
the
that one
object’s has
class toa representation
override the of any
toString() object
so that as
it a text.
returns It
a is then
reasonable up to the
result. programmer
I will immediatelyof the
object’s
object’s class
class to
to override
override the the toString()
toString() so so that
that itit returns
returns aa reasonable
reasonable result.
result. II will
will immediately
immediately
object’sthe
remove class to override
comments forthe toString()method
toString() so that in it returns
the class a reasonable
Subject result. I will immediately
again:
remove the comments for toString() method
remove the comments for toString() method in the class Subject again:in the class Subject again:
remove the comments for toString() method in the class Subject again:
Matematics
Matematics
Matematics
Matematics
Matematics 7
7
Matematics 7

IfIf
Ifyou
youinin
you inthe
theabove
the abovemethod
above methodwrites
method writesthe
writes thestatement
the statement
statement
If you in the above method writes the statement
String s =
String s = "The subject: "
"The subject: " +
+ subject;
subject;
String s = "The subject: " + subject;

the
theresult
the resultwill
result willbebe
will bethat
thatthe
that thevariable
the variables sshas
variable hasthe
has thevalue
the value
value
the result will be that the variable s has the value
Subject: Matematics 7
Subject: Matematics 7
Subject: Matematics 7

The
The reason
reasonisis
Thereason that
isthat
thatthethe plus
theplus operator
operatorisis
plusoperator interpreted
interpretedasas
isinterpreted string
asstring concatenation,
stringconcatenation, and
concatenation,and since
andsince subject
sincesubject
subject
The
is anreason
object,is that
it is the
the plus
value operator
of this is interpreted
object’s as
toString(), string
that isconcatenation,
concateneted. and since subject
Incidentally, the
isisananobject,
object,ititisisthe
thevalue
valueofofthis
thisobject’s
object’stoString(),
toString(),that
thatisisconcateneted.
concateneted.Incidentally,
Incidentally,the
the
is an
result object,
would it is the value of this object’s toString(), that is concateneted. Incidentally, the
result wouldbebe
resultwould bethethe same
sameifif
thesame you
ifyou wrote:
youwrote:
wrote:
result would be the same if you wrote:
String s =
String s = "The subject: "
"The subject: " +
+ subject.toString();
subject.toString();
String s = "The subject: " + subject.toString();

Another method
methodinin
Anothermethod the
inthe class
theclass Object
Objectisis
classObject called
iscalled getClass(),
calledgetClass(), and
anditit
getClass(),and returns
returnsanan
itreturns object
objectofof
anobject the
ofthe type
thetype
type
Another
Another method in the class Object is called getClass(), and it returns an object of the type
Class
Class which
which contains
contains information
information about
about an
an object’s
object’s class
class –
– and
and there
there are
are many.
many. Consider
Consider as
Class which
Class whichcontains
contains information
information about
about ananobject’s
object’sclass
class––and
and there
thereare
aremany.
many. Consider
Consider asas
as
an
an example
example the
the following
following method:
method:
ananexample
examplethe
thefollowing
followingmethod:
method:
private
private static
static void
void test02()
test02()
private
{ static void test02()
{
{ try
try
try
{
{
{ ISubject subject = Factory.createSubject("MAT7", "Matematics");
ISubject subject = Factory.createSubject("MAT7", "Matematics");
ISubject subject = Factory.createSubject("MAT7", "Matematics");
print(subject);
print(subject);
} print(subject);
}
}
catch
catch (Exception
(Exception ex)
ex)
catch
{ (Exception ex)
{
{

121
121
121
121
JAVA 3: OBJECT-ORIENTED PROGRAMMING The class Object
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING the
the Class
Class objeCt
objeCt

System.out.println(ex.getMessage());
}
}

private static void print(Object obj)


{
System.out.println(obj.getClass().getName());
for (Method m : obj.getClass().getMethods()) System.out.println(m.getName());
}

Note
Notethat
thatthe
themethod
methodprint()
print()use
useaaclass
classMethod,
Method,that
thatisisdefined
definedininthe
thepackage
package

java.lang.reflect

The
Themethod
methodprint()
print()has
hasaaparameter
parameterofofthe
thetype
typeObject,
Object,and
andfor
forthis
thisobject
objectititprints
printsthe
the
name
nameofofthe theobject’s
object’sclass,
class,and
andthe
thenames
namesofofthetheobject’s
object’smethods.
methods.The
Themethod
methodtest02()
test02()
creates
creates an object of the type Subject and sends it as a parameter to the print() method.The
an object of the type Subject and sends it as a parameter to the print() method. The
result
resultisisthe
thefollowing:
following:

students.Subject
getECTS
setECTS
setName
getName
toString
getId
wait
wait
wait
equals
hashCode
getClass
notify
notifyAll

You
Youshould
shouldnote
notethe
theclass
classname,
name,andandthe
theobject
objectisisaaSubject,
Subject,although
althoughininthe
themethod
methodtest02()
test02()
isisknown
knownasasananISubject.
ISubject.YouYoushould
shouldalso
alsonote
notethat
thatthe themetod
metodprint()
print()prints
printsthe
thenames
namesofof
total
total14
14methods.
methods.It’s
It’sall
allpublic
publicmethods,
methods,and
andititisisfar
farmore
morethan
thanthe
theclass
classSubject
Subjectdefines,
defines,
but
butthe
therest
restcomes
comesfrom
fromthe theclass
classObject
Object––that
thatyouyouknowknowisisthe
thebase
baseclass
classfor
forSubject.
Subject.

AAClass
Classobject
objecthas
hasmany
manymethods,
methods,sosoyou
youcan
canget
getmany
manydetails
detailsregarding
regardingan
anobject.
object.The
The
method
methodgetClass()
getClass()can
cannot
notbe
beoverridden.
overridden.

122
122
122
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING The
the class Object
Class objeCt

The class
The class Object
Object also
also has
has aa method
method called
called equals()
equals() which
which has
has aa parameter
parameter of
of the
the type
type Object
Object
and
and is
is used
used to
to test
test whether
whether two
two objects
objects are
are the
the same.
same. Consider
Consider then
then the
the following
following method:
method:

private static void test03()


{
try
{
ISubject subject1 = Factory.createSubject("MAT7", "Matematics");
ISubject subject2 = Factory.createSubject("MAT7", "Matematics");
System.out.println(subject1.equals(subject2));
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}

The method creates two objects of the type Subject and tests whether they are the same. If
The method creates two objects of the type Subject and tests whether they are the same. If
you executes the method, you get the result
you executes the method, you get the result

false

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

123
123
JAVA 3: OBJECT-ORIENTED PROGRAMMING the Class objeCt
JAVA 3:
JAVA 3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING the class
The Class Object
objeCt

which is not really what one would expect. The method equals() is defined in the class
which isis not
which not really
really what
what one
one would
would expect.
expect. The The method
method equals()
equals() isis defined
defined inin the
the class
class
Object, and works by comparing the two objects addresses and thus whether they refer to
Object, and
Object, and works
works byby comparing
comparing the the two
two objects
objects addresses
addresses and
and thus
thus whether
whether they
they refer
refer to
to
the same object on the heap. In this case refers subject1 and subject2 to different objects,
the same
the same object
object on
on the
the heap.
heap. InIn this
this case
case refers
refers subject1
subject1 and
and subject2
subject2 to to different
different objects,
objects,
and therefore returns equals() false. Now if you want the comparison instead to be done
and therefore
and therefore returns
returns equals()
equals() false.
false. Now
Now ifif you you want
want the
the comparison
comparison instead
instead to
to be
be done
done
by from the objects’ values or state, it is up to the programmer to override the method in
by from
by from the
the objects’
objects’ values
values or
or state,
state, itit isis up
up to
to the
the programmer
programmer to to override
override thethe method
method in in
the concrete class.
the concrete
the concrete class.
class.

If you look at the class Subject, I would say that two Subject objects are equal if they have
IfIf you
you look
look at
at the
the class
class Subject,
Subject, II would
would say
say that
that two
two Subject
Subject objects
objects are
are equal
equal ifif they
they have
have
the same id – the value is perceived as a key that can identify a Subject. You can then
the same
the same id
id –– the
the value
value isis perceived
perceived asas aa key
key that
that can
can identify
identify aa Subject.
Subject. You
You can can then
then
override equals() in the following way:
override equals()
override equals() in
in the
the following
following way:
way:
public boolean equals(Object obj)
public boolean equals(Object obj)
{
{
if (obj == null) return false;
if (obj == null) return false;
if (getClass() == obj.getClass())
if (getClass() == obj.getClass())
return id.toUpperCase().equals(((Subject)obj).id.toUpperCase());
return id.toUpperCase().equals(((Subject)obj).id.toUpperCase());
return false;
return false;
}
}

That is, a Subject object is equal to another object, if the other object is not null, and if the
That
That is,
is, aa Subject
Subject object
object isis equal
equal to
to another
another object,
object, ifif the
the other
other object
object isis not
not null,
null, and
and ifif the
the
other object also is a Subject, and if both of these Subject objects have the same id when
other
other object
object also
also isis aa Subject,
Subject, and
and ifif both
both ofof these
these Subject
Subject objects
objects have
have the
the same
same idid when
when
there is no distinction between uppercase and lowercase letters. You should note that the
there
there is no distinction between uppercase and lowercase letters. You should note that the
is no distinction between uppercase and lowercase letters. You should note that the
test build on, that the class String overrides equals() such i compare the values af strings.
test
test build
build on, on, that
that thethe class
class String
String overrides
overrides equals()
equals() such
such ii compare
compare the the values
values af
af strings.
strings.
You should also note that there is no distinction on the name or ECTS, and that it is
You
You should
should alsoalso note
note thatthat there
there isis no
no distinction
distinction on on thethe name
name or or ECTS,
ECTS, and and that
that itit isis
the programmer’s decision how the equals() must be overridden and there could be other
the
the programmer’s
programmer’s decisiondecision how
how thethe equals()
equals() must
must bebe overridden
overridden andand there
there could
could bebe other
other
options. If you now executes the method test03() you get result
options. If you now executes the method test03()
options. If you now executes the method test03() you get result you get result

true
true

A method,
AA method, which belongs belongs to equals()
equals() is hashCode(). The The method returns
returns an int,
int, and the
the
method, whichwhich belongs to to equals() isis hashCode().
hashCode(). The method
method returns an an int, and
and the
default implementation in
default in class Object
Object returns the
the object’s memory
memory address. The The method isis
default implementation
implementation in class class Object returns
returns the object’s
object’s memory address.
address. The method
method is
used to
used to identify
identify anan object,
object, as
as well
well as
as to
to represent
represent an
an object
object asas aa number.
number. Later
Later II will
will show
used to identify an object, as well as to represent an object as a number. Later I will show show
applications of
applications of the
the method
method hashCode(),
hashCode(), and and here
here II will
will also
also explaine
explaine how
how toto overrides
overrides this
this
applications of the method hashCode(), and here I will also explaine how to overrides this
method, but in
method, in principle you
you should always
always override hashCode()
hashCode() if you overrides
overrides equals(). IfIf
method, but but in principle
principle you should
should always override
override hashCode() ifif youyou overrides equals().
equals(). If
need be
need be the
the protocol
protocol isis that
that ifif two
two objects
objects are
are equals,
equals, they
they must
must have
have the
the same
same hash
hash code.
code.
need be the protocol is that if two objects are equals, they must have the same hash code.
Because the class
Because class String overrides
overrides hashCode() –– correctly
correctly – it can be be overridden inin the class
class
Because thethe class String
String overrides hashCode()
hashCode() – correctly –– itit cancan be overridden
overridden in thethe class
Subject as follows:
Subject follows:
Subject as
as follows:
public int hashCode()
public int hashCode()
{
{
return id.toUpperCase().hashCode();
return id.toUpperCase().hashCode();
}
}

124
124
124
JAVA
JAVA3: OBJECT-ORIENTED PROGRAMMING The class Object
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING the
the Class
Class objeCt
objeCt

The
The class Object also has a method with the following signature:
The class
class Object
Object also
also has
has aa method
method with
with the
the following
following signature:
signature:

protected void
protected finalize() throws
void finalize() throws Throwable
Throwable

Because
Because it isis protected, it can not be called from other classes, but itit can be overridden.
Because it it is protected,
protected, it it can
can not
not be
be called
called from
from other
other classes,
classes, but
but it can
can be
be overridden.
overridden.
The
The method has not so many uses, and the default implementation performs nothing, but
The method
method has has not
not so
so many
many uses,
uses, and
and the
the default
default implementation
implementation performs
performs nothing,
nothing, but
but
the
the method
method isis called
called by
by the
the garbage
garbage collector
collector when
when an
an object
object isis removed
removed from
from the
the heap.
heap.
the method is called by the garbage collector when an object is removed from the heap.
You
You has the possibility, to override the method to add code to be executed when an object
You hashas the
the possibility,
possibility, toto override
override the
the method
method to to add
add code
code toto be
be executed
executed when
when an
an object
object
isis removed
removed from
from the
the heap.
heap.
is removed from the heap.

The
The last method in class Object, which I will mention has the following signature:
The last
last method
method in
in class
class Object,
Object, which
which II will
will mention
mention has
has the
the following
following signature:
signature:

protected Object
protected clone() throws
Object clone() throws CloneNotSupportedException
CloneNotSupportedException

and
and isis
and again
again aaa method
is again method which
method which
which youyou not
you not the
not the immediately
the immediately
immediately can can call
can call from
call from another
from another class.
another class. The
class. The
The
idea
idea is that
idea isis that
that thethe method
the method should
method should create
should create a copy
create aa copy
copy ofof the
of the current
the current object.
current object. A class
object. AA class can
class can override
can override this
override this
this
method
method ifif
method if itit implements
it implements the
implements the interface
the interface Cloneable.
interface Cloneable.
Cloneable. The The default
The default implementation
default implementation
implementation tests tests whether
tests whether
whether
the
the object’s
object’s class
class implements
implements this
this interface,
interface, and
and if
if not
not the
the method
method raises
raises
the object’s class implements this interface, and if not the method raises an exception. an
an exception.
exception.

IfIf
If III extends
extends the
extends the definition
the definition of
definition of the
of the class
the class Subject
class Subject as
Subject as follows
as follows
follows

public class
public Subject implements
class Subject ISubject, IPoint,
implements ISubject, IPoint, Cloneable
Cloneable

the
the default
the default clone()
default clone() method
clone() method
method will will create
will create
create anan object
an object that
that isis
object that is aaa copy
copy of
copy of the
of the current
the current object
current object
object andand
and
hence
hence have variables with the same value as the current object. In many contexts it is ok,
hence have
have variables
variables with
with the
the same
same value
value as
as the
the current
current object.
object. In
In many
many contexts
contexts it
it is
is ok,
ok,
but
but if you
but ifif you want
you want to
want to determine
to determine
determine how how the
how the copy
the copy is created
copy isis created
created youyou can
you can be
can be override
be override clone().
override clone(). If,
clone(). If, for
If, for
for
example
example
example the the object
the object has
object has references
has references
references to to other
to other objects,
other objects, it may
objects, itit may
may be be necessary,
be necessary, and
necessary, and another
and another reason
another reason
reason
may
may
may be be that
be that the
that the method
the method
method in in Object
Object isis
in Object protected.
is protected.
protected. In In the
In the class
the class Subject
class Subject you
Subject you could
you could override
could override
override the the
the
method
method to
to something
something like
like the
the
method to something like the following: following:
following:

public
public Object
Object clone()
clone() throws
throws CloneNotSupportedException
CloneNotSupportedException
{
{
Subject
Subject subject
subject =
= null;
null;
try
try
{
{
subject
subject == new
new Subject(new
Subject(new String(id),
String(id), new
new String(name),
String(name), ects);
ects);
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
}
}
return
return subject;
subject;
}
}

125
125
125
125
JAVA 3: OBJECT-ORIENTED PROGRAMMING The Class
the class objeCt
Object

That the creation of a Subject object is wrapped in try/catch it is because I have written the
constructor of the class Subject so that it can raise an exception. You should also note that
I as actual parameters to the constructor creates copies of the strings. Now it is not really
necessary, but is included because it in other contexts, in the case of other class types than
String, is often necessary.

You should also note that the method is public although in Object it is protected. It is actually
allowed on that way to strengthen the visibility of a method such that in a derived class is
defined with greater visibility than in the base class. One can, in turn, not reduce visibility.

Consider the following method:

private static void test04()


{
try
{
ISubject subject1 = Factory.createSubject("MAT7", "Matematics");
ISubject subject2 = (Subject)((Subject)subject1).clone();
System.out.println(subject1.equals(subject2));
System.out.println(subject1 == subject2);
}

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

126
JAVA 3: OBJECT-ORIENTED PROGRAMMING The class Object
JAVA 3: OBJECT-ORIENTED PROGRAMMING the Class objeCt
JAVA 3: OBJECT-ORIENTED PROGRAMMING the Class objeCt

catch
catch (Exception
(Exception ex)
ex)
{
{
System.out.println(ex.getMessage());
System.out.println(ex.getMessage());
}
}
}
}

IfIf
Ifyou
youexecute
you executethe
execute themethod,
the method,you
method, youget
you getthe
get theresult:
the result:
result:

true
true
false
false

because
because the two objects isisindeed a copy ofofeach other and, therefore equals(). The last
because the
the two
two objects
objects is indeed
indeed aa copy
copy of each
each other
other and,
and, therefore
therefore equals().
equals(). The
The last
last
statement
statement prints
printsfalse
falseand
andititshows
showsthat
thatsubject1
subject1 and
andsubject2
subject2are
aretwo
two different
differentobjects.
objects.You
You
statement prints false and it shows that subject1 and subject2 are two different objects. You
should
should note the statement
should note
note the
the statement
statement

ISubject subject2
ISubject subject2 =
= (Subject)((Subject)subject1).clone();
(Subject)((Subject)subject1).clone();

subject1
subject1isis
subject1 isinin the
inthe code
thecode known
knownasas
codeknown asanan object
objectofof
anobject the
ofthe type
thetype ISubject,
typeISubject, and
anditit
ISubject,and does
itdoes not
doesnot have
havea aaclone()
nothave clone()
clone()
method.
method. Therefore,
method.Therefore, it is necessary
Therefore,ititisisnecessary with
necessarywith a type
witha atype of cast
typeofofcast of subject1
castofofsubject1 to a Subject.
subject1totoa aSubject. The
Subject.The method
Themethod
method
clone()
clone() returns an Object, and therefore it is necessary with a typecast of
clone() returns an Object, and therefore it is necessary with a typecast of the returnvalue.
returns an Object, and therefore it is necessary with a typecast of the
the return
return value.
value.
The
The concept
concept typecast
typecast isis elaborated
elaborated in
in the
the next
next
The concept typecast is elaborated in the next chapter. chapter.
chapter.

127
127
127
JAVA
JAVA
JAVA 3:
3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Typecast
typeCast
typeCast of
oF
oF objects
objeCts
PROGRAMMING objeCts

6
6 TYPECAST
TYPECAST OF
OF OBJECTS
OBJECTS
III have
have
have previously
previously
previously in in
in Java
Java
Java 111 mentioned
mentioned
mentioned typecast
typecast
typecast of of
of simple
simple
simple types.
types.
types. AsAs
As an
an
an example
example
example you
you
you can
can
can not
not
not
explicit
explicit
explicit copy
copy
copy aaa long
long
long to
to
to an
an
an int
int
int because
because
because an
an
an int
int
int may
may
may not
not
not have
have
have enough
enough
enough space.
space.
space. ItIt
It may
may
may be
be
be necessary
necessary
necessary
toto
to write something like the following to tell the compiler that t well should be copied to
write
write something
something like
like the
the following
following to
to tell
tell the
the compiler
compiler that
that tt well
well should
should be
be copied
copied to
to a:a:
a:

long
long tt =
= 123;
123;
int a;
int a;
a
a =
= (int)t;
(int)t;

Also
Also objects can be typecasted, but ititisisnecessary that they belong to the same class hierarchy.
Also objects
objects can
can be
be typecasted,
typecasted, but
but it is necessary
necessary that
that they
they belong
belong to to the
the same
same class
class hierarchy.
hierarchy.
Otherwise,
Otherwise, you get an exception ifif not the compiler before isis giving an error. Consider as
Otherwise, you get an exception if not the compiler before is giving an error. Consider as
you get an exception not the compiler before giving an error. Consider as
an
an example the following method:
an example
example the
the following
following method:
method:

private
private static
static void
void test05()
test05()
{
{
try
try
{
{
Subject
Subject subject1
subject1 == new
new Subject("MAT7",
Subject("MAT7", "Matematics");
"Matematics");
ISubject subject2 = subject1;
ISubject subject2 = subject1;
Subject
Subject subject3
subject3 == (Subject)subject2;
(Subject)subject2;
System.out.println(subject1.equals(subject2));
System.out.println(subject1.equals(subject2));
System.out.println(subject1.equals(subject3));
System.out.println(subject1.equals(subject3));
System.out.println(subject3.equals(subject2));
System.out.println(subject3.equals(subject2));
//
// Course
Course course
course == (Course)subject1;
(Course)subject1;
}
}
catch
catch (Exception
(Exception ex)
ex)
{
{
System.out.println(ex.getMessage());
System.out.println(ex.getMessage());
}
}
}
}

Here
Here refers subject1, subject2 and subject3 all to the same object. Note that you can write
Here refers
refers subject1,
subject1, subject2
subject2 and
and subject3
subject3 all
all to
to the
the same
same object.
object. Note
Note that
that you
you can
can write
write

subjet2
subjet2 =
= subjet1
subjet1

for
for subject1
subject1isis
forsubject1 isaaaSubject
Subject object
Subjectobject and
objectand thus
andthus specifically
thusspecifically an
specificallyan ISubject
anISubject object.
ISubjectobject. In
object.In contrast,
Incontrast, the
contrast,the statment
thestatment
statment

subjet3
subjet3 =
= (Subjet)subjet2
(Subjet)subjet2

128
128
128
JAVA 3:
JAVA 3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Typecast of
typeCast oF objects
objeCts

requires aa typecast,
requires typecast, as
as subject2
subject2 is
is an
an ISubject
ISubject object,
object, which
which is
is not
not necessarily
necessarily aa Subject
Subject object.
object.
Note the
Note the syntax
syntax of
of aa typecast,
typecast, where
where in
in front
front of
of aa variable
variable you
you write
write the
the type
type to
to cast
cast to,
to,
in parentheses.
in parentheses.

By contrast,
By contrast, the
the following
following statement
statement

Course course = (Course)subject1;

results in a compiler error because Course and Subject not are types from the same class
results in a compiler error because Course and Subject not are types from the same class
hierarchy.
hierarchy.

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

129
129
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Aalast
lastnote
noteabout
aboutclasses
Classes

7
7 AA LAST
LAST NOTE
NOTE ABOUT
ABOUT CLASSES
CLASSES
As
As aa final
final note
note regarding
regarding classes
classes II mention
mention the
the word
word final.
final. IfIf one
one defines
defines aa variable
variable final
final
like
likeNAME
NAMEininthe theclass
classInstitution
Institution

public final static String NAME = "The Linux University";

thismeans
this meansthat
thatthe
thevariable
variableisisaaconstant,
constant,and
anditsitsvalue
valuecan cannotnotbe bechanged.
changed.AlsoAlsomethods
methods
can be
can be defined
defined final,
final, and
and aa final
final method
method cancan not
not be
be overridden
overridden inin aa derived
derived class.
class. IfIf aa
methodisisoverridden
method overriddenininaaderived
derivedclass,
class,you
youhashasthe
thepossibility
possibilitytotowritewritethe
themethod
methodtotohavehave
aa whole
whole different
different meaning,
meaning, andand ifif you
you do
do not
not want
want itit toto be
be possible,
possible, youyou can
can define
define thethe
methodfinal.
method final.Also
Alsofinal
finalclasses
classescan
canbe bedefined,
defined,andandaafinal
finalclass
classisisaaclass
classwhich
whichcan
cannot
notbe be
inherited.As
inherited. Asananexample
exampleisisthe
theString
Stringclass
classfinal.
final.

7.1 CONSIDERATIONS
7.1 CONSIDERATIONSABOUT
ABOUTINHERITANCE
INHERITANCE

II will
will conclude
conclude all
all what
what isis said
said about
about interfaces
interfaces and
and inheritance
inheritance with
with aa fewfew remarks.
remarks. Seen
Seen
from the
from the programmer
programmer consists
consists aa program
program ofof classes
classes that
that defines
defines the
the objects
objects used
used by
by the
the
application toto perform
application perform its its work.
work. For For the
the sake
sake ofof maintenance
maintenance ofof the the program
program you you are
are
interested that
interested that these
these classes
classes isis asas loosely
loosely coupled
coupled asas possible,
possible, and
and that
that is,
is, that
that the
the classes
classes
shouldknow
should knowso solittle
littleabout
abouteacheachothers
othersasaspossible.
possible.InInthat
thatway
wayyouyoucancanchange
changethetheclasses
classes
without itit affects
without affects the
the rest
rest ofof the
the program.
program.You You should
should therefore
therefore strive
strive toto write
write the
the classes,
classes,
soaachange
so changeonly
onlyaffects
affectsthe
theclass
classitself
itselfand
andthus
thusonly
onlyhashaslocal
localsignificance.
significance.

Now you
Now you can
can not
not write
write programs
programs without
without there
there are are couplings
couplings between
between the the classes,
classes, the
the
meaning ofof aa class
meaning class isis precisely
precisely that
that itit must
must make
make services
services available
available for
for others
others toto use,
use, but
but
you can
you can ensure
ensure that
that thethe coupling
coupling only
only takes
takes place
place through
through public
public methods.
methods. That’s
That’s why
why II
sometimes have
sometimes have talked
talked about
about data
data encapsulation
encapsulation where where instance
instance variables
variables are
are kept
kept private,
private,
andthus
and thusititbecomes
becomesthe theprogrammer
programmerwho whothrough
throughthe theclass’s
class’spublic
publicmethods
methodsdecides
decideswhich
which
couplings toto be
couplings be possible.
possible. This
This principle
principle cancan be
be further
further supported
supported through
through an an interface
interface ifif
all the
all the classes
classes are
are defined
defined by by an
an interface.
interface. AnAn interface
interface defines
defines through
through abstract
abstract methods
methods
(methodsininan
(methods aninterface
interfaceare areby
bydefault
defaultpublic
publicabstract),
abstract),which
whichcouplings
couplingsshould
shouldbe bepossible,
possible,
andadhere
and adheretotoititandandalways
alwaysdefine
definereferences
referencestotoobjects
objectsusing
usingaadefining
defininginterface,
interface,youyougetget
aalooser
loosercoupling
couplingofofthe theprogram’s
program’scomponents
componentsasasan anobject
objectalone
aloneisisknown
knownasasan aninterface
interface
and the
and the class
class that
that implements
implements the the interface
interface isis not
not known
known andand may
may bebe changed
changed without
without
itit affects
affects the
the rest
rest ofof the
the program.
program. Therefore,
Therefore, itit isis aa design
design principle
principle that
that that
that you
you should
should
programtotoan
program aninterface.
interface.

130
130
JAVA 3: OBJECT-ORIENTED PROGRAMMING A last note about classes

To program to an interface is a good design principle, but everything can be overstated.


A program can easily consist of several hundred classes, and if each (or most) of these
classes defines an interface, the number of types will be huge and may lead to code that is
difficult to grasp. One should therefore consider, when a class must define an interface and
concerning primary classes, which represent key concepts in which there is a chance that
there will be changes. A program will always consist of many classes that are using other
classes that are local in nature, and these classes should not be defined with an interface.
The upshot is that programming to an interface is an important principle and one of the
best ways to secure loose couplings between parts of the program, but also that, while
developing consider whether an interface makes sense.

Another use of interfaces is that using interfaces at design time you can define different
contracts that the program’s objects must comply. As a class can implement multiple interfaces
(all of them you need), you can create objects that meet multiple contracts, and as some of
the most important thing you can test whether an object meets one or the other contract.
With reference to the previous chapters, an object defined Cloneable abide by the contract,
that it can create a copy of itself. Another interface is called Comparable, and classes that
implements this interface, instantiates objects that can be arranged in order and hence, for
example be sorted. Java defines a number of such interfaces, which defines one or another
property that an object may have. You will later in the book Java 4 about collection classes
face classes that implements many interfaces. An interface is a concept that defines contracts
which objects must comply.

If you look at the interfaces defined in this book, they reflect very closely the classes that
implements these interfaces. It does absolutely not necessarily be the case, and many interfaces
define a contract in form of a few and perhaps only a single method.

131
JAVA 3: OBJECT-ORIENTED PROGRAMMING A last note about classes

With regard of inheritance one can say that there are two uses. In one situation you have
some classes which are similar, such that they somewhat are comprised of the same variables
and methods. In such a situation you can take what the classes have in common, and move
it into a common base class, that the others inherits. That way, you avoid the same code
can be found in several places and thus have a program that takes up less space, but the
important thing is that if you have to change the code, you should only change it at one
place, and you are sure that you do not forget to change somewhere. The second situation
is that you have defined a concept in the form of a class, and then you need a different
concept, similar to the first but might need an extra variable or method, or there may be a
method that should work on another way. In this case, the new concept can be defined as
a class that inherits the first class. The two situations are really two sides of the same coin,
but in the first case we speak of generalization, while in the second case, wee talk about
specialization. Whatever’s inheritance reflects the fact that a program consists of classes that
have something in common and to model concepts of the same kind, and may be useful
to define a hierarchy of classes that inherit each other.

At the design level the implementation of an interface also is a form of inheritance as an


interface says that an object satisfies a particular contract. Because Java only supports linear
inheritance, interfaces help during the design to work with multiple inheritance.

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

132
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING A
a last
last note
note about
about classes
Classes

The
The most most important
important of of inheritance
inheritance isis not
not so so much
much the
the expansion
expansion of
of existing
existing code
code (although
(although
itit isis of
of course
course also
also important),
important), but
but itit isis the
the relationship
relationship between
between super
super class
class and
and subclass.
subclass.
If
If you
you have
have aa specialization
specialization

(and
(and here
here itit isis not
not so
so important,
important, ifif A
A isis aa class
class or
or an
an interface),
interface), itit isis important
important that
that aa BB isis
also
also an
an AA and
and aa BB anywhere
anywhere can
can be
be treated
treated in in the
the same
same way
way as
as an
an A. A. It It means
means that
that you
you can
can
write
write aa method
method and and thus
thus code
code which
which treats
treats anan AA object:
object:

type metode(A a)
{
}

and
and the
the method
method will
will work
work regardless
regardless of
of whether
whether thethe parameter
parameter isis an
an AA object
object or
or BB object
object
or
or another type that directly or indirectly inherits A. The method does not know the
another type that directly or indirectly inherits A. The method does not know the
specific type, and it does not have to do it. It is called polymorphism and is one of
specific type, and it does not have to do it. It is called polymorphism and is one of the mostthe most
important
important concepts
concepts inin object-oriented
object-oriented programming
programming and and allows
allows you
you toto write
write program
program code
code
that is very flexible and general.
that is very flexible and general.

Inheritance
Inheritance isis one
one of of the
the basic
basic principles
principles behind
behind object-oriented
object-oriented programming
programming and and more
more
than that, for it is a requirement that an object-oriented programming
than that, for it is a requirement that an object-oriented programming language supports language supports
inheritance.
inheritance. However,
However, itit isis notnot the
the solution
solution to
to everything,
everything, and and there
there isis also
also criticism
criticism of
of
inheritance. Taking the above design where B inherits A, it reflects
inheritance. Taking the above design where B inherits A, it reflects a strong connection a strong connection
and
and itit especially
especially ifif AA defines
defines protected
protected members.
members. There
There isis aa high
high probability
probability that
that changes
changes inin
AA will have an impact on derived classes. Moreover, one can mention
will have an impact on derived classes. Moreover, one can mention that the connection that the connection
between
between AA andand BB isis veryvery static
static and
and determined
determined atat compile-time.
compile-time. Sometimes
Sometimes one one thinks,
thinks,
therefore, on a design
therefore, on a design as as

wherein
wherein an an object
object BB knows
knows an an AA object
object through
through aa reference.
reference. Here
Here reference
reference can
can be
be replaced
replaced
at
at runtime, providing the opportunity to the object B that it can refer to another A object,
runtime, providing the opportunity to the object B that it can refer to another A object,
and
and the result is a code that is more flexible. One speaks sometimes that B delegate tasks
the result is a code that is more flexible. One speaks sometimes that B delegate tasks
to
to the A object. The two design principles are not directly each other alternatives, but in
the A object. The two design principles are not directly each other alternatives, but in
the last years there has probably been briefed on using delegation in situations
the last years there has probably been briefed on using delegation in situations where you where you
would
would previously
previously use
use of
of inheritance.
inheritance.

133
133
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Aalast
lastnote
noteabout
aboutclasses
Classes

PROBLEM
PROBLEM33
InInthis
thistask,
task,you
youmust
mustwrite
writesome
someclasses
classesthatthatare
areorganized
organizedininaahierarchy.
hierarchy.The
Theclasses
classesare
are
simple
simpleandandrepresent
representgeometric
geometricobjects,
objects,triangles
trianglesandandsquares,
squares,and
andtotothe
theextent
extentthat
thatthere
there
isisaaneed
needfor
formathematical
mathematicalformulas,
formulas,ititisissimple
simpleformulas,
formulas,which
whichareareknown
knownfrom
fromprimary
primary
school.
school.TheThegoal
goalisistotoshow
showmany
manyofofthe
theconcepts
conceptsofofclasses
classestreated
treatedininthis
thisbook.
book.

Start
Start by
by creating
creating aa NetBeans
NetBeans project,
project, you
you can
can call
call Geometry.
Geometry. The
The example
example treates
treates asas
mentioned
mentionedgeometric
geometricshapes,
shapes,but
butyou
youshould
shouldonly
onlybebeinterested
interestedininaashape’s
shape’sperimeter
perimeterand
and
area.
area.Correspondingly,
Correspondingly,aashape
shapecan
canbebedefined
definedasasfollows:
follows:

package geometry;

/**
* Defines a geometrical shape.
*/
public interface IShape
{
/**
* @return The circumference of the shape
*/
public double perimeter();

/**
* @return The area of the shape
*/
public double area();
}

andyou
and youneed
needtotoadd
addthis
thisinterface
interfacefor
foryour
yourproject.
project.You
Youmust
mustthen
thenadd
addananauxiliary
auxiliaryclass
class
thatshould
that shouldbe
becalled
calledPoint
Pointand
andrepresents
representsaapoint
pointininaaplane
planecoordinate
coordinatesystem:
system:

package geometry;

public class Point


{
public static final double ZERO = 1.0e-20; // represents zero

private double x;
private double y;
public Point(double x, double y)
{
this.x = x;
this.y = y;
}

134
134
JAVA 3: OBJECT-ORIENTED PROGRAMMING A last note about classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING a last note about Classes

public double getX()


{
return x;
}

public double getY()


{
return y;
}

public double length(Point p)


{
return Math.sqrt(sqr(x – p.x) + sqr(y – p.y));
}

360°
public String toString()
{

.
return String.format("(%.4f, %.4f)", x, y);
}

thinking

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


135
135
JAVA 3: OBJECT-ORIENTED PROGRAMMING A last note about classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING a last note about Classes

public boolean equals(Object obj)


{
if (obj == null) return false;
if (getClass() == obj.getClass())
{
Point p = (Point)obj;
return Math.abs(x – p.x) <= ZERO && Math.abs(y – p.y) <= ZERO;
}
return false;
}

public static double sqr(double x)


{
{{return x * x;
return xx ** x;
} return x;
} }}
}}

Regarding the method length(), note that given two points (x , y ) and (x , y ) you determines
(𝑥𝑥11, 𝑦𝑦𝑦𝑦𝑦𝑦1111) and
Regarding the method length(), note that given two points (𝑥𝑥𝑥𝑥 22 (𝑥𝑥22, 𝑦𝑦𝑦𝑦𝑦𝑦2222) 2you
(𝑥𝑥𝑥𝑥
2
determines the
the distance between the points as:
distance between the points as:

√(𝑥𝑥11 − 𝑥𝑥𝑥𝑥𝑥𝑥22 )22 + (𝑦𝑦𝑦𝑦


√(𝑥𝑥𝑥𝑥 (𝑦𝑦11 − 𝑦𝑦𝑦𝑦𝑦𝑦22 )22

Also note that the class has a static method sqr() which returns the square of a number. In principle,
Also note that the class has a static method sqr() which returns the square of a number.
such a method does not have to do with a point and is also just an auxiliary method to implement
In principle, such a method does not have to do with a point and is also just an auxiliary
length(), but because it may be useful in other contexts, it is defined as a static public method.
method to implement length(), but because it may be useful in other contexts, it is defined
as a static
Write publicclass
an abstract method.
Shape that implements the interface in IShape. The class should only overrides
the method equals(), such two shapes are the same, if the objects has the same class, and if the two
Write an
shapes abstract
have class
the same Shape and
perimeter thatarea.
implements the interface in IShape. The class should only
overrides the method equals(), such two shapes are the same, if the objects has the same
The
class,next
andclass willtwo
if the represent
shapesa concrete
have thegeometric shape. Theand
same perimeter class should be named Ellipse and must
area.
represents an ellipse, when an ellipse is solely defined by the two radi that are transferred as
parameters to the constructor:
The next class will represent a concrete geometric shape. The class should be named Ellipse
The next class will represent a concrete geometric shape. The class should be named Ellipse
and must represents an ellipse, when an ellipse is solely defined by the two radi that are
transferred as parameters to the constructor:

You can calculate the ellipse's perimeter and area on the basis of the following formulas:

𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 = 𝑎𝑎𝑎𝑎𝑟𝑟11𝑎𝑎𝑎𝑎𝑟𝑟22𝜋𝜋𝜋𝜋
𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 𝜋𝜋

𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝
𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑝𝑝𝑝𝑝 2𝜋𝜋√0.5(𝑟𝑟1122 + 𝑎𝑎𝑎𝑎𝑟𝑟2222 )
𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 = 2𝜋𝜋𝜋𝜋√0.5(𝑎𝑎𝑎𝑎

With the ellipse in place, you can write a class Circle, representing a circle when a circle is simply an
ellipse where the two radi are equal. The class Circle can be written as a class that inherits Ellipse.

136
136Start with a class Polygon, which can represent an
As a next step, yot should write classes to triangles.
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Aalast
lastnote
noteabout
aboutclasses
Classes

You
You
You can
Youcan
can
can calculate
calculate the
calculate
calculate the
thethe ellipse’s
ellipse's
ellipse’s
ellipse's perimeter
perimeter and
perimeter
perimeter and
andarea
and
area area
ononthe on
onthe
thebasis
area basis basis
ofofthe
the ofofthe
following
basis
the following
followingformulas:
theformulas:
following formulas: formulas:

𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎==𝑟𝑟1𝑎𝑎𝑎𝑎𝑟𝑟12𝑎𝑎𝑎𝑎𝜋𝜋
𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 2 𝜋𝜋𝜋𝜋
2 22
𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝
𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑝𝑝𝑝𝑝𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎==2𝜋𝜋√0.5(𝑟𝑟1 12++𝑟𝑟2𝑎𝑎𝑎𝑎2)
2𝜋𝜋𝜋𝜋√0.5(𝑎𝑎𝑎𝑎 )

With
With the
the ellipse
ellipse ininplace,
place, you
you can
canwrite
awrite a class
classCircle, representing aacircle when isisasimply
circleanis
With
With the
theellipse
ellipse ininplace,
place,you
youcan
canwrite
write classaCircle,
aclass Circle, Circle, representing
representing
representing a acircle
circlewhen circle
when when
a acircle
circle asimply
circle anis
simply
ellipse
simply
ellipse an
anellipse
where
where the
thetwo
ellipse
twowhere
radi
where the
radiare
arethetwo
equal.
two
equal. radi
Theradi
The are
class
are
class equal.
Circle can
equal.
Circle The
canThe class
classCircle
bebewritten
writtenas can
asa aclass
Circle class bebeinherits
that
canthat written
written
inherits asasaaclass
Ellipse.
Ellipse. class
that
thatinherits
inheritsEllipse.
Ellipse.
As
Asa anext
nextstep,
step,yot
yotshould
shouldwrite
writeclasses
classestototriangles.
triangles.Start
Startwith classPolygon,
witha aclass Polygon,which
whichcan
canrepresent
representanan
arbitrary
arbitrary
AsAsaanext polygon.
nextpolygon.
step, ItItcan
step,yot can beberepresented
yotshould
should represented
write
writeclasses byPoint
by
classes Point
to objects
objectsthat
totriangles.
triangles. that
Start are
Startarethe
withthepolygon's
with apolygon's
aclass vertices.
vertices.
classPolygon,
Polygon, The
Theclass
which
which class
can
can
should
should not
representnotvalidate
validatethe
thecorners
corners and
and test
testwhether
whether they
they lead
leadtotoirregular
irregularpolygons,
polygons, for
forexample
example polygons
polygons
representan anarbitrary
arbitrarypolygon.
polygon.ItItcan canbeberepresented
representedby byPoint
Pointobjects
objectsthat
thatare
arethe
thepolygon’s
polygon’s
where
wheresides
sidesintersect.
intersect.AApolygon
polygoncancanbebewritten
writtenasasthe
thefollowing
followingclass:
class:
vertices.
vertices.The
Theclass
classshould
shouldnot
notvalidate
validatethe
thecorners
cornersand
andtest
testwhether
whetherthey
theylead
leadtotoirregular
irregular
polygons,
polygons,
package for
for example polygons where sides intersect. A polygon can be written asas the
example
geometry; polygons where sides intersect. A polygon can be written the
package geometry;
following
followingclass:
class:
public
publicabstract
abstractclass
classPolygon
Polygonextends
extendsFigur
Figur
{{
package geometry;p;
protected
protectedPunkt[]
Punkt[] p; //
//polygonens
polygonenshjørner
hjørner

public
publicPolygon(Punkt
public Polygon(Punkt
abstract ...
class p)
...Polygon
p) extends Figur
{{
{
protected Punkt[] p; // polygonens hjørner
92
92
public Polygon(Punkt … p)
{
this.p = p;
}
public double omkreds()
{
double sum = p[p.length – 1].length(p[0]);
for (int i = 1; i < p.length; ++i) sum += p[i – 1].length(p[i]);
return sum;
}

public String toString()


{

}
}

Knowing
Knowing the
the vertices,
vertices, you
you can
can immediately
immediately implements
implements the
the method
method perimeter()
perimeter() asas the
the
circumference can be determined as the sum of the lengths of the edges. However,
circumference can be determined as the sum of the lengths of the edges. However, you can you can
not
notimmediately
immediatelyimplement
implementthe themethod
methodarea(),
area(),and
andthe
theclass
classisistherefore
thereforedefined
definedabstract.
abstract.

137
137
}

Knowing the vertices, you can immediately implements the method perimeter() as the circumference
can be
JAVA determined as thePROGRAMMING
3: OBJECT-ORIENTED sum of the lengths of the edges. However, you note
A last can not immediately
about classes
implement the method area(), and the class is therefore defined abstract.

Next, write a class Triangle, which must be a class that inherits Polygon. The class must have
Next, write a class Triangle, which must be a class that inherits Polygon. The class must have a
aconstructor
constructor that has three points as parameters, and apart from the constructor the class
that has three points as parameters, and apart from the constructor the class alone has to
alone hasthetotoString()
override overrideand
theimplement
toString()the
andmethod
implement
area(). the methodthearea().
Regarding Regarding
last you the last
can determine the
you can determine the area of a triangle with
area of a triangle with sides a, b and c as follows: sides a, b and c as follows:

2
𝑎𝑎2 + 𝑏𝑏 2 − 𝑐𝑐 2
𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 = ½𝑎𝑎𝑎𝑎√1 − ( )
2𝑎𝑎𝑎𝑎

In the
In theinterest of of
interest other classes
other the area
classes the calculation should be
area calculation done be
should by means of using
done by meansa public static
of using a
method that has as parameters has the triangle's vertices.
public static method that has as parameters has the triangle’s vertices.

The class Triangle represents an arbitrary triangle defined by three points. You can also have more
The class Triangle represents an arbitrary triangle defined by three points. You can also have
specialized classes for the triangles, such as Equilateral class representing an equilateral triangle,
more
which specialized
should be aclasses
class for
thatthe triangles,
inherits such Triangle.
the class as Equilateral class representing
The class's an equilateral
constructor must have one
triangle, which should be a class that inherits the class Triangle. The class’s constructor
parameter that is the side length (note that it is easy to define three points which form the vertices in a
must have
triangle withone parameter
a certain that is -the
side length startside
withlength (note(0,0)).
the point that For
it isperformance
easy to define threethepoints
reasons class
should override
which methodinperimeter(),
form thethevertices a triangle since
with ita can be implemented
certain side lengthmore effectively
– start with theif point
you know the
(0,0)).
side length.
For Write the
performance class Equilateral.
reasons the class should override the method perimeter(), since it can be
implemented more effectively if you know the side length. Write the class Equilateral.
Write similar to a class RightAngled that represents a right angled triangle.

As the last shapes you should write some classes to squares. Start with a class GeneralSquare, which
inherits the class Polygon. The class must have a constructor, which parameters are four Point objects.
Furthermore the the class must implements the method area(), which is abstract in the base class.
There is no general formula to determine the area of a general square, but you draw a diagonal, that
divides the square into two triangles (because I ignore the problem that a square may be concave). You
can therefore implement the method area() by determining the area of the two triangles.

You must then write a class Rectangle, which inherits the class GeneralSquare when the class's
We will turn your CV into
an opportunity of a lifetime
93

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

138
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Aalast
lastnote
noteabout
aboutclasses
Classes

Write
Writesimilar
similartotoa aclass
classRightAngled
RightAngledthat
thatrepresents
representsa aright
rightangled
angledtriangle.
triangle.

AsAsthe
thelast
lastshapes
shapesyouyoushould
shouldwrite
writesome
someclasses
classestotosquares.
squares.Start
Startwith
witha aclass
classGeneralSquare,
GeneralSquare,
which
whichinherits
inheritsthe
theclass
classPolygon.
Polygon.The
Theclass
classmust
musthavehavea aconstructor,
constructor,which
whichparameters
parametersare are
four
fourPoint
Pointobjects.
objects.Furthermore
Furthermorethe thethetheclass
classmust
mustimplements
implementsthethemethod
methodarea(),
area(),which
which
isisabstract
abstractininthe
thebase
baseclass.
class.There
Thereisisno
nogeneral
generalformula
formulatotodetermine
determinethethearea
areaofofa ageneral
general
square,
square,butbutyou
youdraw
drawa adiagonal,
diagonal,that
thatdivides
dividesthe
thesquare
squareinto
intotwo
twotriangles
triangles(because
(becauseI Iignore
ignore
the
theproblem
problemthatthata asquare
squaremaymaybebeconcave).
concave).YouYoucancantherefore
thereforeimplement
implementthe themethod
methodarea()
area()
bybydetermining
determiningthe thearea
areaofofthe
thetwo
twotriangles.
triangles.

You
Youmust
mustthen
thenwrite
writea aclass
classRectangle,
Rectangle,which
whichinherits
inheritsthe
theclass
classGeneralSquare
GeneralSquarewhen
whenthetheclass’s
class’s
constructor
constructorhas
hastwo
twoparameters
parametersthat thatrespectively
respectivelyare
arethe
thewidth
widthand andheight.
height.Also,
Also,write
writea aclass
class
Square
Squarewhen
whena asquare
squarejust
justisisa arectangle
rectanglewhere
wherethethesides
sidesare
areofofequal
equallength.
length.

You’ve
You’vewritten
writtensome
someclasses
classesthat
thatrepresents
representsgeometric
geometricobjects,
objects,and
andyou
youmust
mustnow
nowdefine
definea a
composite
compositeshape,
shape,which
whichconsists
consistsofofother
othershapes.
shapes.The
Thefollowing
followinginterface
interfaceinherits
inheritsIShape
IShape
and
anddefines
definesa acomposite
compositeshape
shapecalled
calleda aIDrawing:
IDrawing:

package geometri;

public interface IDrawing extends IShape


{
public void add(IShape … shape) throws Exception;
}

Write
Writea aclass
classDrawing
Drawingthat
thatimplements
implementsthis
thisinterface
interfacewhen
whenthe
thecircumference
circumferenceofofa adrawing
drawingisis
defined
definedasasthe
thesum
sumofofthe
theperimeters
perimetersofofallallthe
thedrawing’s
drawing’sshapes
shapesand
andthe
thesame
sameforforthe
thearea.
area.

AAdrawing
drawingisistherefore
thereforeespecially
especiallyananIShape,
IShape,and
andthus
thusa adrawing
drawingcontains
containsother
otherdrawings.
drawings.
Below is a test program that creates a drawing that consists
Below is a test program that creates a drawing that consists of of

1.
1.a adrawing
drawingthat
thatcontains
containsa acircle,
circle,a aequilateral
equilateraland
anda arectangle
rectangle
2. a right angled triangle
2. a right angled triangle
3.
3.a adrawing
drawingthat
thatcontains
containsa asquare
squareand andtwo
twocircles
circles

package geometry;

public class Geometry


{
public static void main(String[] args)
{

139
139
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Aalast
lastnote
noteabout
aboutclasses
Classes
JAVA 3: OBJECT-ORIENTED PROGRAMMING a last note about Classes

print(create(create(new Circle(2), new Equilateral(3), new Rectangle(3, 4)),


print(create(create(new Circle(2), new Equilateral(3), new Rectangle(3, 4)),
new RightAngled(3, 4), create(new Square(5), new Circle(1), new Circle(3))));
new RightAngled(3, 4), create(new Square(5), new Circle(1), new Circle(3))));
}
}
private static void print(IShape shape)
private static void print(IShape shape)
{
{
System.out.println(shape);
System.out.println(shape);
System.out.println("Perimeter: " + shape.perimeter());
System.out.println("Perimeter: " + shape.perimeter());
System.out.println("Area: " + shape.area());
System.out.println("Area: " + shape.area());
}
}
private static IShape create(IShape … shapes)
private static IShape create(IShape … shapes)
{
{
IDrawing d = new Drawing();
IDrawing d = new Drawing();
try
try
{
{
d.add(shapes);
d.add(shapes);
}
}
catch (Exception ex)
catch (Exception ex)
{
{
System.out.println(ex.getMessage());
System.out.println(ex.getMessage());
}
}
return d;
return d;
}
}
}
}
Test
Testthe
theprogram.
program.The
Theresult
resultshould
shouldbe
besomething
somethinglike
likethe
thefollowing:
following:
Test the program. The result should be something like the following:
Start drawing
Start drawing
Start drawing
Start drawing
Circle, r = 2,00000000
Circle, r = 2,00000000
Equilateral: 3
Equilateral: 3
Rectangle: width = 3.0, height = 4.0
Rectangle: width = 3.0, height = 4.0
End drawing
End drawing
Right angled triangle with kateters: 3.0 and 4.0
Right angled triangle with kateters: 3.0 and 4.0
Start drawing
Start drawing
Square, side 5.0
Square, side 5.0
Circle, r = 1,00000000
Circle, r = 1,00000000
Circle, r = 3,00000000
Circle, r = 3,00000000
End drawing
End drawing
End drawing
End drawing
Perimeter: 92.69911184307752
Perimeter: 92.69911184307752
Area: 90.87941146728707
Area: 90.87941146728707
The
Thetypes
typesofofthis
thistask
taskisisorganized
organizedininaaclass
classhierarchy
hierarchyand
andcancanbebeillustrated
illustratedasasshown
shownbelow.
below.
The
It’s types of this task is organized in a class hierarchy and can be illustrated as shown below.
It’ssimple
simpletotoexpand
expandthe theclass
classhierarchy
hierarchywith
withnew
newclasses,
classes,including
includingclasses
classesfor
fornew
newshapes,
shapes,
It’s
andsimple to expand the class hierarchy with new classes, including classes for new shapes,
and as long as these classes complies with the contract IShape, the class Drawing canuse
as long as these classes complies with the contract IShape, the class Drawing can use
and
theseas classes
long asasthese
it classesnothing
knows complies withthe
about theconcrete
contractclasses.
IShape, the class Drawing can use
these classes as it knows nothing about the concrete classes.
these classes as it knows nothing about the concrete classes.

140
140
140
JAVA 3: OBJECT-ORIENTED PROGRAMMING A last note about classes

AXA Global
Graduate Program
Find out more and apply

141
JAVA 3: OBJECT-ORIENTED PROGRAMMING A last note about classes

7.2 THE COMPOSITE PATTERN


In fact it is quite often that, in practice, you meat a situation similar to above and think
for example on a part list where you have a product that is composed of subcomponents,
or think of a menu where a menu consisting of menu items or other menus. Another
example is a filesystem consisting of directories and files. Therefore, it is natural to express
the situation in a design pattern called a composite pattern.

The problem is thus to manipulate a hierarchy of objects, where the bottom of the hierarchy
have some concrete objects that we call the leaf objects, and there are some other objects
that we call composite objects consisting of leaf objects and other composite objects. Both
leaf objects and composite objects have a common base class (and possibly it is an interface
or an abstract class), and the idea is that composite objects treat their child objects alike,
whether in the case of leaf or composite objects. The solution is illustrated with a figure as
shown below and the solution is referred as a composite pattern.

In practice, there may be different flavors, and often there may be several kinds of leaf objects
that all are part of a hierarchy. This is the case in the above example with geometric shapes.
Here, the Component class corresponds to the interface IShape, and the class Leaf corresponding
to Shape. In the figure below corresponds the class Composite to IDrawing. In principle, it is a
very simple pattern, but in practice there are still some considerations on how to implements
the pattern. The goal is as mentioned that the Leaf and the Composite objects must have the
same behavior, and therefore the methods addComponent() and removeComponent() is defined
in Component. It provides, however, a problem since they do not make sense for Leaf objects.
Where necessary, they must in Leaf classes be implemented as methods that do not perform
anything and possible raises an exception. If you instead uses a design as shown above, it
then is necessary to test whether specific objects are Leaf or Composite objects.

142
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

8 FINAL
8 Final EXAMPLE
example
As a conclusion of this book, I will write a program that can evaluate matheatical expressions.
As a conclusion of this book, I will write a program that can evaluate matheatical expressions. The
The user should
user should be ablebetoable
entertoa enter a mathematical
mathematical expressionexpression
that dependthat
on depend on one
one or more or more
variables, for
variables,
example: for example:

2 ∗ sin(𝑥𝑥0) + 𝑠𝑠𝑞𝑞𝑞𝑞𝑞𝑞(5 ∗ 𝑥𝑥1 + 3)

that depends
that dependsonontwo variables.
two Then
variables. the the
Then useruser
should enter enter
should valuesvalues
for thefor
expression's variables
the expression’s and the
variables
program should then evaluate the expression for these variables.
and the program should then evaluate the expression for these variables.
If there is an error:
If there is an error:
– the user has entered an expression that is not syntactically correct
– --the
theuser
user
hashas entered
entered an expression
arguments that are notthat
legalis compared
not syntactically correct
to the current expression
– --anthe
error occurs
user when thearguments
has entered expression that
is evaluated
are not legal compared to the current expression
-- an error occurs when the expression is evaluated
the program must show an appropriate error message.
the program must show an appropriate error message.
In the example above the expression includes sine and square root. The program should support the
most common mathematical functions somewhat similar to what applies for a mathematical calculator,
In
andthe
it is example above
a desire that the be
it should expression includes
easy to extend sine and
the program withsquare root. The
new functions, program
if the should
need arises.
support the most common mathematical functions somewhat similar to what applies for
aThe
mathematical
program mustcalculator, and ituser
have a graphical is ainterface
desire where
that ityou
should be easy
can enter to extend
expressions and the program
values for the
variables.
with newWith regard toif expressions
functions, there are following requirements:
the need arises.

An expression
Theprogram is not
must have case sensitive,
a graphical userand it should
interface not matter
where you canwhether
enteryou write in lowercase
expressions or
and values
for the uppercase.
variables. With regard to expressions there are following requirements:
 An expression may contain any number of variables, referred to as x0, x1, x2, ..., that is an x
followed by a non-negative integer or number.
-- An expression is not case sensitive, and it should not matter whether you write in
 Numbers is always entered with dot as decimal point.
lowercase or uppercase.
 An expression must support the four common arithmetic operators +, -, * and /.
-- An expression may contain any number of variables, referred to as x0, x1, x2, …,
 It should be allowed to use parentheses in any number of levels.
 Ifthat is an x followed
a mathematical functionby
hasa several
non-negative integer
arguments, or number.
they must be separated by comma.
-- Numbers is always entered with dot as decimal point.
-- An expression must support the four common arithmetic operators +, -, * and /.

8.1--Analyse
It should be allowed to use parentheses in any number of levels.
-- If a mathematical function has several arguments, they must be separated by comma.
The above can be seen as the requirements for the program. It is always the starting point for a sofware
development project, but before you can address the development of the program it is the typical
needed to clarify uncertainties or boundaries. This is also true in this case where it is necessary to
clarify which functions the program exactly must support and how the user interface should be.

A mathematical function is identified by a name and then it can be followed by a parameter list in
parentheses. In an expression, it must be possible to use the following functions:

97
143
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

8.1 ANALYSE
The above can be seen as the requirements for the program. It is always the starting point
for a sofware development project, but before you can address the development of the
program it is the typical needed to clarify uncertainties or boundaries. This is also true in
this case where it is necessary to clarify which functions the program exactly must support
and how the user interface should be.

A mathematical function is identified by a name and then it can be followed by a parameter


list in parentheses. In an expression, it must be possible to use the following functions:

-- constant functions (functions without parentheses)


-- pi
-- e
-- functions in 1 variable
-- sin cot sqr
-- asin acot sqrt
-- cos ln abs
-- acos exp frac
-- tan log floor
-- atan antilog

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

144
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

-- functions in 2 variables
-- pow
-- root

To define the application user interface I has created a NetBeans project named Calc. The
project creates a prototype, which is a simple application that opens the following window:

That it is a prototype only means that it is a program that is not doing anything. The
buttons have no function, but it can be a good place to start the development of a program
to clarify what it’s all about. First, it is relatively quickly to develop such a program, and
partly to the prototype can be presented to the future users, where it can be a useful tool
to clarify that the task is understood correct.

In this case it is decided, that the program should be able to work with 20 variables, that the
program must have an input field for entering an expression and a list box for the results.

145
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

AN EXPRESSION

Exactly an expression can be described with the following syntax diagrams:

146
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

An argument can start with one or more sign characters (plus or minus). Then there are
four options

1. const, that always must be a non-negative number – a string that can be converted
to a double
2. var, that is a variable and then a string at format Xn, where n is an index
3. function, that is a mathematical function
4. an expression in parentheses

What remains is to define what a function is, and it appears from the above.

The value of an expression must always be a double.

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
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

147
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

8.2 DESIGN
An expression must be represented by a class named Expression. In principle, it is a very
simple class, that in addition to a constructor simply consists of a single method that returns
from arguments the expression’s value:

Here it is the constructor, that is complex since, as parameter it has the expression as a string,
and it is accordingly the constructor’s task to split the string up into tokens and validate
whether these tokens represents a legal expression. A token is an item that can be included
in an expression, and a token is a substring such as cos, + and a number. According to the
above syntax diagrams and associated comments there are following tokens

+ addition or sign - subtraction or sign * multiplication

/ division ( left parenthesis ) right parenthesis

, argument separator sin sinus asin arc sinus

cos cosinus acos arc cosinus tan tangens

atan arc tanges cot cotangens acot arc cotangens

ln natural logarithm exp exponential function log logarithm 10

alog antilog sqr square function sqrt square root

pow power of root root of abs absolut value

frac fraction floor interger part pi the constant pi

e the constant e

xn a variable that start with x and is follwed en non-negative integer

num a number that is a non-negative decimal number with . as decimal point

148
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

This can result in 30 different tokens – and indeed 31 as plus or minus especially can be a
sign. The different tokens has to be treated different, but can be arranged into groups with
common properties, and as such, I will define the following class hierarchy, where each
token is defined by a class:

149
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

It is very simple classes, and as an example is SinToken a class that represents a sine function.
The class is derived from FuncToken, and the class has only two properties, where the first
returns the number of arguments, while the second determines the function’s value from
a single argument:

The constructor in the class Expression must perform three operations:

-- Scanning the expression which means that the string should be split into the tokens
that the expression consists of.
-- Parsing the expression that means to control that the expression’s syntax is correct
according to the syntax diagrams.
-- Converting the expression to postfix form, meaning that the expression’s elements
must be reorganized into a sequence of tokens in postfix form.

150
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Final
FInal example
example

To solve the first problem, the parameter string is divided into tokens of the kind defined
above. When the string is divided you have a number of tokens, each of which is a string,
and all these strings must be converted to a Token object.

After the scanning, you have a list of tokens, and parsing has to investigate whether this
list of tokens is in accordance with the syntax rules. It is not simple, but it means to write
a method corresponding to each of the above syntax diagrams.

A STACK

In the book Java 1 I described an ArrayList as an example on a collection class, and I have
used an ArrayList many times since. In the first chapter in this book I mentioned the program
stack as a data structure, where the runtime system store parameters and local variables.
Java also implements a collection class as a stack, and I need that class in the following,
and therefore little about what a stack is.

It is as an ArrayList a container, that can store objects of a particular type of, but it is a
very simple data structure with only two importen operations:

1.
1. push that put an object on the stack (store a value at the top of the stack)
2.
2. pop that returns an remove the object on the top of the stack

It is as such a LIFO data structure, where the object that is removed from a stack is the last
object, that is put on the stack. In Java a stack also has other operation, and as an exampel
and operation peek, that returns the object on the top of the stack but without remove it.
It means that peek only look at the top of the stack.

As an ArrayList there is no limit om then number of objects a stack can contains.

In Java the type is called Stack, and I uses the type in the program, bul I vil also refer to
a stack below, and therefore this remark.

TO POSTFIX

Usually you write an expression on infix form which means that you writes the operator
between two operands, as for example:

2+3

151
151
JAVA
JAVA 3:
JAVA 3: OBJECT-ORIENTED
3: OBJECT-ORIENTED PROGRAMMING
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING FInal
Final example
FInal example
example

which
which means
which means the
means the sum
the sum of
sum of 2
of 22 and
and 3.
and 3. If
3. If there
If there are
there are several
are several operators,
several operators, we
operators, we need
we need rules
need rules for
rules for how
for how the
how the
the
expression must
expression must be
must be evaluated.
be evaluated. For
evaluated. For example
For example means
example means
means

2
2*3
3+4
4

that you
that
that you first
you first calculate
first calculate the
calculate the product
the product of
product of 2
of 22 and
and 3
and 33 and
and then
and then adds
then adds this
adds this result
this result to
result to 4
to 44 –
–– the
the result
the result
result
isis 10.
10. In
In contrast,
In contrast, means
contrast, means
means

2
2+3
3*4
4

that you
that you first
you first calculates
first calculates the
calculates the product
the product of
product of 3
of 33 and
and 4,
and 4, since
4, since multiplication
since multiplication has
multiplication has higher
has higher precedence
higher precedence
precedence
than addition
than
than addition –
addition –– the
the result
the result is
result isis therefore
therefore 14.
therefore 14. If
14. If you
If you wish
you wish to
wish to suppress
to suppress this
suppress this rule,
this rule, you
rule, you has
you has to
has to
to
use parentheses:
use parentheses:

(2+3)
(2+3) * 4
4

and the
and the expression
the expression has
expression has the
has the value
the value of
value of 20.
of 20.
20.

If in
If
If in an
in an expression
an expression there
expression there are
there are several
are several operators
several operators of
operators of equal
of equal priority,
equal priority, the
priority, the rule
the rule is
rule isis that
that the
that the operators
the operators
operators
are evaluated
are evaluated from
evaluated from left.
from left. Below
left. Below is
Below isis first
first computed
first computed the
computed the sum
the sum of
sum of 2
of 22 and
and 3
and 33 and
and then
and then subtract
then subtract 4
subtract 44
because addition
because addition and
and subtraction
subtraction havehave the
the same
same priority:
priority:

2+3−4
2+3−4

An expression
An
An expression may
expression may be
may be more
be more complex,
more complex, for
complex, for example
for example
example

(1+2
(1+2 ** (3+4))(⁄(5+6)
(3+4))(⁄(5+6) ** 7)
7)

where there
where there are
there are parentheses
are parentheses within
parentheses within the
within the parentheses.
the parentheses. The
parentheses. The value
The value of
value of the
of the expression
the expression is
expression isis 0.194805.
0.194805.
0.194805.
When an
When an expression
an expression contains
expression contains parentheses,
contains parentheses, the
parentheses, the parentheses
the parentheses are
parentheses are evaluated
are evaluated first,
evaluated first, starting
first, starting with
starting with
with
the innermost
the
the innermost parentheses.
innermost parentheses. It
parentheses. It is
It isis certainly
certainly possible
certainly possible to
possible to write
to write aaa method
write method that
method that does
that does it,
does it, but
it, but if
but ifif the
the
the
expression becomes
expression becomes more
more complex
complex with with mathematical
mathematical functions
functions andand many
many parentheses,
parentheses, itit
isis not
not simple,
simple, and
and therefore
therefore one one will
will typically
typically convert
convert the
the expression
expression to
to postfix
postfix form.
form. This
This
means that
means that an
an operator
operator isis written
written after
after the
the operands.
operands. Thus,
Thus, the
the above
above expression’s
expression’s isis written
written as as

2
233+ +
2
2 3 ** 4
4++
234*+ +
23+4*
2
233++4 4–

1234+*+56+7*/

152
152
152
JAVA3:3:OBJECT-ORIENTED
JAVA OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Finalexample
FInal example

IfIffor
forexample
exampleyou
youmust
mustcalculate
calculatethe
thevalue
value, ,you
youhave
havea alist
listofoffive
fivetokens,
tokens,and
andyou
youevaluates
evaluates
theexpression
the expressionbybytraversing
traversingthe
thelist
listfrom
fromleft
lefttotoright,
right,andandevery
everytime
timeyou
youencounters
encountersanan
operatorititacts
operator actson
onthe
thetwo
twooperands
operandspreceding:
preceding:

23*4+
64+
10

The
Theideaideaisisthat
thatany
anyexpression
expressioncancanbebewritten
writtenininpostfix
postfixform
formwithout
withoutusing
usingofofparentheses.
parentheses.
When
Whenthe theexpression
expressionshould
shouldbebeevaluated,
evaluated,ititisistraversed
traversedjust
justfrom
fromleft
lefttotoright.
right.Every
Everytime
time
you
you come to an operand, put it on a stack. Is it an operator you pop the stack twice(if(if
come to an operand, put it on a stack. Is it an operator you pop the stack twice
ititisisan
anoperator
operatorwithwithtwo
twoarguments)
arguments)calculates
calculatesthe theresult
resultand
andput
putititon
onthe
thestack.
stack.Finally
Finally
the
thestack
stackwill
willcontain
containonly
onlyone
oneelement
elementwhich
whichisisthe theresult.
result.The
Themethod
methodmay maybased
basedon
onthethe
last
lastofofthe
theabove
aboveexpressions
expressionsbebeisisillustrated
illustratedininthethefollowing
followingmanner:
manner:

44
33 33 77 66 77
22 22 22 22 14
14 55 55 11
11 11
11 77
77
11 11 11 11 11 11 15
15 15
15 15
15 15
15 15
15 15 0.1948
15 0.1948
11 22 33 44 ++ ** ++ 55 66 ++ 77 ** //

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

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.rug.nl/feb/education

153
153
JAVA
JAVA 3:
3: OBJECT-ORIENTED PROGRAMMING
OBJECT-ORIENTED PROGRAMMING Finalexample
FInal example

The
The conclusion is that it is
is much
much easier
easier to
to evaluate
evaluate an
anexpression
expressionininpostfix
postfixform
formthan
thanone
one
in
in infix form and it is therefore
therefore worthwhile
worthwhile to to seek
seekaastrategy
strategy(an(analgorithm)
algorithm)totoconvert
convertanan
expression
expression from infix to postfix
postfix form.
form. ItIt may
may be be done
done inin the
thefollowing
followingmanner
mannerbybyusing
using
aa stack:
stack:

the expresseion is traversed from left and for every tooken


1. if it is a sign push it on the stack
2. if it is a function push it on the stack
3. if it is a variable push it on the stack
4. if it is a number push it on the stack
5. if it is a left parenthes push it on the stack
6. if it is a right parenthes, then pop the stack and add the top
of the stack to the resultat until you get a left parenthes
7. if it is an operator then pop the stack and add the top of the
stack to the resultat as long as the priority of the top of the
stack is less than or equal to the priority of the element, push
the element on the stack
pop the stack and add the top of stack to the
result until the stack is empty

As
As you
you can
can see, it is
see, it is crucial
crucial inin the
the algorithm
algorithm that
that there
thereare
areassigned
assignedthetheright
rightpriorities
prioritiesfor
for
the
the individual tokens. It
individual tokens. It is
is the
the priorities
priorities that
that determine
determine when
whentotomovemovefrom fromthethestack
stacktoto
the
the result,
result, which
which is is just
just aa list.
list. The
The two
two important
important points
pointsininthe
thealgorithm
algorithmare are66andand7.7.IfIf
you
you get
get to
to an
an operator
operator –– forfor example
example aa multiplication
multiplication––you youmust
mustfirst
firstmove
moveeverything
everythingonon
the
the stack
stack with
with aa better
better priority
priority than
than multiplication
multiplication toto the
the result
resultlist.
list.ItItwill
willbebenumbers,
numbers,
variables
variables and
and functions,
functions, andand then
then the
the multiplication
multiplication operator
operatorisisput
puton onthethestack.
stack.

So,
So, if
if the
the expression’s tokens are
expression’s tokens are converted
convertedto topostfix
postfixform,
form,ititisissimple
simpletotoimplement
implementmethod
method
getValue()
getValue() in
in the class Expression.
the class Expression.
So,
So, ifif the
the expression's
expression's tokens
tokens are
are converted
convertedtotopostfix
postfixform,
form,it itis issimple
simpletotoimpl
im
getValue()
getValue()in
inthe classExpression.
theclass Expression.
If
If you
you look
look at the expression
at the expression
If
If you
you look
lookatatthe
theexpression
expression
(1 + 2 * (3 + 4) )⁄( (5 + 6) * 7)
(1++22∗∗(3(3++4)4))⁄)(⁄(5
(1 ( (5++6)6)∗ ∗7)7)

itit can
can be
be converted
converted to
to postfix
postfixititform
can
form in the
can be the following
beinconverted
manner:
totopostfix
following
converted form
formininthe
manner:
postfix thefollowing
followingmanner:
manner:

11
11 22
11 22 33
1 2 3 4 +
1 2 3 4 +
1 2 3 4 + * +
1 2 3 4 + * +
1 2 3 4 + * + 5
1 2 3 4 + * + 5
1 2 3 4 + * + 5 6 +
1 2 3 4 + * + 5 6 +
1 2 3 4 + * + 5 6 + 7 *
1 2 3 4 + * + 5 6 + 7
1 2 3 4 + * + 5 6 + 7 ** /
1 2 3 4 + * + 5 6 + 7 * /
4
3 + +4
( (3 (+ (+
2 ( ( ( (
* * * * * *
1 +
154 +2 +* + * + * + * + * +*
( (1 (+
154
(+ (+ (+ (+ (+ (+ ( +
(( 1( +( 2( *
( (( 3( +( 4( ) ( )
1 + 2 ( 3 + 4 ) )
1 2 3
1 2 3 4 +
1 2 3 4 + * +
1 2 3 4 + * + 5
JAVA 1
3: 2 3 4 + * + 5 6
OBJECT-ORIENTED +
PROGRAMMING Final example
1 2 3 4 + * + 5 6 + 7 *
1 2 3 4 + * + 5 6 + 7 * /

4
3 + +
( ( ( (
2 * * * * * *
1 + + + + + + + +
( ( ( ( ( ( ( ( ( ( /
( 1 + 2 * ( 3 + 4 ) ) /

6
5 + + 7
( ( ( ( * *
( ( ( ( ( ( ( (
/ / / / / / / / /
( ( 5 + 6 ) * 7 )

In this particular task, I will apply the following priorities:

-- numbers, variables 0
-- sign 1
-- function 2
-- multiplication, division 3
-- addition, subtraction 4
-- left parenthes 9
-- right parenthes, comma 99

8.3 PROGRAMMING
As is apparent from the above, the program will consist of many classes corresponding to
the token classes. They are all in the same file, named Tokens that contain a single public
class. It has a single static method called toToken() which, based on a substring representing
the next token, and a Token object for the last token converts the substring to a token. The
class is used by the Expression class as part of the scanning.

The class Expression is as mentioned, a complex class and after the scanning the class has
a list of Token objects. These objects must be parsed to test the syntax of the expression,
and for this purpose must be written a number of methods corresponding to the syntax
diagrams. This methods uses recursion which I will mention below.

After the parsing, the list of tokens must be converted to postfix form, but with the above
algorithm it is relatively simple. You should note, that the conversion needs a stack, that is
a collection class as explained above. The same applies to implements the method getValue(),
that calculates the value of an expression.

155
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final
FInal example

RECURSION

To write the class Expression (the syntax checker) I needs recursion and therefore a few
words about what it is.

A method in a class can be seen as an isolated code that performs a specific operation on
basis of parameters and possible returns a value. The method’s statements, the commands it
executes, can be all possible statements and there are no limitations on what it can be. For
example calling another method, and a method may thus especially also calls the method
itself. If so, wee say that the method is recursive. As an example of a recursive method –
and a method which does not concern the specific program – is shown a method that
determines the factorial of n:

static long factorial(int n)


{
if (n == 0 || n == 1) return 1;
return n * factorial(n – 1);
}

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.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

156
method, and a method may thus especially also calls the method itself. If so, wee say that the method
is recursive. As an example of a recursive method - and a method which does not concern the specific
program - is shown a method that determines the factorial of n:
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

static long factorial(int n)


{
Atifa first
(n ==glance,
0 || nrecursive methods
== 1) return 1; can be hard to figure out, but once you have been
familiar
returnwithn * the principle, -it 1);
factorial(n is not particularly difficult. Above is the principle that if n is
}
0 or 1, you can directly determine the result. If n is greater than 1, one can determine the
factorial of n as n times the factorial of n-1. You can think of it in this way, to determine
At a first glance, recursive methods can be hard to figure out, but once you have been familiar with the
the factorial of n it is reduced to determine the factorial of n-1, which is a smaller a problem
principle, it is not particularly difficult. Above is the principle that if n is 0 or 1, you can directly
than I started
determine with:If To
the result. n isdetermine
greater thanthe factorial
1, one of n. If the
can determine I repeat above
factorial a sufficient
of n as n times thenumber
factorial
of n-1.
times, I get finally to the simple case in which n is 0 or 1 and where I can directly
You can think of it in this way, to determine the factorial of n it is reduced to determine the
determine the result.
factorial of n-1, which is a smaller a problem than I started with: To determine the factorial of n. If I
repeat above a sufficient number of times, I get finally to the simple case in which n is 0 or 1 and
whereprinciple
The I can directly
of a determine
recursivethe result. is that a problem may be divided into two problems:
method
A simple problem which can readily be solved, and a simpler (smaller) problem of the same
The principle of a recursive method is that a problem may be divided into two problems: A simple
kind as the original.
problem which can readily be solved, and a simpler (smaller) problem of the same kind as the original.

Formally, thefactorial
Formally, the factorial
of nofisndefined
is defined as follows:
as follows:

1 𝑓𝑓𝑓𝑓𝑓𝑓 𝑛𝑛 = 0 or 𝑛𝑛 = 1
𝑛𝑛! = { }
𝑛𝑛 ⋅ (𝑛𝑛 − 1)! 𝑓𝑓𝑓𝑓𝑓𝑓 𝑛𝑛 > 1

and then by a recursive definition, and in such


106situations, recursion is often a good solution.
In this case, the method factorial() simply just a rewrite of the mathematical formula to a
method in Java.

It is clear that in this case the method could be written iteratively by means of a simple
loop, and this solution would even be preferable, but in other situations, recursion is a
good solution to provide a simple solutions and even a code which is easier to read and
understand than an equivalent iterative solution. There is reason to always be aware of
recursive methods, as each recursive call creates an activation block on the program stack.
There is therefore a danger that the recursive methods use the whole stack, with the result
that the program will crash.

THE VIEW

This leaves the program’s view, which simply consists of a single class named MainView.
The class contains nothing new and should not be discussed further here.

157
JAVA 3: OBJECT-ORIENTED PROGRAMMING Final example

The program Calc has in contrast to the programs that I have shown so far in this series
of books on software development, focus on algorithms, and thus how to solve a relatively
complex problem using a program. Rather than show the code here (and there are over
1200 lines of code) should you study the code and its algorithms and here especially

-- how the scan is done


-- how the expression is parsed
-- how an expression is converted to postfix
-- how an expression evaluated

It happens all in class Expression, but the code is carefully documented.

158
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A

APPENDIX A
Applications must be tested before they can be used, and for example you can try out the
program, and check whether the program gives the correct result. It will always be a part of
a test, since it is here that one realizes where the program to the user works as it should. You
must remember to test how the application behaves when you enter something illegal or the
program use arguments that are not legal, and such, and it is also important to test what
happens when the window is resized. Besides, it is important that such user tests are performed
by others than who wrote the program when there is a great risk that the programmer because
of complicity overlook anything: You never know what real users can find on!

Sometimes you can not do anything other than what I have mentioned above, but in other
contexts it is necessary to test the code on a lower level, where the programmer tests the
code. I will mention three important ways:

1. Comment the code.


2. Debug the code.
3. Unit test the code.

and I will as an example use the program CurrrencyProgram.

COMMENT THE CODE


All three methods are important, but each with their opportunities. I have previously
mentioned that to write comment’s in the code as an effective (and often overlooked) means
to ensure the quality of the finished program. In principle, it is trivial, but you should
not underestimate the process. For the sake of future maintenance is good documentation
clearly important, but more important is the process of writing the documentation, if it
does otherwise performed conscientiously.

I think you have to document the following:

-- In front of each class write a comment that tells of the class’s purpose and its genesis,
but generally you should write everything that you believe that that a person that in
the future should maintain the code, needs to know. The comment is updated by
any subsequent substantial change of the class, and is described as a Java comment,
so that it becomes part of a complete class documentation.
-- All variables and other data definitions are documentated with a short comment
for what a variable is use for. Here I not use Java comments, unless it is a public
static variabel or field.

159
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A

-- All public methods are documented with Java comments, so they are included in a
part of the final class documentation. All parameters, return values and exceptions
are documented, but in general there should also be a description of the method’s
purpose and including pre conditions of the parameters and possible side effects.
For simple get methods, it is typically sufficient to comment the return value.
-- All private and protected methods are in principle documented in the same way,
but here I usually do not use Java comments. The documentation of these methods
should not be included in the final class documentation.
-- Finally, there are algorithms in which it may be necessary to comment on the
details of the code. Generally I leave those comments to be part of the comment
in front of the method, and to endeavor to avoid comments inside the body of
the method, but if it is necessary to explain how the algorithm work, of course
not refrain from such comments.

As mentioned, the process is important because as a part of the job thinking through why
you now have written the code that you have. I would not say that in this way, all errors
are found, but you will find an incredible number of inconveniences and places where the
solution is ineffective.

It is an extensive work documenting code, but the work is well spent!

It is not all code, I document with comments and it is typically the controller and model
classes. However, it is rare to documents classes in the user interface and at least only to
a limited extent. I feel simply not that it makes any special dividends, whether as future
documentation or detection of inexpediencies. The reason is probably that the development
of the user interface is largely reuse of code from other programs.

The project CurrencyProgram is documented according to those recommendations.

JAVA DOC

As mentioned above, you should widely use Java comments, and I also discussed how to
get NetBeans to insert a skeleton in front of a method. As shown many times there is a
special syntax for inserting comments from the parameters, return values, etc.. and there
are actually some more, where the most important are:

-- @author, the author of the class


-- {@code} Display text in code font without interpreting the test as HTML
-- @exception Adds a Throws heading to the generated documentation, with the
classname and a description.

160
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A

-- @{link} Inserts an inline link with the visible text label that points to the documentation
for the specified package, class, or member name of a referenced class.
-- @param Adds a parameter with the specified parameter name followed by the
specified description of the parameter.
-- @return Adds a Returns section with a description.
-- @see Adds a See Also heading with a link or text entry that points to a reference.

The idea is that by using a tool these comments can generate a complete documentation
as an HTML document, and you can even write your own HTML in the docmentation.

If you have a project like Currency and in NetBeans right clicks on the project name, you
get a menu item Generate Javadoc, which generates the documentation. NetBeans will then
open a browser with the the result, which you can save. Below is shown the documentation
of the current project:

161
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A

DEBUG THE CODE


Now it may not be entirely correct to call debug the code for part of the test, but NetBeans
has a good debugger, and since I have not previously referred to it, it must have a few
words at this location.

When you want to test a program, it will often fail, and perhaps you get a wrong result,
or the program crashes. The task then is to find the error and correct it, and here the
debugger can help. You can set a breakpoint, which means that the excution of the program
stops when the program reaches that point in the code, and you can then see the value of
variables and check whether they have the right value. You can also step forward in the code
statement by statement and constantly monitor what happens with variables. The debugger
is a highly efficient tool to find where a program failed, but in general the debugger is used
to analyze the code.

As an example, one might think that the program CurrencyProgram fails, when you create a
new CurrencyTable object (which is a singleton, and there is a possibility of an error when
the object is instantiated), and the task is then to find out where it goes wrong. As an
example, one could then set a breakpoint in the method init():

162
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A

You set the breakpoint by clicking with the mouse next to the desired line (here line 88).
From the menu you can then start the debugger by selecting Debug | Debug Project. When
init() is performed, the program will stop, where there is set a breakpoint, and you can
then step through the code line by line (by using F8). That way you can see where the
program possibly crashes. You can also put a watch on variables (by right-clicking in the
debug window), and you can see the variables values and what happens to them:

163
JAVA
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING Appendix
appendIx A
a

The
The debugger
debugger has
has many
many other
other opportunities
opportunities to to analyze
analyze the
the code.
code. For
For example
example youyou can
can by
by
pressing
pressing F7F7 jump
jump into into the
the code
code for
for aa method.
method. YouYou should
should examine
examine the
the Debug
Debug menu
menu to to
get
get an
an idea
idea of
of what
what is is possible.
possible. It
It is
is worthwhile
worthwhile to to use
use some
some time
time learning
learning the
the debugger
debugger
to
to know,
know, since
since itit is
is aa highly
highly effective
effective tool
tool for
for troubleshooting.
troubleshooting. Probably
Probably itit is
is not
not directly
directly aa
testing
testing tool,
tool, but
but aa good
good tool
tool for
for finding
finding the
the errors
errors detected
detected during
during the
the testing.
testing.

UNIT TEST
Unit
Unit test
test is
is carried
carried out
out with
with aa tool,
tool, that
that isis integrated
integrated into
into NetBeans.
NetBeans. Unlike
Unlike the
the testing
testing
of
of the
the program,
program, where
where you
you test
test how
how the
the finished
finished program
program behaves,
behaves, and
and whether
whether itit meets
meets
all
all requirements,
requirements, unitunit test
test is
is aa systematic
systematic wayway to
to test
test individual
individual classes
classes and
and methods,
methods, andand
therefore
therefore itit is
is something
something that
that must
must bebe done
done byby the
the programmer
programmer as as part
part of
of the
the development.
development.
It
It is
is not
not everything
everything that
that you
you cancan unit
unit test,
test, and
and itit is
is best
best suited
suited for
for testing
testing controller
controller and
and
model
model classes,
classes, and
and specifically
specifically unit
unit test
test is
is effective
effective test
test of
of classes
classes in
in libraries.
libraries.

II will
will test
test the
the class
class Controller,
Controller, which
which has
has three
three methods:
methods:

package currencyprogram;

import java.util.*;
import java.io.*;

/**
* Class containing methods to the program's data processing.
*/
public class Controller
{
/**
* Converter an amount from one currency to another currency.
* The conversion is done primarily through the next calculation method, and this
* method should primarily validate that amount is a legal number.
* @param amount The amount to be converted
* @param from The currency to be converted from
* @param to The currency to be converted to
* @return The result of the conversion
* @throws Exception The amount can not be parsed or an currency objects is null
*/
public double calculate(String amount, Currency from, Currency to)
throws Exception
{

}

164
164
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A
JAVA 3: OBJECT-ORIENTED PROGRAMMING appendIx a

/**
* Converter an amount from one currency to another currency.
* @param amount The amount to be converted
* @param from The currency to be converted from
* @param to The currency to be converted to
* @return The result of the conversion
* @throws Exception If one of the two currency objects are null
*/
public double calculate(double amount, Currency from, Currency to)
throws Exception
{

}

/**
* Updating the currency table from a semicolon delimited text file.
* Each line consists of three fields separated by semicolons and in the
* following order:
* name;code;rate
* @param file The file from which to read currencies
* @return A list containing all lines that could not be converted into currency
*/

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

165
165
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A
JAVA 3: OBJECT-ORIENTED PROGRAMMING appendIx a

public ArrayList<String> update(File file)


{

}
}

First,
First,I Icreates
createsaatest
testclass.
class.You
Youdo
dothis
thisby
byright-clicking
right-clickingononthe
theclass
classname
nameController.java
Controller.java
ininthe Projects tab, and here should you choose Tools | Create / Update
the Projects tab, and here should you choose Tools | Create / Update Tests Tests

I Ikept
keptall
allthe
thesettings
settingsasasthey
theyare.
are.When
Whenyou
youclick
clickOK,
OK,you
youmay
mayreceive
receiveaadialog
dialogbox:
box:

166
166
JAVA3:3:OBJECT-ORIENTED
JAVA OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING appendIxAa
Appendix

andififso,
and so,choose
chooseJUnit
JUnit4.4.Then
ThenNetBeans
NetBeanscreates
createsaatest
testclass,
class,asasshown
shownbelow.
below.The
Thetest
testclass
class
isiscalled
calledControllerTest,
ControllerTest,and andbesides
besidesaadefault
defaultconstructor
constructorisiscreated
createdfour
fourempty
emptymethods
methods
asas well
well asas three
three test
test methods.
methods. There
There are
are generally
generally created
created aa test
test method
method for
for each
each non-
non-
privatemethod
private methodininthe theclass.
class.When
Whenthe thetest
testclass
classisiscarried
carriedout,
out,this
thismeans
meansthat
thatall
allofofthe
the
testmethods
test methodsare areexecuted.
executed.TheThefour
fourempty
emptymethods
methodsare areused
usedtotoadd addcode
codethat
thatyou
youwant
want
performed,respectively
performed, respectivelybefore
beforeand
andafter
afterthe
thetest,
test,and
andtwotwomethods
methodstotobe beperformed
performedbefore
before
andafter
and afterthetheindividual
individualtest
testmethods.
methods.InInthis
thiscase
caseI Iwill
willnot
notadd
addanything
anythingand
andthethemethods
methods
couldeasily
could easilybe bedeleted.
deleted.

package currencyprogram;

import java.io.File;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class ControllerTest {

public ControllerTest() {
}

@BeforeClass
public static void setUpClass() {
}

@AfterClass
public static void tearDownClass() {
}

@Before
public void setUp() {
}

@After
public void tearDown() {
}
@Test
public void testCalculate_3args_1() throws Exception {
System.out.println("calculate");
String amount = "";
Currency from = null;

167
167
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A
JAVA 3: OBJECT-ORIENTED PROGRAMMING appendIx a

Currency to = null;
Controller instance = new Controller();
double expResult = 0.0;
double result = instance.calculate(amount, from, to);
assertEquals(expResult, result, 0.0);
fail("The test case is a prototype.");
}

@Test
public void testCalculate_3args_2() throws Exception {
System.out.println("calculate");
double amount = 0.0;
Currency from = null;
Currency to = null;
Controller instance = new Controller();
double expResult = 0.0;
double result = instance.calculate(amount, from, to);
assertEquals(expResult, result, 0.0);
fail("The test case is a prototype.");
}

168
168
JAVA 3: OBJECT-ORIENTED PROGRAMMING appendIx a

JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A


JAVA 3: OBJECT-ORIENTED PROGRAMMING
@Test appendIx a

public void testUpdate() {


System.out.println("update");
@Test
File file
public void= testUpdate()
null; {
Controller instance = new Controller();
System.out.println("update");
ArrayList<String>
File file = null; expResult = null;
ArrayList<String>
Controller instanceresult
= new =Controller();
instance.update(file);
assertEquals(expResult, result);
ArrayList<String> expResult = null;
fail("The test case
ArrayList<String> is a =prototype.");
result instance.update(file);
}assertEquals(expResult, result);
fail("The test case is a prototype.");
}}

You must specifically noting how the test methods are named, and how to solve the problem
}
that two methods has the same name. The auto-generated test methods can usually not
You mustdirectly
be used specifically
for noting howbut
anything, the you
test methods
can notice arethat
named,
the and how toincludes
methods solve theusual
problem
Java
that two methods
statements, and thehas theofsame
work name.
writing unitThe
testsauto-generated
is to write codetesttomethods can usually
test methods. not
As a start,
be usedchanged
I have directly the
for middle
anything,
testbut you can
method notice
to the that the
following methods
while I haveincludes
comment usual
out Java
the
statements,
code in the and
otherthetwo:
work of writing unit tests is to write code to test methods. As a start,
I have changed the middle test method to the following while I have comment out the
code
@Testin the other two:
public void testCalculate_3args_2() throws Exception {
System.out.println("calculate(double amount, Currency from, Currency to)");
@Test
Currency
public voidc1testCalculate_3args_2()
= new Currency("DKK", "Danish crowns", 100);
throws Exception {
System.out.println("calculate(double amount,750);
Currency c2 = new Currency("EUR", "Euro", Currency from, Currency to)");
Currency c1
Currency c3 == new
new Currency("DKK",
Currency("USD", "Danish
"US dollar", 600);
crowns", 100);
Controller instance = new Controller();
Currency c2 = new Currency("EUR", "Euro", 750);
assertEquals(instance.calculate(1000,
Currency c3 = new Currency("USD", "US c2, c1), 7500,
dollar", 600); 0.0001);
assertEquals(instance.calculate(1000,
Controller instance = new Controller(); c1, c2), 133.33, 0.01);
assertEquals(instance.calculate(1000, c2,
assertEquals(instance.calculate(1000, c2, c1),
c3), 7500,
1200, 0.0001);
0.0001);
assertEquals(instance.calculate(1000, c3, c2), 800, 0.0001);
assertEquals(instance.calculate(1000, c1, c2), 133.33, 0.01);
}assertEquals(instance.calculate(1000, c2, c3), 1200, 0.0001);
assertEquals(instance.calculate(1000, c3, c2), 800, 0.0001);
}
Wee say that the method has four test cases. Each test case performs the method assertEquals()
with two currency objects as parameters. Every time the method’s return value is tested whether
Wee
it hassaya that thevalue
certain methodandhas four test
because thecases.
typeEach test case
is double, youperforms the the
must with method assertEquals()
last parameter set
with two currency
the maximum objects asIfparameters.
deviation. a test case Every timetest
fails, the the is
method’s returnwith
interrupted valueanis tested whether
error message.
it has isa to
That certain value
accept the and
test because
all tests the
casestype
mustis double, you must
be performed with error.
without the lastThat’s
parameter
what theset
the
unitmaximum
test is about,deviation.
and theIfonlya test casetofails,
thing learntheis test
which is interrupted
test cases it with an error
is possible message.
to write. To
That
performis totheaccept
test, the test all the
right-click teststest
cases must
class underbe performed
the Projectswithout
tab anderror.
choose That’s
Test what the
File. The
unit
resulttest
saysis where
about,the
andtest
theisonly thing tocorrectly:
performed learn is which test cases it is possible to write. To
perform the test, right-click the test class under the Projects tab and choose Test File. The
result says where the test is performed correctly:

169

169
169
JAVA
JAVA
JAVA3:3:OBJECT-ORIENTED
OBJECT-ORIENTEDPROGRAMMING
PROGRAMMING Appendix
appendIxAa
JAVA 3:
3: OBJECT-ORIENTED
OBJECT-ORIENTED PROGRAMMING
PROGRAMMING appendIx
appendIx a
a

InIn
Inthis
thiscase,
this case,the
case, thetest
the testfailed.
test failed.The
failed. Thereason
The reasonisis
reason isthat
thatthe
that thethird
the thirdtest
third testcase
test casefails,
case fails,since
fails, since––
since –erroneously
erroneously––
erroneously –
there
thereisisananincorrect
incorrect expected
expected value.
value.I Ichange
change
there is an incorrect expected value. I change it to ititto
to

assertEquals(instance.calculate(1000,
assertEquals(instance.calculate(1000, v2,
assertEquals(instance.calculate(1000, v2, v3),
v2, v3), 1250,
v3), 1250, 0.0001);
1250, 0.0001);
0.0001);

and
andthe
and thetest
the testisis
test isperformed
performedcorrect:
performed correct:
correct:

The
Thevalue
The valueofof
value ofsuch
suchtests
such testsisis
tests isofof
ofcourse
coursedetermined
course determinedby
determined bythe
by thenumber
the numberofof
number oftest
testcases.
test cases.Below
cases. Belowisis
Below isthe
the
the
code
codefor
forthe
thefirst
firsttest
testmethod:
method:
code for the first test method:

@Test
@Test
@Test
public
public void
public void testCalculate_3args_1()
void testCalculate_3args_1() throws
testCalculate_3args_1() throws Exception
throws Exception {
Exception {
{
System.out.println("calculate(String
System.out.println("calculate(String amount, Currency from,
System.out.println("calculate(String amount, Currency from,
amount, Currency Currency
from, Currency to)");
Currency to)");
to)");
Currency
Currency c1
c1 =
= new
new Currency("DKK",
Currency("DKK", "Danish
"Danish crowns",
crowns", 100);
100);
Currency c1 = new Currency("DKK", "Danish crowns", 100);
Currency
Currency c2
Currency c2
c2 == new
= new Currency("EUR",
new Currency("EUR", "Euro",
Currency("EUR", "Euro", 750);
"Euro", 750);
750);
Currency
Currency c3 = new Currency("USD", "US dollar", 600);
Currency c3
c3 =
= new
new Currency("USD",
Currency("USD", "US
"US dollar",
dollar", 600);
600);
Controller
Controller instance
instance =
= new
new Controller();
Controller();
Controller instance = new Controller();
assertTrue(Math.abs(instance.calculate("1000",
assertTrue(Math.abs(instance.calculate("1000", c2,
assertTrue(Math.abs(instance.calculate("1000", c2, c1)
c2, c1) –
c1) – 7500)
– 7500) <
7500) < 0.01);
< 0.01);
0.01);
assertTrue(Math.abs(instance.calculate("1000",
assertTrue(Math.abs(instance.calculate("1000", c1, c2) – 133.33) <
assertTrue(Math.abs(instance.calculate("1000", c1, c2) – 133.33) < 0.01);
c1, c2) – 133.33) < 0.01);
0.01);
assertTrue(Math.abs(instance.calculate("1000",
assertTrue(Math.abs(instance.calculate("1000", c2,
c2, c3)
c3) –
– 1250)
1250) <
<
assertTrue(Math.abs(instance.calculate("1000", c2, c3) – 1250) < 0.01);0.01);
0.01);
assertTrue(Math.abs(instance.calculate("1000",
assertTrue(Math.abs(instance.calculate("1000", c3,
assertTrue(Math.abs(instance.calculate("1000", c3, c2)
c3, c2)
c2) –– 800)
– 800)
800) << 0.01);
< 0.01);
0.01);
}
}
}

ItItlooks like the previous test method, and the difference between the two methods is also
It looks
looks like
like the
the previous
previous test
test method,
method, and
and the
the difference
difference between
between the
the two
two methods
methods isis also
also
only
only the
the type
typeofofthe
thefirst
firstparameter.
parameter. Each
Eachtest
testcase
caseisiswritten
written this
thistime
time ininaadifferent
differentmanner
manner
only the type of the first parameter. Each test case is written this time in a different manner
byby means ofofassertTrue(). There are no special reasons for it ininaddition to showing the syntax.
by means
means of assertTrue().
assertTrue(). There
There are
are no
no special
special reasons
reasons for
for it
it in addition
addition to
to showing
showing the
the syntax.
syntax.

You
Youcan also add your own test methods, and the following method isisused to test whether
You can
can also
also add
add your
your own
own test
test methods,
methods, and
and the
the following
following method
method is used
used to
to test
test whether
whether
you
youget an exception ififthe calculate() method isisperformed with aaCurrency that isisnull:
you get an exception if the calculate() method is performed with a Currency that is null:
get an exception the calculate() method performed with Currency that null:

@Test(expected=Exception.class)
@Test(expected=Exception.class)
@Test(expected=Exception.class)
public
public void
public void testNullValuta()
void testNullValuta() throws
testNullValuta() throws Exception
throws Exception {
Exception {
{
System.out.println("calculate
System.out.println("calculate with arguments that
System.out.println("calculate with arguments that is
with arguments that is null");
is null");
null");
Currency
Currency c1
c1 =
= new
new Currency("DKK",
Currency("DKK", "Danish
"Danish crowns",
crowns", 100);
100);
Currency c1 = new Currency("DKK", "Danish crowns", 100);
Controller
Controller instance
Controller instance =
instance = new
= new Controller();
new Controller();
Controller();

170
170
170
170
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A
JAVA 3: OBJECT-ORIENTED PROGRAMMING appendIx a
JAVA 3: OBJECT-ORIENTED PROGRAMMING appendIx a

assertEquals(instance.calculate(1000, c1, null), 7500, 0.0001);


assertEquals(instance.calculate(1000, c1, null), 7500, 0.0001);
assertEquals(instance.calculate(1000, null, c1), 133.33, 0.01);
assertEquals(instance.calculate(1000, null, c1), 133.33, 0.01);
}
}

You
You should
should note,
note, how
how to
to specify
specify that
that aa test
test case
case may
may raise
raise an
an exception.
exception.

Next
Next II adds
adds aa test
test class
class for
for the
the class
class CurrencyTable.
CurrencyTable. This
This is
is done
done in
in exactly
exactly the
the same
same manner
manner
as above, and the results are as follows:
as above, and the results are as follows:

package currencyprogram;
package currencyprogram;

import java.util.Iterator;
import java.util.Iterator;
import org.junit.After;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.*;
public class CurrencyTableTest {
public class CurrencyTableTest {

public CurrencyTableTest() {
public CurrencyTableTest() {
}
}

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

171
171
171
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A
JAVA 3: OBJECT-ORIENTED PROGRAMMING appendIx a

@BeforeClass
public static void setUpClass() {
}

@AfterClass
public static void tearDownClass() {
}

@Before
public void setUp() {
}

@After
public void tearDown() {
}
@Test
public void testGetInstance() {
System.out.println("getInstance");
CurrencyTable expResult = null;
CurrencyTable result = CurrencyTable.getInstance();
assertEquals(expResult, result);
fail("The test case is a prototype.");
}

@Test
public void testGetCurrency() throws Exception {
System.out.println("getCurrency");
String code = "";
CurrencyTable instance = null;
Currency expResult = null;
Currency result = instance.getCurrency(code);
assertEquals(expResult, result);
fail("The test case is a prototype.");
}

@Test
public void testIterator() {
System.out.println("iterator");
CurrencyTable instance = null;
Iterator<Currency> expResult = null;
Iterator<Currency> result = instance.iterator();
assertEquals(expResult, result);
fail("The test case is a prototype.");
}
@Test
public void testUpdate() {
System.out.println("update");

172
172
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A
JAVA 3: OBJECT-ORIENTED PROGRAMMING appendIx a

Currency currency = null;


CurrencyTable instance = null;
boolean expResult = false;
boolean result = instance.update(currency);
assertEquals(expResult, result);
fail("The test case is a prototype.");
}
}

Thistime
This timethere
thereare
arefour
fourtest
testmethods.
methods.The Thefirst
firsttest
testthe
thestatic
staticmethod
methodgetInstance(),
getInstance(),which
which
simplyreturns
simply returnsaareference
referencetotothethesingleton.
singleton.ItItmakes
makesno nosense,
sense,and
andI Iwill
willdelete
deleteit.it.So
Soyou
you
cansimply
can simplydelete
deletethe
thetest
testmethods
methodswhichwhichyouyoudo donot
notwish
wishtotomake
makeuseuseof.
of.I Iwould
wouldalsoalso
deletethe
delete thetest
testmethod
methodthatthattests
teststhe
theiterator.
iterator.I Iwill
willnow’s
now’swriting
writingthe
thecode
codeforforthe
thelast
lasttwo
two
testmethods:
test methods:

@Test
public void testGetCurrency() throws Exception {
System.out.println("getCurrency(String code)");
assertNotNull(CurrencyTable.getInstance().getCurrency("DKK"));
assertNotNull(CurrencyTable.getInstance().getCurrency("EUR"));
}

@Test
public void testUpdate() {
System.out.println("update(Currency currency)");
try
{
int count1 = 0;
for (Currency c : CurrencyTable.getInstance()) ++count1;
Currency c1 = new Currency("EUR", "European euro", 800);
Currency c2 = new Currency("TST", "Test currency", 1000);
CurrencyTable.getInstance().update(c1);
CurrencyTable.getInstance().update(c2);
Currency c3 = CurrencyTable.getInstance().getCurrency("EUR");
Currency c4 = CurrencyTable.getInstance().getCurrency("TST");
int count2 = 0;
for (Currency c : CurrencyTable.getInstance()) ++count2;
System.out.println(c3.getName());
System.out.println(c4.getName());
assertEquals(c3.getRate(), 800, 0.0001);
assertEquals(c4.getRate(), 1000, 0.0001);
assertEquals(count2 – count1, 1);
}
catch (Exception ex)
{
System.out.println(ex);
}
}

173
173
JAVA 3: OBJECT-ORIENTED PROGRAMMING Appendix A

There is not much to explain, but note that the first use assertNotNull() to test that an object
is not null. Note also that this time you should not create an instance of the CurrencyTable,
as the class is written as a singleton. Finally, note the last test method, and that a test
method can include all the Java statements that may be needed.

Back there is a test method in the test class ControllerTest, but I will not write the code, but
note that it is simple to write a file with test data and test if the method is working properly.

The strength of a unit test depends as mentioned by the number of test cases. It can be
a lot of work to write test classes for unit testing, but classes must be tested, and the real
value of the unit test is that if first written individual test methods you can repeat the test
all the times that may be required, and it is, in principle, every time the class is modified.

As a final note regarding unit test NetBeans has a menu Run | Test Project, and if you choose
that, all test classes are performed.

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

174

You might also like