1005ict object oriented programming lecture · pdf file1005ict object oriented programming...

Post on 06-Mar-2018

226 Views

Category:

Documents

4 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1005ICT Object Oriented ProgrammingLecture Notes

School of Information and Communication TechnologyGriffith University

Semester 2, 2015

1

1 Introduction

Welcome to 1005ICT object oriented programming (OOP).

These lecture notes are divided into sections. This one describes the course’s:

• content;

• roles and responsibilities;

• assessment;

• resources; and

• some things you need to do now.

1005ICT Object Oriented Programming – 2015-2 2

1.1 7005ICT Programming Principles 2

For this semester, the class also includes Masters students enrolled in 7005ICTProgramming Principles 2 (PP2).

The course materials and assessment items will be the same as for the un-dergraduate course, however the grading basis will be different.

Please note that this is the second part of our introduction to programming.

If your undergraduate program did not include programming, please see thecourse convenor or your program convenor for advice as to whether this isthe right course for you.

1005ICT Object Oriented Programming – 2015-2 3

1.2 Take notes?

These notes are posted on the web.

So you don’t have to copy them all down.

But we say more than goes in the slides.

You should be prepared to take notes that capture the extra information.

1.2.1 Take notes today!

Write down the things in colour.

1005ICT Object Oriented Programming – 2015-2 4

1.3 Course Convenors & Lecturers

course convenor Andrew Rock& lecturer a.rock@griffith.edu.au

Technology Building (N44) 1.37

1005ICT Object Oriented Programming – 2015-2 5

1.4 Course web site

These notes will be posted on the web at:http://www.ict.griffith.edu.au/arock/oop/

You will find the laboratory notes and anything else you need there too.

Write down the uniform resource locator (URL) now!

You can also access these resources via Learning@Griffith, though directaccess via the above URL will be quicker.

Lectures are captured and available, after editing, onLearning@Griffith’s Echocentre.

1005ICT Object Oriented Programming – 2015-2 6

1.5 What the course is about

This is the second part of an introduction to:

• programming tools;

• programming concepts;

• problem solving; and

• programming languages.

The emphasis will be on the object oriented aspects of the Java program-ming language.

1005ICT Object Oriented Programming – 2015-2 7

1.6 The choice of programming languages

In your working life you will write lots of programs, in lots of programminglanguages.

Any time you create a script, automation, spreadsheet, or animation, it’sprogramming.

It may be that you never program in Java after completion of your program-ming classes.

However, Java is a programming language that has all of the attributes foundin all of the common application and scripting languages. Its notation issimilar to many, including C, C++, C#, JavaScript, and ActionScript.

1005ICT Object Oriented Programming – 2015-2 8

1.7 Prerequisites

This course assumes some knowledge of programming in an imperativeprogramming language.

Most of you will have completed 1001ICT Introduction To Programming(ITP).

That course uses an imperative subset of Java, Making Stuff Happen (MaSH).

If you have not done that particular course, any prior course on program-ming should provide an equivalent background.

MaSH is very similar to C, Pascal, and related languages.

If you do not have a pass or better for 1001ICT or an equivalent course, youare not qualified to undertake this course.

See me asap, if you are unsure that you have the prerequisites.

1001ICT and 7001ICT are also offered this semester.

1005ICT Object Oriented Programming – 2015-2 9

1.8 Classes and assessment

1.8.1 Lectures

In a 2-hour lecture every week, we will learn the concepts and strategiesused in programming.

During 5 of the lectures, we will test your learning with quizzes.

3 + 4 + 5 + 6 + 7 = 25 marks

1.8.2 Workshops

In a 1-hour workshop every week we demonstrate more examples and pro-vide and discuss extra non-assessed problems.

1005ICT Object Oriented Programming – 2015-2 10

1.8.3 Labs

In 10 2-hour assessed lab classes you put the theory into practice.

2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 = 40 marks

1.8.4 Common times

A common time is a class where there are no set activities, but you can getindividual help if you need it or we can challenge you with extra, harderproblems if you want them.

1.8.5 Final project

The course ends with a larger programming project (35 marks).

1005ICT Object Oriented Programming – 2015-2 11

1.8.6 Attendance summary

Students are expected to attend all lectures and workshops.

You are enrolled in one 2 hour labs class. Attend that every week from week2.

Attend any common time as needed, from week 2.

“Eighty percent of success is showing up.” – Woody Allen.

1.8.7 Assessment summary

quizzes 3 + 4 + 5 + 6 + 7 = 25labs 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 = 40project 35total 100

1005ICT Object Oriented Programming – 2015-2 12

1.8.8 Minimum requirements for labs and quizzes

The labs are quizzes are treated as one assessment item each.

If you do not attend the majority of each, we don’t think you are reallyattempting them.

If you don’t attend at least 6 labs, you don’t get any lab marks at all.

If you don’t attend at least 3 quizzes, you don’t get any quiz marks at all.

Either of these outcomes will make it almost impossible to pass the course.

You may even be awarded a grade of Fail Not Sat, which would be a betterindication of your performance than a plain Fail.

1005ICT Object Oriented Programming – 2015-2 13

1.8.9 Supplementary exam

Supplementary assessment, if passed, can raise your grade from a 3 to thelowest passing grade (a 4).

To be eligible, you must have been awarded a 3, have submitted/sat themajority of the assessed labs, the majority of the quizzes, and at least partof the final project.

For this course, the supplementary assessment takes the form of a two-hour,closed-book, written examination.

1005ICT Object Oriented Programming – 2015-2 14

1.9 Lecture notes

The lecture notes are available on the course web site in various formats.

The most useful format is the A5 version, which:

• has a table of contents;

• has an index;

• has clickable links;

• includes appendices that summarise the programming language andenvironments, plus other useful reference information;

• is ideally formatted for a tablet or laptop screen; and

• prints double-sided as a small book.

1005ICT Object Oriented Programming – 2015-2 15

1.10 Griffith Sciences Laboratory Induction

You will have been briefed in orientation about workplace health and safety,and the on-line course and test on Learning@Griffith in the organisationGriffith Sciences Laboratory Induction that you must complete.

In this course we will be checking that you have passed that test.

You must print the certificate that shows that you passed that test, within thelast year, and bring it to your first programming lab class (in week 2).

1005ICT Object Oriented Programming – 2015-2 16

1.11 Peer Assisted Study Sessions

At Nathan, this course has a student learning support service, Peer AssistedStudy Sessions (PASS).

PASS offers free extra weekly study sessions, led by more experienced fel-low students (PASS leaders).

The details about PASS will be presented by the PASS leaders in the week2 lecture.

PASS is optional (and limited access), but students who use it have beenshown to get better results than students who don’t.

At Logan PASS is not available.

However, we are trying to find an alternate means of extra support, andchange the Nathan PASS timetable so it is possible for Logan students tocommute.

1005ICT Object Oriented Programming – 2015-2 17

Please use PASS or the alternatives!

Attendance is counted and if it drops below a certain level they get with-drawn. Just go to be social, so they are there when you need them.

Don’t forget that they are led by high-achieving students, and they may havetips for you beyond the course content.

1005ICT Object Oriented Programming – 2015-2 18

1.12 Revision

There is no section in these lecture notes, marked “revision”.

That would be boring to write, boring for students who had passed 1001ICT,and a bit mystifying for students with other backgrounds.

All students should do some revision with their previous course materials.

If you did 1001ICT, the last section Why MaSH Is Rubbish is a good placeto start.

As we walk through the new material, I will endeavour to indicate what issimilar to what you have seen before and what is truly new.

1005ICT Object Oriented Programming – 2015-2 19

1.13 Section summary

This section covered:

• why this course on programming is an important part of your programof studies;

• prerequisites;

• how this course is organised, taught and assessed;

• where the resources for this course can be found on the web;

• who the teachers are and how to contact them; and

• what you need to do to get started in this course.

1005ICT Object Oriented Programming – 2015-2 20

1.14 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 21

1.15 Things to do

What you need to be doing as soon as possible to get started:

• Get a diary or organiser and plan how you can spend your week prof-itably, including the following items.

• Make sure you are properly enrolled in this course and in a laboratory.

• Read the course outline and the course web site.

• Prepare for the first workshop by reading the exercises on the website.

• Prepare for laboratory 1, in week 2. Find the notes on the web site.There are some questions you need to answer before your lab class.

1005ICT Object Oriented Programming – 2015-2 22

• Complete the Griffith Sciences Laboratory Induction onLearning@Griffith, and bring the printed certificate to labs at leastonce.

• Revise your previous programming course notes.

• Lecture notes appendices A and B contain useful information that youshould read now.

1005ICT Object Oriented Programming – 2015-2 23

2 Kick-start Java

This section provides just enough Java to enable the practical activities inthe first laboratory class (in week 2).

The goals of the first laboratory will be to ensure that everyone (no mattertheir previous background) can edit and run a Java program using the mostbasic tools.

The emphasis in this section is on how to do some basic things, but not onwhy we do them that way.

1005ICT Object Oriented Programming – 2015-2 24

2.1 Hello, World!

This was the first and last example program in 1001ICT:

public class Hello {

public static void main(String[] args) {System.out.println("Hello, World!");

}

}

It must be saved in a file called Hello.java.

All of its components will be discussed below.

1005ICT Object Oriented Programming – 2015-2 25

2.1.1 System.out.println()

Use the procedure System.out.println() to print one anything –one String, one int, one boolean, etc. – and then a newline.

Examples:

System.out.println("Hello, World!"); // StringSystem.out.println(42); // intSystem.out.println(true); // booleanSystem.out.println(4.2); // doubleSystem.out.println("Meaning = " + 42); // What type?

There is also System.out.print(), which does not output a newline.

1005ICT Object Oriented Programming – 2015-2 26

2.1.2 The class

The whole program is encapsulated in a class:

public class Hello {

}

A class is the compilation unit for Java, that is, the smallest language ele-ment that the compiler will accept.

normalClassDeclaration

classBodyidentifierclass

classModifier

(This is a syntax diagram. See Appendix B for an explanation of the nota-tion.)

1005ICT Object Oriented Programming – 2015-2 27

public is an optional class modifier, but usual for a class that is to bemade available for use.

classModifier

public

private

static

Not all of these modifiers are useable with all kinds of classes.

As we learn more about Java’s object oriented aspects, more modifiers willbe introduced.

1005ICT Object Oriented Programming – 2015-2 28

The identifier is the name of the class.identifier

javaLetter

digit

javaLetter

keyword

booleanLiteral

not

A class’s name must start with a capital letter.

The name of a public class must match the name of the file.

1005ICT Object Oriented Programming – 2015-2 29

Java programs are written inUnicode, so the definition ofwhat is a letter, for the purposeof creating identifiers, is verybroad.

Letters may be selected fromother scripts, such as Greek, butdone rarely.

Underscores are used to separatewords within a name all in capi-tals.

Don’t use dollar signs. Theyare only for machine-generatedcode.

javaLetter

a

...

z

A

...

Z

Any other Unicode letter

_

$

1005ICT Object Oriented Programming – 2015-2 30

Digits are the decimal digits.

digit

0

...

9

The boolean literals are false and true.booleanLiteral

false

true

All of Java’s keywords are listed below.

keyword

See list.

1005ICT Object Oriented Programming – 2015-2 31

abstract double int strictfpassert else interface superboolean enum long switchbreak extends native synchronizedbyte final new thiscase finally null throwcatch float package throwschar for private transientclass goto protected tryconst if public voidcontinue implements return volatiledefault import short whiledo instanceof static

1005ICT Object Oriented Programming – 2015-2 32

The class body uses braces to encapsulate the sequence of class body dec-larations.

classBody

}

classBodyDeclaration

{

In our example, there is only one declaration in the body, the main method.

1005ICT Object Oriented Programming – 2015-2 33

2.1.3 The main method

In general, a method is declared like this, with a header and a body.

methodDeclaration

methodBodymethodHeader

The header declares the interface by which this method may be called.

methodHeader

methodDeclaratorresultType

methodModifier

methodDeclarator

)

formalParameterList

(identifier

The identifier is the method’s name, which should start with a lower caseletter.

1005ICT Object Oriented Programming – 2015-2 34

The method modifiers public and private con-trol the visibility of a method from other classes.

static makes the method static (not dynamic), thatis, belonging to the class and not to objects created atrun-time.

methodModifier

public

private

static

The result type is either:

• a type, the type that will be returned by thisfunction; or

• void, making this method a procedure thatdoes not return anything.

resultType

type

void

1005ICT Object Oriented Programming – 2015-2 35

The formal parameter list shows the types and names of the method’s pa-rameters.

formalParameterList

lastFormalParameter

,formalParameter

formalParameter

variableDeclaratorIdtype

lastFormalParameter

formalParameter

variableDeclaratorId

][

identifier

Later we will introduce another more interesting option for the last formalparameter.1005ICT Object Oriented Programming – 2015-2 36

The program starts executing (aside from some initialisations) at the mainmethod of the class that is run.

public static void main(String[] args) {

}

• It must have the name main;

• must be public so it is visible to be called to start the program;

• must be static so that it exists before any (dynamic) objects arecreated;

• must be a procedure (“returns” void); and

• must have a parameter with type array of strings.

1005ICT Object Oriented Programming – 2015-2 37

2.1.4 Compiling

The simplest way to compile the program is to invoke the Java compilerdirectly from the command line:

$ javac Hello.java$

Where:

• javac is the name of the Java compiler; and

• Hello.java is the name of the Java source code file.

• Hello.class is the object code file output by the compiler. Itcontains Java bytecode.

1005ICT Object Oriented Programming – 2015-2 38

2.1.5 Running

The simplest way to run the program is to invoke the Java virtual machine(JVM) directly from the command line:

$ java HelloHello, World!$

Where:

• java is the name of the JVM; and

• Hello is the name of the class to run.

1005ICT Object Oriented Programming – 2015-2 39

2.2 Hello, You!

Hello.java shows how to package a program and how to print some-thing.

Printing in Java is as easy as it is in MaSH, albeit a little more verbose.

Reading is a bit trickier, and we’ll leave it for a bit.

However the command line arguments make it easy to get a small amountof information into a program without reading.

1005ICT Object Oriented Programming – 2015-2 40

public class HelloYou {

public static void main(String[] args) {System.out.println("Hello, " + args[0] + "!");

}

}

$ javac HelloYou.java$ java HelloYou AndrewHello, Andrew!$

The array of strings argument to main holds any other command line argu-ments received by the java command other than the class name.

1005ICT Object Oriented Programming – 2015-2 41

2.3 Add

We can input numbers this way, we just need to convert them from thestrings.

public class Add {

public static void main(String[] args) {int a = Integer.parseInt(args[0]),

b = Integer.parseInt(args[1]);System.out.println(a + " + " + b +

" = " + (a + b));}

}

1005ICT Object Oriented Programming – 2015-2 42

$ javac Add.java$ java Add 1 21 + 2 = 3$

The function Integer.parseInt(String) converts a string to theint that it represents.

Similarly Double.parseDouble(String)...

Now we can write simple programs that print stuff with string or numericinputs.

1005ICT Object Oriented Programming – 2015-2 43

2.4 Section summary

This section covered:

• how to write a class;

• how to write a main method;

• how to print;

• how to use command line arguments;

• how to compile a program; and

• how to run it.

1005ICT Object Oriented Programming – 2015-2 44

2.5 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 45

2.6 Self-practice exercises

Do these in your own time to revise a little programming.

1. Write a Java program that inputs a person’s height and weight as com-mand line arguments and prints their body mass index (BMI).

2. Extend your BMI calculation program so that after the BMI is calcu-lated, it tells the user whether they are underweight, overweight or inthe normal range)

3. Write a Java program that accepts two integers and prints all of theintegers between and inclusive of those numbers.

1005ICT Object Oriented Programming – 2015-2 46

3 The Software Development Process

This section looks at the overall life cycle of software and provides a contextfor the design and implementation phases that are the main concerns of thiscourse.

1005ICT Object Oriented Programming – 2015-2 47

3.1 The waterfall model

Software has a life cycle.

It is conceived, developed, used, discarded, and replaced.

The life cycle is described in various ways, but one of the most popular isthe waterfall model.

This model divides the process into phases, analysis, design, implementa-tion, integration and maintenance.

In a well-run project, the step from one phase to the next is made only afterverification or testing.

Detection, of an error that requires reversion to a previous phase is expen-sive!

The earlier a defect is detected, the cheaper it is to fix.

1005ICT Object Oriented Programming – 2015-2 48

Analysis

Verification

Design

Verification

Implementation

Testing

Integration

Testing

MaintenanceThe waterfall model1005ICT Object Oriented Programming – 2015-2 49

phase delivers description exit phase when

analysis requirementsspecifica-tion

finding out whatthe software is sup-posed to do

the specificationhas been verifiedby the requestorsas meeting theirneeds

design design figuring out howthe software will doit

the design has beenverified to matchthe specification

implementation softwarecompo-nents

coding in program-ming languages,creation of otherassets (graphicsetc.)

each componentseparately passestests

1005ICT Object Oriented Programming – 2015-2 50

phase delivers description exit phase when

integration deployablesoftware

bringing the com-ponents together,installing

passes tests of thewhole system

maintenance ongoingsupport

small fixes in re-sponse to changingcircumstances

the software nolonger meets thecurrent require-ments without amajor reconsidera-tion that belongs toan earlier phase

The phase that lasts the longest (for a successful software project) is themaintenance, and it is therefore the most expensive over time.

Maintenance will be cheaper and easier if the earlier phases are done better.

1005ICT Object Oriented Programming – 2015-2 51

3.2 Other models

There are plenty of other models for the software lifecycle and the develop-ment process.

For example: iterative development, and agile development...

All of these are just variations on the waterfall model, with more willingnessto accept that the looping back to pervious phases is inevitable in practice.

So progress to later phases is not held up until the prior phases are 100%complete.

1005ICT Object Oriented Programming – 2015-2 52

3.3 Human communication

A large software project may divide these phases between different peopleor teams of people.

It is almost guaranteed that the people performing the maintenance will nothave been involved in the initial development.

The success of the project depends as much on the communication betweenall these people as on the technical aspects.

This course has an emphasis on the technical literacy required: reading andwriting documentation, and design notation.

1005ICT Object Oriented Programming – 2015-2 53

3.4 Use the right tools

It is very important that the choice of the tools is made on the basis of theneeds of the users and the project and not just the preferences or experienceof the participants.

The law of the hammer:

If you only have a hammer, everything looks like a nail.

Good designs are language independent.

A good object oriented design should be implementable in the best availableobject oriented programming language.

The design notations should not be too specific to a particular language.

1005ICT Object Oriented Programming – 2015-2 54

3.5 Section summary

This section covered:

• the waterfall model of the software development process and lifecy-cle; and

• the need for language independence in design notations.

1005ICT Object Oriented Programming – 2015-2 55

3.6 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 56

4 Programming In the Large

In this section we:

• consider the levels of programming, programming-in-the-small ver-sus programming-in-the-large;

• introduce the Java application programming interface (API) and itsdocumentation; and

• introduce Java packages.

Knowing how to read and use the Java API is as important as learning theJava language itself.

1005ICT Object Oriented Programming – 2015-2 57

4.1 Small To large programs

The assumed knowledge for this course is of programming-in-the-small.

At the core of imperative/procedural programming are its five elements:

assignment – variables, types, variable declarations, and assignment state-ments;

calls – methods, procedures, functions, and calls to them;

sequence – putting the above actions in a sequence to be carried out inorder;

iteration – loops, recursion, repetition of actions; and

selection – choosing between alternate actions.

1005ICT Object Oriented Programming – 2015-2 58

With just these five elements, any program could be constructed.

All of the generations of programming languages provide them.

So why do modern programming languages provide a lot more features thanjust these?

Two words: scale and cost.

• Cost, because programmers want to get paid, and the people who hirethem want to get the most value for that pay; and

• scale, because real programs range from quite small to huge.

1005ICT Object Oriented Programming – 2015-2 59

A (crude) measure of how big a program is, is source lines of code (SLOC).

Literally, how many lines of source code are used to create the program.

Here are some SLOC figures quoted on the web (rarely published for closed-source programs):

mashc 5 thousandMicrosoft word (first version) 27 thousandMicrosoft word (current) “at least a few million”World of Warcraft 5.5 millionWindows XP 45 millionMac OS X 10.4 86 million

Only one of these examples was written by just one person.

Most of these lines of code, are the kinds of lines you already know how towrite, but there are a lot of them.

1005ICT Object Oriented Programming – 2015-2 60

Not only do all of these lines of code have to be written in the first place,they must:

• be organised so that multiple people can find and access the parts ofthe code that they need to;

• be organised so that multiple people can not destructively interferewith each other’s code;

• be organised and documented so that they can be easily used andreused; and

• be organised so that they can be maintained (debugged, and modifiedover time).

Maintenance over time can be the most expensive part of a software’s totallife.

1005ICT Object Oriented Programming – 2015-2 61

A modern programming language must promote:

• the efficiency with which individual programmers work;

• the efficiency with which teams of programmers work;

• the reusability of code;

• the maintainability of code; and

• the efficiency with which code from different organisations can becombined.

1005ICT Object Oriented Programming – 2015-2 62

4.2 The standard Java API

Java is designed for small and large programming projects and has all themodern features to support programming in the large.

The best place to see this demonstrated is by looking at the standard JavaAPI.

This is the most important reference source for Java programmers.

It documents the pre-existing reusable code that they use to build new ap-plications.

1005ICT Object Oriented Programming – 2015-2 63

4.2.1 Where to find the Java API documentation

Java was originally developed by computer scientists working for Sun Mi-crosystems, which has since been taken over by Oracle. Hence:

http://www.oracle.com/technetwork/java/

is the current start point for downloading Java tools and documentation.

We will be using the Java Platform, Standard Edition (Java SE), at:

http://www.oracle.com/technetwork/java/javase/

From here, you can downloadyour own copy of the API.

Click on the Downloads tab.

1005ICT Object Oriented Programming – 2015-2 64

Look for Additional Resources, Java SE Documentation and then Down-load.

1005ICT Object Oriented Programming – 2015-2 65

Click on Accept Licence Agreement, then the download link.

1

2

When you unpack the .zip file, you get the API documentation as a largecollection of HTML files.

The most important aspect of the licence granted to you is that you do notmake these files accessible from the internet.

1005ICT Object Oriented Programming – 2015-2 66

You don’t have to download the API and install it on your own machine.

You can use the Java API on Oracle’s site:

http://docs.oracle.com/javase/8/docs/api/

I have also installed it on our own web server, but it is only available withinGriffith University, to save your NetCheck costs.

http://www.ict.griffith.edu.au/arock/java/docs/api/

1005ICT Object Oriented Programming – 2015-2 67

Here is the first page (in three frames) of the API. Everything is arranged inpackages.

1005ICT Object Oriented Programming – 2015-2 68

4.3 Small To large programming features

4.3.1 Subroutines to methods

Subroutines

The first step in making code reusable was the subroutine (or procedure, orfunction).

A subroutine enables some statements to be encapsulated and given a nameby which they can be called.

In old languages like Fortran, programmers could share their subroutines.

A collection of useful subroutines was called a library.

Note that what was considered important to share and reuse at that time wasonly the statements and the actions they performed.

1005ICT Object Oriented Programming – 2015-2 69

The problem with names

One problem that emerges quickly is that programmers must make sure thatthe names that they give their routines don’t clash with the names used byother programmers, who’s code they want to use.

This was especially fun in early FORTRAN, where the names could onlybe 6 characters long.

Methods

Only in object-oriented languages are subroutines etc. called methods.

1005ICT Object Oriented Programming – 2015-2 70

4.3.2 Modules to classes

Modules

Later languages were better designed for sharing not just actions, but data.

The new languages, C, Algol, Modula, could share new data types, not justmethods.

Modules were created to encapsulate and share data types, variables, andmethods.

Modules can control which of the definitions inside them are public or pri-vate.

An opaque type is one that is public, but the details of its internal structureare not.

The module will provide the methods that do everything that can be donewith or to that type.

1005ICT Object Oriented Programming – 2015-2 71

A module that defines an opaque type and its methods is said to define anabstract data type.

A module that contains private variables and methods to operate on them issaid to define an abstract data object.

Classes

Classes in object oriented languages like Java take this a little further.

A class is a module.

A class also defines a new type.

A class can be used like an abstract data object, but more commonly like anabstract data type.

Sometimes a class is just used as a collection of methods.

1005ICT Object Oriented Programming – 2015-2 72

The names problem solved – nearly

If variables and methods belong to modules or classes, then we can solvethe problem with names that clash, using qualification.

If class A defines a method called doThing(), but so does class B, we canrefer to them uniquely as A.doThing() and B.doThing().

But what happens if another programmer wants to use the name A or B forher class?

1005ICT Object Oriented Programming – 2015-2 73

4.3.3 Packages

Packages are the modern way to share code.

A package is an even higher level container for classes.

A package corresponds physically to a folder that contains all of the classfiles in that package.

The names problem solved – finally

Qualification is taken further with packages.

The name of a class can be qualified with the name of the package thatcontains it.

Packages can be nested (folders inside folders), so enough qualification canbe added to break any name clashes.

To be sure to avoid clashes, businesses use their web domain (backwards)to name their packages.1005ICT Object Oriented Programming – 2015-2 74

For example, two programmers in two different companies can use the samenames without any problems with clashes if their code is bought togetherinto the same system.

com.eyebeem.tax.DeductableItem.writeOff()com.esaypee.tax.DeductableItem.writeOff()

1005ICT Object Oriented Programming – 2015-2 75

4.4 Java package declarations

All Java code exists within packages, either unnamed or named.

Any Java class exists in just one package.

All of the classes we have written so far belong to the unnamed package,because we didn’t declare otherwise with a package declaration.

The compilation unit is the smallest amount of code accepted by the com-piler.

compilationUnit

typeDeclarationimportDeclaration

packageDeclaration

The type declaration is usually a normal class declaration.

1005ICT Object Oriented Programming – 2015-2 76

A compilation unit starts with an optional package declaration.

packageDeclaration

;packageNamepackage

If it is omitted, we are specifying the unnamed package.

Example with a package declaration:

package au.edu.griffith.oop;

public class PackageTest {

public static void main(String[] args) {System.out.println("Go, packages!");

}

}

1005ICT Object Oriented Programming – 2015-2 77

As in these examples, package names should start with lower case letters,so they may be distinguished from class names.

The downside is that to run this program, it must be in the folder hierarchythat matches the package name.

] javac au/edu/griffith/oop/PackageTest.java] java au.edu.griffith.oop.PackageTestGo, packages!]

For casual development and learning we don’t usually bother with pack-ages, and that is the reason that the unnamed package exists.

1005ICT Object Oriented Programming – 2015-2 78

4.5 Java import declarations

The converse to declaring that your code belongs in a package is to declarethat you want to use someone else’s code that is in a package.

This is done with an import declaration, of which there are two kinds.

importDeclaration

singleTypeImportDeclaration

typeImportOnDemandDeclaration

The first kind imports just one class from a package.

singleTypeImportDeclaration

;typeNameimport

1005ICT Object Oriented Programming – 2015-2 79

The second kind imports all of the classes from a package (as they areneeded).

typeImportOnDemandDeclaration

;*.packageOrTypeNameimport

The second kind is more commonly used (unless you like typing a lot).

1005ICT Object Oriented Programming – 2015-2 80

4.5.1 When you need import declarations

If you want to use a class in a package, saycom.eyebeem.coolstuff.MissileLauncher, you would eitherimport just that class:

import com.eyebeem.coolstuff.MissileLauncher;

or import all the classes in that package, as needed.

import com.eyebeem.coolstuff.*;

Then you can use the name MissileLauncher in your program, and thecompiler will know where it comes from.

1005ICT Object Oriented Programming – 2015-2 81

4.5.2 When you don’t need import declarations

Here are the times you don’t need to import a class:

• when the class is in the same package as the class you’re writing(maybe the unnamed package);

• when the class is in the special package java.lang, which is al-ways imported automatically; or

• when you fully qualify the class every time you use its name.

There have been no import declarations in any of our example programs sofar, because we have not used any classes not in java.lang.

1005ICT Object Oriented Programming – 2015-2 82

4.5.3 Avoid collisions

While using fully qualified names always allows you to avoid the collisionsbetween the names you choose for your classes, it is inconvenient.

Avoid any of the names already used in package java.lang and any otherstandard packages that you are likely to use frequently.

The compiler will report errors if you pick a name that collides with analready existing one.

1005ICT Object Oriented Programming – 2015-2 83

4.5.4 Example with imports

This is an example program that demonstrates the use of import declara-tions.

It does something cool and useful.

Warning: the lines commented with // !!! contain Java language fea-tures we have not covered yet.

/*** file: OpenURI.java

** author: Andrew Rock

** use: java OpenURI <URI>

** opens the <URI> in your default web

** browser.

*/

1005ICT Object Oriented Programming – 2015-2 84

import java.net.*; // for class URIimport java.awt.*; // for class Desktop

public class OpenURI {

public static void main(String [] args)throws Exception { // !!!

Desktop.getDesktop() // !!!.browse(new URI(args[0])); // !!!

}

}

We are not far from understanding all of this code.

We need two things, objects and exceptions, both coming soon.

1005ICT Object Oriented Programming – 2015-2 85

4.6 Section summary

This section covered:

• a review of the elements of imperative programming;

• the reasons why programming languages have features beyond thoseelements;

• where to find the standard Java API;

• levels of encapsulation and how they help with name classes; and

• Java packages and package and import declarations.

1005ICT Object Oriented Programming – 2015-2 86

4.7 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 87

5 Case Study: Class java.lang.Math

This section takes a close look at the documentation, in the Java API, ofclass java.lang.Math.

We will:

• learn how to find it;

• learn how to read it;

• make comments on the purpose, design and properties of this class;and

• make a new class that emulates the design of this class.

1005ICT Object Oriented Programming – 2015-2 88

5.1 Package java.lang

Package java.lang:

• is the only package imported automatically by the compiler;

• contains classes that are needed by nearly all programs, such asString.

1005ICT Object Oriented Programming – 2015-2 89

5.2 Finding a class in the API

If you know which package you are looking for, use the list in the top leftframe.

1005ICT Object Oriented Programming – 2015-2 90

Scroll down to the package you want and click.

1005ICT Object Oriented Programming – 2015-2 91

Then the lower left frameshows the lists of interfacesand then classes in that pack-age.

Interfaces are a variation ona class that we will introducelater.

After that are more types ofclasses that we can ignore forthe moment.

1005ICT Object Oriented Programming – 2015-2 92

Scroll down to the class you’re looking for and click.

The main frame at right will now contain the documentation for the class.

1005ICT Object Oriented Programming – 2015-2 93

When you are looking for a class, but you don’t know what package it’s in,there are ways to find it:

• If you click on All Classes at the top of the top-left frame, the lowerleft frame will list all of them.

• Along the top of the main frame at right are various ways to searchthe API, including a full alphabetic index.

This is very handy for finding individual methods as well as wholeclasses.

1005ICT Object Oriented Programming – 2015-2 94

5.3 Reading class Math

Our goal is to understand as much of this page as possible.

1005ICT Object Oriented Programming – 2015-2 95

These are navigation links that will take you away from this page.

These are navigation links within this page.

Most things are listed on the page twice; once in a brief summary and againin detail.

We can tell by which links are active, that this class has fields (variables)and methods, but no nested classes or constructors.

1005ICT Object Oriented Programming – 2015-2 96

This is the true heading of the page.

It tells us that this:

• belongs to package java.lang;

• is class Math; and

• is a direct subclass of class java.lang.Object.

What that means is for later when we discuss inheritance.

1005ICT Object Oriented Programming – 2015-2 97

This is the actual Java code that declares this class.

It tells us that this:

• is a public class called Math (public, class);

• is a direct subclass of class java.lang.Object(extends Object); and

• that it may not be subclassed itself (final).

This is not a class that is much involved in inheritance (subclassing),which is why it is a good place to start.

1005ICT Object Oriented Programming – 2015-2 98

The next part is a textual description of the class.

It ends with the version of Java that first included this class.

1005ICT Object Oriented Programming – 2015-2 99

Next come the good bits, the members of the class, starting with the sum-mary of the fields.

We can tell that these fields are constants, because their names are in allcapital letters.

1005ICT Object Oriented Programming – 2015-2 100

What can we tell about these constants?

• They are both static, that is, not dynamic, and can be used directlyfrom the class without the need to create objects.

• They are type double, double precision floating point numbers.

• We can also tell from the textual description what they mean.

It should also be noted that this list contains only the public fields.

Nothing private is documented in the API.

There may be private constants or variables, but we will never know.

1005ICT Object Oriented Programming – 2015-2 101

Next comes the very long summary of methods.

1005ICT Object Oriented Programming – 2015-2 102

What can we tell about these methods?

• They are all static, that is, not dynamic, and can be used directlyfrom the class without the need to create objects.

• They all have types, eg double, not void. So they are all functionsand not procedures.

• Some of them have the same names, but different parameter types.

• We can also tell from the textual description what they mean.

1005ICT Object Oriented Programming – 2015-2 103

Below the summaries, come the detailed descriptions.

They start with the full details of the declaration:

• public of course; and

• final making it a constant.

1005ICT Object Oriented Programming – 2015-2 104

Similarly for methods, providing more details, in particular about the pa-rameters.

1005ICT Object Oriented Programming – 2015-2 105

5.4 The design of class Math

What have we learned about this class?

• It contains only static members (fields and functions) that can beused directly from the class, without requiring the creation of dy-namic objects.

• It is a subclass of java.lang.Object, but that isn’t actually in-teresting because every class is a subclass of java.lang.Object.

• It can’t be subclassed itself final.

This class isn’t really used in an object oriented way at all.

It is really just a library of useful functions, a library class or static class.

1005ICT Object Oriented Programming – 2015-2 106

5.5 Example program using class Math

Write a program that simulates rolling a die, by printing a random wholenumber between and inclusive of 1 and 6.

We need a random number generation function.

Look it up in the API!

5.5.1 Version 1 – not reusable at all

/*** file: Die1.java

** author: Andrew Rock

** purpose: Prints a random number in [1..6].

*/

public class Die1 {1005ICT Object Oriented Programming – 2015-2 107

public static void main(String [] args) {System.out.println(

(int) (Math.random() * 6.0) + 1);}

}

Notes:

• No need to declare a package.

• No need to import anything.

• We must qualify random() with Math.

1005ICT Object Oriented Programming – 2015-2 108

$ javac Die1.java$ java Die15$ java Die15$ java Die14$ java Die11$ java Die14$ java Die16$

1005ICT Object Oriented Programming – 2015-2 109

5.5.2 Version 2 – with a function

The calculation of a random die result is useful in many programs.

It is worth separating out as a separate function.

/*** file: Die2.java

** author: Andrew Rock

** purpose: Prints a random number in [1..6].

*/

public class Die2 {

public static void main(String [] args) {System.out.println(die());

}

1005ICT Object Oriented Programming – 2015-2 110

// die() returns a random number in [1..6].public static int die() {

return (int) (Math.random() * 6.0) + 1;}

}

Notes:

• I made this function public, though private would work too. Itis only used within the same class.

• The function is static. It must be, as we are not creating any dy-namic objects.

• We don’t need to qualify the call to die() as it is in the same class.

1005ICT Object Oriented Programming – 2015-2 111

5.5.3 Version 3 – with a function in its own class

To make the function truly reusable, it needs to be available for multipleprograms to use.

We can put the reusable part of the program, the function, in a class of itsown.

We can emulate the design of java.lang.Math, with only staticmembers.

Put each class in a separate file, in the same folder.

1005ICT Object Oriented Programming – 2015-2 112

/*** file: Die.java

** author: Andrew Rock

** purpose: Static class providing a die() function.

*/

public class Die {

// die() returns a random number in [1..6].public static int die() {

return (int) (Math.random() * 6.0) + 1;}

}

Note: This class, like most Java classes has no main method.

1005ICT Object Oriented Programming – 2015-2 113

/*** file: Die3.java

** author: Andrew Rock

** purpose: Prints a random number in [1..6].

*/

public class Die3 {

public static void main(String [] args) {System.out.println(Die.die());

}

}

Note: We still don’t need to import anything as class Die is in the sameunnamed package.

1005ICT Object Oriented Programming – 2015-2 114

We now have two classes to compile, in the right order.

$ javac Die.java$ javac Die3.java$ java Die32$

1005ICT Object Oriented Programming – 2015-2 115

5.6 Section summary

This section covered:

• how to find a class in the Java API;

• how to read the page for a class in the API;

• that java.lang.Math is just a library of static constants andfunctions;

• how to create our own static class; and

• how to compile and run a program consisting of two classes.

1005ICT Object Oriented Programming – 2015-2 116

5.7 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 117

6 Basic Java Data Types

This section reprises the basic Java data types, and introduces a few more.

1005ICT Object Oriented Programming – 2015-2 118

6.1 Simple data types

Java is not a purely object-oriented programming language.

It does have its simple (or primitive or atomic) data types, like C and Pascaland older languages.

Ultimately the objects we create will store their data in these simple types.

Here are the important simple types:

• boolean – the logical values of false or true;

1005ICT Object Oriented Programming – 2015-2 119

• the integral types:

– byte – 8 bits, signed, from -128 (−27) to 127 (27 − 1).

– short – 16 bits, signed, from -32768 (−215) to 32767 (215−1).

– int – 32 bits, signed, from -2147483648 (−231) to 2147483647(231 − 1).

– long – 64 bits, signed, from -9223372036854775808 (−263) to9223372036854775807 (263 − 1).

– char – 16 bits, unsigned, from 0 to 65535 (216−1), for Unicodevalues.

• the floating point types:

– float – 32 bits.

– double – 64 bits.

1005ICT Object Oriented Programming – 2015-2 120

6.2 Compound data types

The compound types allow us to aggregate multiple simple values.

6.2.1 Strings

All languages have some way to store character sequences, strings.

Java has type String, which is a class.

String will be the subject of an upcoming case study.

1005ICT Object Oriented Programming – 2015-2 121

6.2.2 Arrays

Arrays are so useful, they are built into the language.

An array is a collection of element values in a sequence.

The elements can be accessed by their index (position) in the array.

Java arrays are dynamic!

They are allocated (memory) at run time.

Their size may be set at the time they are allocated, but then remains fixed.

double[] a = new double[requiredSize];

1005ICT Object Oriented Programming – 2015-2 122

Setting an array element

a[i] = x;

Using an array element

System.out.println(a[i]);

The length of an array

A Java array has an extra trick, it has a .length property.

Since most arrays are made just big enough for the data they actually hold,this is common:

for (int i = 0; i < a.length; i = i + 1) { ...

1005ICT Object Oriented Programming – 2015-2 123

6.2.3 Classes

Arrays only let us aggregate elements that are all of the same type.

Arrays were invented for programmers creating Maths applications, whereall you need is numbers or lots of numbers.

Programmers working in a broader range of application domains need toaggregate values of different types.

Pascal does this with records, C does it with structures.

Java has neither of these, but it does have the equivalent. It has classes.

Every class we define is defining a new data type.

The global variables we declare in it are the properties, fields or attributes(all synonyms).

1005ICT Object Oriented Programming – 2015-2 124

Static classes

We studied java.lang.Math.

That was one extreme of how classes may be designed.

It contained only static constants and functions.

It was never intended to be used to create dynamic objects.

Dynamic data-only classes

We now consider the other extreme!

We can make classes purely for the storage of data, usually for the purposeof aggregating values with (often) different types.

1005ICT Object Oriented Programming – 2015-2 125

Example scenario, a game has multiple soldier characters spread across abattlefield.

Each soldier has a name, health, experience, and location.

public class Soldier {public String name;public int health;public int experience;public Location location;

}

This should be put in its own file, Soldier.java.

This type aggregates a String, two ints, and a Location

What’s a Location?

1005ICT Object Oriented Programming – 2015-2 126

public class Location {public int x;public int y;

}

A battlefield is a collection of soldiers.

public class Battlefield {public Soldier[] soldiers;

}

What we have done is define classes.

None of the fields (the variables) were declared static.

So none of these dynamic variables actually exist until we create them atrun-time.

1005ICT Object Oriented Programming – 2015-2 127

Note also that all of the fields were declared public.

They have to be, because the code that will give them values is somewhereelse.

An actual dynamic object created from a class (as its template) is called aninstance of the class.

The process of creating an object and allocating memory for it is calledinstantiation.

We do it with the new keyword, similar to the way we allocate arrays.

Battlefield b = new Battlefield();

Note the parentheses, not square brackets.

It looks a bit like calling a method, doesn’t it?

1005ICT Object Oriented Programming – 2015-2 128

Having created a BattleField we need to allocate its array field.

b.soldiers = new Soldier[100];

Then we can instantiate all of the individual Soldiers and theirLocations.

for (int i = 0; i < b.soldiers.length; i = i + 1) {b.soldiers[i] = new Soldier();b.soldiers[i].name = "Unknown";b.soldiers[i].health = 100;b.soldiers[i].experience = 0;b.soldiers[i].location = new Location();b.soldiers[i].location.x = 0;b.soldiers[i].location.y = 0;

}

1005ICT Object Oriented Programming – 2015-2 129

This style of programming is possible in Java, but it is not common.

It is not really object oriented.

It could almost be C.

One big problem is that all the fields have to be public.

This makes them all available for modification by any code anywhere.

In fact the code that instantiates and initialises them is somewhere else.

1005ICT Object Oriented Programming – 2015-2 130

Dynamic object classes

Let’s write new versions that are more object oriented.

We’ll add something new, constructors.

public class Location {

private int x;private int y;

public Location(int newX, int newY) {x = newX;y = newY;

}

}

1005ICT Object Oriented Programming – 2015-2 131

We made the fields private.

We added a constructor, which is like a procedure for initialising the fieldsof an object.

A constructor must have the same name as the class.

A constructor does not have a type or void in front.

This constructor has parameters with which we can provide initial coordi-nates.

This is not always required.

Note how this constructor is used in class Soldier.

1005ICT Object Oriented Programming – 2015-2 132

public class Soldier {

private String name;private int health;private int experience;private Location location;

public Soldier() {name = "Unknown";health = 100;experience = 0;location = new Location(0, 0);

}

}

1005ICT Object Oriented Programming – 2015-2 133

public class Battlefield {

private Soldier[] soldiers;

// n is the number of soldiers to placepublic Battlefield(int n) {

soldiers = new Soldier[n];for (int i = 0; i < n; i = i + 1) {

soldiers[i] = new Soldier();}

}

}

1005ICT Object Oriented Programming – 2015-2 134

Then to create a Battlefield and all its soldiers, we just need:

Battlefield b = new Battlefield(100);

We have packaged the code that does things to the fields in the classes them-selves.

This is true object oriented programming.

To continue development of this example, we would add more methods toeach of the classes.

To really see how object oriented programming is really done, it is time tolook at some examples from the API.

1005ICT Object Oriented Programming – 2015-2 135

6.3 Section summary

This section covered:

• Java’s simple data types;

• Java’s main compound data types:

– arrays; and

– classes;

• objects; and

• constructors.

1005ICT Object Oriented Programming – 2015-2 136

6.4 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 137

7 Case Study: Class java.lang.String

This section takes a close look at class java.lang.String.

Learning to use this class shows how to use many classes.

1005ICT Object Oriented Programming – 2015-2 138

7.1 String API overview

7.1.1 Heading

The package is java.lang.

We will discuss interfaces after inheritance.

1005ICT Object Oriented Programming – 2015-2 139

Strings, like arrays, are a bit special, in that they are built into the Javalanguage.

String literals, like "abc" are stored as instances of this class.

Strings, are immutable, that is, once created, can not be modified.

This means that Strings may be shared by different parts of a program,and can be trusted to stay the same.

1005ICT Object Oriented Programming – 2015-2 140

7.1.2 Fields

There is one field, but it is something that supports sorting.

There is no direct access to the characters stored in the string.

We can guess that each string object will contain an array of characters, butit is private.

1005ICT Object Oriented Programming – 2015-2 141

7.1.3 Constructors

Strings are meant to be created to store character data, so there are plentyof ways provided to do so, that is plenty of constructors (15!).

1005ICT Object Oriented Programming – 2015-2 142

Some of these constructors are marked “Deprecated”.

This means that this is an old version, that should not be used for new code,and is only provided for backward compatibility with old programs.

1005ICT Object Oriented Programming – 2015-2 143

7.1.4 Methods

There are many methods in class String.

Most are dynamic (to be used with objects), though some are static (tobe used with the class).

Of all of them, these two are the most important:

1005ICT Object Oriented Programming – 2015-2 144

From those two, most of the others can be created, because they provideaccess to the character data in the String.

This is very common and important.

If variables (fields) are public, then anyone can access and change them.

It is usually better to make the fields private, and to provide read-onlyaccess to them via methods.

A method that provides access to the data in an object is called an accessor.

There are many more methods, take the time to browse the API yourself.

We will be using many of them through the rest of the course.

1005ICT Object Oriented Programming – 2015-2 145

7.2 Using strings

All strings are dynamic objects.

A deep understanding of what they are and how they are stored helps usunderstand all objects.

1005ICT Object Oriented Programming – 2015-2 146

7.2.1 Class String

The class String defines its fields, methods and constructors.

All of these things are called the members of the class.

The class has a dual role:

• to encapsulate all of these members – in doing so it gathers together(in one place) how strings are to be made, stored and used; and

• defines the new type String – that allows the creation of dynamicString instances (objects).

1005ICT Object Oriented Programming – 2015-2 147

7.2.2 String objects

To actually store character sequences, we create, at run-time, dynamic Stringobjects, which are instances of class String.

The process of creating an instance is called instantiation.

The practical issue involved with creating a new object is finding a contigu-ous patch of RAM (random access memory) big enough to store it.

As a program runs, it can create and destroy millions of objects.

Finding a patch of memory can sometimes be a slow process.

If one program creates fewer dynamic objects than another, to get the samework done, it will be faster, and more efficient.

1005ICT Object Oriented Programming – 2015-2 148

So you’ve just made a string, somewhere in RAM. Where is it?

Among all those objects, which one is your particular string?

1005ICT Object Oriented Programming – 2015-2 149

7.2.3 String references

Addresses

The way we identify individual objects is by remembering exactly where itis in memory.

Where something is in RAM is its address, the unique number of the bytein RAM where the object starts.

Pointers

Older languages, like C and Pascal, had special types of variables that storedan address, and called them pointers.

Pointers were numbers that could be directly manipulated to access any-where in RAM, which is the source of many bugs and are exploited bymalware.

1005ICT Object Oriented Programming – 2015-2 150

References

References in Java are pointers that the language only permits limited oper-ations on.

The limits are imposed to make Java software more secure.

How do we create a reference variable?

The truth is, every time we have made a String variable, we made areference variable.

1005ICT Object Oriented Programming – 2015-2 151

String s = "Boo!";

Boo!

s

The variable s is the reference, not the object.

1005ICT Object Oriented Programming – 2015-2 152

What are the limited things that we can do with references?

• We can compare references with == and != to see if they are equalor not, that is, pointing to the same object.

• We can dereference them, with the period (.).

Dereferencing means following the reference to where it points to accessthe object’s members.

For example to access the first character in a string:

char first = s.charAt(0);

1005ICT Object Oriented Programming – 2015-2 153

null

With objects being dynamic, coming and going at run-time, sometimes wewant to have a reference that currently doesn’t point at any object.

For this Java has the special value null.

A reference variable can be compared with == to see if it currently pointsto an object or not.

1005ICT Object Oriented Programming – 2015-2 154

Garbage

The only way we can access an object is by dereferencing a reference.

If we break the connection, by changing that reference, we can no longeraccess the object.

String s = "Boo!";s = "Who!";

Boo!

s

Who!

1005ICT Object Oriented Programming – 2015-2 155

Objects that can’t be used, because there are no references to them at all,are a useless waste of memory, garbage.

For older languages like C++, it’s up to programmers to delete their objects.

If they don’t clean up their old objects, the memory they have fills up withgarbage.

This kind of defect is called a space leak.

1005ICT Object Oriented Programming – 2015-2 156

Garbage collection

The JVM keeps a count of how many references point to every object.

If the count drops to zero, then the JVM can identify that an object isgarbage.

When memory gets low, the JVM can deallocate the garbage, to free thememory.

This process is called garbage collection.

It is still possible to have space leaks in Java programs, if the objects wedon’t really want any more are still referenced.

You can break the connection by assigning null to the reference.

The garbage collection thread can then clean it up.

1005ICT Object Oriented Programming – 2015-2 157

7.3 Equality for strings

The following series of example programs give some expected and someunexpected results.

public class Equals1 {public static void main(String[] args) {

String s = "Boo!";String t = "Who!";System.out.println(s == t);

}}

prints false.

Not surprising.

1005ICT Object Oriented Programming – 2015-2 158

public class Equals2 {public static void main(String[] args) {

String s = args[0];String t = args[1];System.out.println(s == t);

}}

$ java Equals2 Boo! Who!false$

Not surprising.

But wait...

1005ICT Object Oriented Programming – 2015-2 159

$ java Equals2 Boo! Boo!false$

Remember that == compares the references to see if they are pointing to thesame object.

In this case they are not.

To see if two different string objects contain exactly the same characters, useone String’s equals method to see if it contains the same characters asanother.

1005ICT Object Oriented Programming – 2015-2 160

public class Equals3 {public static void main(String[] args) {

String s = args[0];String t = args[1];System.out.println(s.equals(t));

}}

$ java Equals3 Boo! Who!false$ java Equals3 Boo! Boo!true$

That’s better. We think we have it all worked out now. Heh, heh...

1005ICT Object Oriented Programming – 2015-2 161

public class Equals4 {public static void main(String[] args) {

String s = "Boo!";String t = "Boo!";System.out.println(s == t);

}}

$ java Equals4true$

The Java compiler works very hard to save memory. If the same stringliteral appears in multiple places, it is stored in just one object.

It is only safe to do it this way, because the string objects are immutable.

1005ICT Object Oriented Programming – 2015-2 162

7.4 Building strings

We have been using + to concatenate strings, and there is nothing wrongwith doing that.

However, if we are building a lot of strings out of small pieces, it can bevery inefficient, because strings are immutable.

Every time we use a statement like:

aString = aString + aChar;

we are creating a whole new string object and making the old one garbagethat must be collected.

The solution is to not always use the immutable String type.

Java has mutable alternatives, StringBuffer and StringBuilder.

1005ICT Object Oriented Programming – 2015-2 163

7.5 Unicode consequences

The characters in strings could be anything from the vast Unicode set.

Don’t try to write your own character conversion functions, like changingcase, because there are many more kinds of letters than we know, and youwon’t cover them all.

Fortunately all these kinds of operations are provided in classes Characterand String.

Always check the API first, to see if what you need isn’t already there.

1005ICT Object Oriented Programming – 2015-2 164

7.6 The design of class String

This class is an example of the classic abstract data type.

It defines a type for storing information, but hides the storage details.

What it also provides is the suite of operations that can be performed onthat type.

String is a very typical example of the majority of classes in the JavaAPI, a mix of data storage (state) and operations on it.

Our previous case study subject Math was not so typical.

Understanding String is an important step in learning object oriented pro-gramming.

1005ICT Object Oriented Programming – 2015-2 165

7.7 Section summary

This section covered:

• another look at the API documentation for an important Java class,String;

• the meaning of “deprecated”;

• the basic string accessor methods;

• the relationship and nature of the String class, objects and refer-ences;

• the null reference;

• garbage collection; and

• what equality means for objects and references.1005ICT Object Oriented Programming – 2015-2 166

7.8 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 167

7.9 Self-practice exercises

1. Write a program that accepts two string command line arguments andprints the number of times that the first string can be found in thesecond string. (MaSH Online Judge problem-id: 0507-howMany)

2. Write a program that accepts three string command line argumentsand prints the third string, but with all occurrences of the first stringreplaced by the second string. (MaSH Online Judge problem-id:0508-replaceAll)

1005ICT Object Oriented Programming – 2015-2 168

8 Case Study: java.util.Scanner

This section examines class java.util.Scanner.

This class is another excellent example of true object oriented program-ming.

It combines a hidden, mutable state, with the operations that may be per-formed with it.

It is also very useful for reading data from the keyboard or files.

1005ICT Object Oriented Programming – 2015-2 169

8.1 Purpose

Most programs accept input from some source, keyboards, files or networkconnections.

At the lowest level, input is about ingesting (reading) a stream of bytes.

But usually those bytes need to be aggregated into strings, lines, words,numbers or tokens.

A Scanner is an object that performs this aggregation (called scanning),for any stream of bytes.

1005ICT Object Oriented Programming – 2015-2 170

8.2 Design

The fundamental design of class Scanner is different to the subjects ofthe previous case studies.

java.lang.Math is purely a library of static functions and constants.

Each java.lang.String object does contain (though hidden) a vari-able, the array of characters. However once created the String’s variableis never changed.

A java.util.Scanner instance contains hidden (private) variables,and these variables must change as it is used.

We say that these objects maintain a mutable state.

1005ICT Object Oriented Programming – 2015-2 171

8.3 Members

8.3.1 Fields

None – that are public anyway.

8.3.2 Constructors

Scanner has many constructors.

All of them have arguments. There is no constructor that has no arguments.

That means before any Scanner object can be created, some informationmust be provided to initialise the object’s internal hidden fields.

Each constructor provides the Scanner with the source of bytes it is toscan.

1005ICT Object Oriented Programming – 2015-2 172

This is the constructor we will use most.

The argument required is a java.io.InputStream.

One of those exists already for us to use, java.lang.System.in,which is the standard stream input.

1005ICT Object Oriented Programming – 2015-2 173

This constructor makes a Scanner that scans a string.

1005ICT Object Oriented Programming – 2015-2 174

This constructor makes a Scanner that scans a disk file.

However, we aren’t ready to use this one yet, as if the file we try to readfrom does not exist, this constructor throws an exception.

We need to learn about exceptions as soon as we can.1005ICT Object Oriented Programming – 2015-2 175

8.3.3 Methods

This class has many methods.

None of them are static. So they are all methods that operate on Scannerinstances.

The most important of them are all called nextSomething() orhasNextSomething().

The nextSomething() methods are functions that return the nextSomething scanned from the scanner’s source.

The hasNextSomething() methods are functions that return the trueif and only if nextSomething() could successfully return a Something.

(For those who did MaSH, mashc translated readSomething() intonextSomething() and isNextSomething() intohasNextSomething().)

1005ICT Object Oriented Programming – 2015-2 176

For example there are these pairs of methods:

int nextInt() boolean hasNextInt()long nextLong() boolean hasNextLong()double nextDouble() boolean hasNextDouble()String nextLine() boolean hasNextLine()String next() boolean hasNext()

The last pair (without any Something) are for tokens.

Normally a token is a sequence of non-whitespace characters, delimited bywhitespace, but there are methods in class Scanner to vary this definition.

(MaSH: readWord(), isNextWord().)

1005ICT Object Oriented Programming – 2015-2 177

8.4 State

How do we know that a Scanner instance maintains an internal state?

Because every time we call nextSomething(), we do indeed get thenext one, and not the same one every time.

Because it maintains an internal state, and provides services via its methods,Scanner is a classic example of true object oriented programming.

1005ICT Object Oriented Programming – 2015-2 178

8.5 Example: Average

A simple program that uses a Scanner to read numbers:

/*** file: Average.java

** author: Andrew Rock

** use: java Average < numbers

** prints the average of all the numbers

** read from standard input.

*/

import java.util.*;

public class Average {

1005ICT Object Oriented Programming – 2015-2 179

public static void main(String[] args) {Scanner sc = new Scanner(System.in);double total = 0.0;int n = 0;while (sc.hasNextDouble()) {

total = total + sc.nextDouble();n = n + 1;

}System.out.println("Average = " + total / n);

}

}

1005ICT Object Oriented Programming – 2015-2 180

8.6 Example: MovingAverage

In this example we will create a new, reusable class that defines objects thatmaintain a complex mutable state, and provide services via methods.

A problem: A moving average is used to reveal the underlying trends in anoisy series of values.

For example, this chart shows the underemployment rate for Australia since1978.

There are lots of small wiggles in the series, that are probably not signifi-cant.

1005ICT Object Oriented Programming – 2015-2 181

0.0#

1.0#

2.0#

3.0#

4.0#

5.0#

6.0#

7.0#

8.0#

9.0#1# 5# 9# 13#

17#

21#

25#

29#

33#

37#

41#

45#

49#

53#

57#

61#

65#

69#

73#

77#

81#

85#

89#

93#

97#

101#

105#

109#

113#

117#

121#

125#

129#

133#

Australian*Underemployment*Rate*

original#

1005ICT Object Oriented Programming – 2015-2 182

A moving average is calculated for each value in the series by averaging anumber of sequential values in the series.

A moving average can be calculated for each original value and its neigh-bours.

8.6.1 Design

We will design a reusable class that calculates moving averages efficiently.

1005ICT Object Oriented Programming – 2015-2 183

Fields

• An inefficient class would add up all the neighbouring values for ev-ery value.

An efficient class would add each new value to a rolling total andsubtract the oldest value.

In order to subtract them, the values themselves need to be remem-bered for a little while.

So we need an array of values, the size of which is the number ofvalues to be included in each moving average.

• It needs the rolling total.

• It needs the number of values to use to include in the moving average.

• It needs the number of values that have actually been added into thetotal so far.

1005ICT Object Oriented Programming – 2015-2 184

Constructor

A constructor is needed to initialise all of the fields.

What the moving average object needs to know first is how many values aregoing to be used for each moving average.

That will be the argument for the constructor.

With that information, the array can be instantiated with the right size.

1005ICT Object Oriented Programming – 2015-2 185

Methods

At a minimum, these methods are needed.

• A method to add a new value into the rolling total.

• A method to access the current moving average.

There could be more.

1005ICT Object Oriented Programming – 2015-2 186

8.6.2 Implementation

The implementation is the actual Java code that realises the design.

Class

/*** file: MovingAverage.java

** author: Andrew Rock

** purpose: Maintains a moving average of a series

** of values.

*/

public class MovingAverage {

}

1005ICT Object Oriented Programming – 2015-2 187

Fields

// the number of values to average overprivate int span;

At the time we are writing this code, we don’t know how many values areto be included in the moving average, so we can not initialise this variablehere.

All the variables (fields) will be private!

All of the fields and methods will be dynamic (not static).

1005ICT Object Oriented Programming – 2015-2 188

// the values of the current averageprivate double[] values;

We can’t instantiate the array yet, because we don’t know how big it needsto be.

// the number of values available for the// current averageprivate int count = 0;

// the position to save the next valueprivate int next = 0;

We do know that as a MovingAverage object is created, there are novalues yet, so we can initialise these variables here.

1005ICT Object Oriented Programming – 2015-2 189

// the rolling total of the valuesprivate double total = 0.0;

1005ICT Object Oriented Programming – 2015-2 190

Constructor

// new MovingAverage(n) instantiates a new// MovingAverage that will average over up to// n values.public MovingAverage(int n) {

span = n;values = new double[span];

}

The constructor has an argument that provides the number of values to av-erage over.

The constructor must have the same name as the class, and has no returntype, not even void.

1005ICT Object Oriented Programming – 2015-2 191

Methods

// addValue(value) adds this new value to the// moving average.public void addValue(double value) {

total = total - values[next] + value;values[next] = value;count = Math.min(count + 1, span);next = (next + 1) % span;

}

This is the only complicated method.

The exact detail of how it works is less important to understand than whatit says it does.

1005ICT Object Oriented Programming – 2015-2 192

// hasAverage() returns true iff there is at// least one value from which to calculate an// average.public boolean hasAverage() {

return count > 0;}

// getAverage() returns the current average.// precondition: hasAverage() returns true.public double getAverage() {

return total / count;}

hasAverage() is provided to make getAverage() safer to use.

What is the risk?

1005ICT Object Oriented Programming – 2015-2 193

8.6.3 Client program

This is a simple program that uses the MovingAverage class.

/*** file: Smooth.java

** author: Andrew Rock

** use: java Smooth span < series

** Prints the moving average for every

** input values in a series read from

** standard input.

** span is the maximum number of points

** to include in each average

*/

import java.util.*;

1005ICT Object Oriented Programming – 2015-2 194

public class Smooth {

public static void main(String[] args) {int span = Integer.parseInt(args[0]);Scanner sc = new Scanner(System.in);MovingAverage ma = new MovingAverage(span);while (sc.hasNextDouble()) {

ma.addValue(sc.nextDouble());System.out.println(ma.getAverage());

}}

}

The following chart compares the original data with the moving averagecalculated with a span of 11.

1005ICT Object Oriented Programming – 2015-2 195

0.0#

1.0#

2.0#

3.0#

4.0#

5.0#

6.0#

7.0#

8.0#

9.0#

1# 5# 9# 13#

17#

21#

25#

29#

33#

37#

41#

45#

49#

53#

57#

61#

65#

69#

73#

77#

81#

85#

89#

93#

97#

101#

105#

109#

113#

117#

121#

125#

129#

133#

original#

avg11#

1005ICT Object Oriented Programming – 2015-2 196

8.7 Section summary

This section covered:

• an introduction to class java.util.Scanner;

• how to use it;

• its design;

• a simple example program that used a Scanner; and

• a more complex example where we used the same design pattern asScanner to create our own reusable class with a mutable state.

1005ICT Object Oriented Programming – 2015-2 197

8.8 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 198

8.9 Self-practice exercises

1. Write a program that accepts one string command line argument andprints the number of times that this string can be found in all of stan-dard input.

2. Write a program that accepts two string command line arguments andprints all of standard input, but with all occurrences of the first stringreplaced by the second string.

1005ICT Object Oriented Programming – 2015-2 199

9 Essential Object Oriented Programming

This section brings together the essential elements of object oriented pro-gramming, including inheritance, and introduces UML class diagrams.

This theory section is very long, even without code examples. Examplecode will follow API case studies which show these ideas in practice.

9.1 Review of definitions

We have encountered a lot of new ideas so far in this course.

Here is a review in the form of a list of definitions:

1005ICT Object Oriented Programming – 2015-2 200

9.1.1 Static versus dynamic

Anything that is created, defined or bound at compile time is static.

Anything that is created, defined or bound at run time is dynamic.

Examples:

• If we declare that a variable i has type int, then that type is stati-cally bound to that variable, but the values assigned at run time to thevariable are dynamically bound.

• If a compiler copies all of the object code for library subprogramsinto the executable file for a program, that is static linking.

If the library object code is only accessed at run time, as needed, thenthat is dynamic linking.

Java classes are loaded at run time, hence are dynamically linked.

1005ICT Object Oriented Programming – 2015-2 201

• If a method or variable is defined in a Java class as static, thenthere is just one of them defined, it belongs to the class itself, and isavailable to use before any dynamic objects are created.

If a method or variable is not static, dynamic objects have to becreated before they can be used, as many copies are created as objects,and they belong to the objects.

• Static methods or variables are often called class methods or variables

• Dynamic methods or variables are often called instance methods orvariables

1005ICT Object Oriented Programming – 2015-2 202

9.1.2 Packages

Packages are collections of classes.

1005ICT Object Oriented Programming – 2015-2 203

9.1.3 Classes

Nearly all Java code is encapsulated in a class which:

• can act as a simple container for related static subprograms and con-stants, e.g. java.lang.Math;

• can act as an abstract data object, maintaining a single static collec-tion of data (state), and providing the services (operations) that canbe performed with that state;

• can act as an abstract data type, providing a template for dynamicobjects each of which maintains its own state and the operations thatcan be performed with it.

A class may mix and match these patterns, but good designs are usually justone of them.

1005ICT Object Oriented Programming – 2015-2 204

9.1.4 Fields, properties, attributes

The global (declared outside of any method) variables of a class are itsfields, properties, or attributes.

All of these are synonyms.

They make up the state of the class (if static) or objects (if dynamic).

9.1.5 Methods

The functions and procedures in a class are its methods.

They implement the services that the class or objects provide.

1005ICT Object Oriented Programming – 2015-2 205

9.1.6 Constructors

The special subprograms that are called when an object is created, are calledconstructors.

Their main purpose is to initialise the state of new dynamic objects.

9.1.7 Members of a class

The members of a class are its fields, methods, constructors, and anythingelse declared at the top level in the class.

1005ICT Object Oriented Programming – 2015-2 206

9.1.8 Instances of a class

The instances of a class are the objects created using a class as a template.

The object will include all of the dynamic fields and methods defined in theclass.

It is common to say that the class acts as a blueprint or template for theobjects.

Creating a new object (instance) is called instantiation.

1005ICT Object Oriented Programming – 2015-2 207

9.2 New definitions

9.2.1 Accessors and mutators

It is common (and recommended) that all of the fields of an object beprivate.

To provide read-only access to a field, we provide a function that returns itsvalue.

Such a function is called an accessor and they are usually named getThing().

A mutator is a procedure that allows a field to be changed, and usuallynamed setThing().

Why not just make the field public? As well as changing the field, theprocedure can update other fields that depend on it or carry out some action.

1005ICT Object Oriented Programming – 2015-2 208

9.2.2 Message passing

When you read about object oriented programming, you see the term mes-sage passing.

It occurs when one object sends information to, or requests a service ofanother.

This is done by one object calling another’s method.

The first object sends information as the method’s actual parameters, andthe the second object can send information back as a function’s result (orby calling back to one of the first object’s methods).

1005ICT Object Oriented Programming – 2015-2 209

9.2.3 Object oriented programming

Object oriented programming is commonly defined as viewing a programas a collection of objects, where each object:

• maintains its own state;

• provides services; and

• communicates with and requests services of other objects by messagepassing.

The advantages of this style of programming follow from the fact that ob-jects are all cooperating, but still fairly autonomous little virtual machines.

1005ICT Object Oriented Programming – 2015-2 210

Separating a large program into objects facilitates code reuse and allowslarge teams to collaborate in large projects.

But actually all of this can be achieved with abstract data objects and types.

The common definition of object oriented programming always includesjust one more thing: inheritance.

1005ICT Object Oriented Programming – 2015-2 211

9.2.4 Object oriented design

Object oriented design is the process of problem solving and software de-sign by decomposing a solution or program into interacting objects.

The emphasis is typically on the representation or modelling of the piecesand actors in a problem as separate objects.

The design can go as far as defining the state that needs to be maintained byeach object and the services to be provided.

It is common for object oriented designs to be supported or expressed withdiagrams.

1005ICT Object Oriented Programming – 2015-2 212

9.3 Inheritance

When performing an object oriented design, we try to identify the distinctobjects that represent the situation, and we design a class for each.

For instance, in an information system for this university, we need to main-tain records for thousands of people.

To uniquely identify any person we need at least their:

• name;

• birthdate; and

• address.

1005ICT Object Oriented Programming – 2015-2 213

However only some people have a formal relationship with the university,as councillors, staff, students, alumni, or affiliates.

All of them are called members of the university.

All members of the university have a unique identification number(Snnnnnnn).

These members are a subset of all people.

In turn, students, staff, etc. are subsets of the members.

The information system will need to record different information for stu-dents and staff.

Inheritance in object oriented programming languages is about expressingthis subset/superset relationship as a relationship between classes.

The name class is chosen to be similar to set.

1005ICT Object Oriented Programming – 2015-2 214

Most people are familiar with Venn diagrams.

Staff

People

Students

Councillors

Affiliates

Members

Diagrams are useful for helping to communicate complicated situations.

1005ICT Object Oriented Programming – 2015-2 215

9.3.1 Diagramming inheritance in UML

This is a Unified Modelling Language (UML) class diagram of the samesituation.

Person

Member

Councillor Staff Student Affiliate

1005ICT Object Oriented Programming – 2015-2 216

A diagram like this looks a lot like a family tree, hence inheritance.

UML is very much the industry standard for software design.

It contains many types of diagramming notations for many aspects of soft-ware design.

The class designs are the most commonly used.

Everyone that does object oriented programming and design needs to beable to read at least simple UML class diagrams.

Classes

Classes are drawn as boxes.

SomeClass

1005ICT Object Oriented Programming – 2015-2 217

Inheritance

An arrow with a big triangle arrowhead, usuallyat the higher end, indicates the inheritance rela-tionship between two classes.

The subclass inherits all or some of its membersfrom the superclass.

Superclass

Subclass

Colour and shading

The colours and shading don’t mean anything. Add them for emphasis, orto make it pretty.

1005ICT Object Oriented Programming – 2015-2 218

9.3.2 Practical uses for inheritance

The inheritance relationship between classes is not just a mathematicalnicety, it has practical uses to minimise the cost of software developmentand maintenance.

The inheritance is quite literal.

If a subclass inherits from its superclass, it gets all of the members of thatclass for free, without having to rewrite them.

This is a new way to reuse code.

If the superclass gets some maintenance, the changes automatically flowthrough to all its subclasses.

1005ICT Object Oriented Programming – 2015-2 219

9.3.3 extends

In Java the keyword that is used to declare the inheritance relationship isextends.

A new subclass declares that it extends its single direct superclass.

The words is extends, because the new subclass has all of the membersof the superclass, and then, usually, defines some more.

The syntax of a normal class now becomes:

normalClassDeclaration

classBody

typeextends

identifierclass

classModifier

1005ICT Object Oriented Programming – 2015-2 220

9.3.4 java.lang.Object

Every class has exactly one direct superclass.

If it does not have an extends declaration, then it implicitly extendsjava.lang.Object.

1005ICT Object Oriented Programming – 2015-2 221

9.3.5 protected

Inheritance creates the need for a new visibility modifier for the membersof a class.

public makes a member visible to any other class.

private makes a member invisible to all other classes.

protected makes a member visible only to subclasses of the class.

1005ICT Object Oriented Programming – 2015-2 222

9.3.6 final classes

A class declared with the modifier final may not be subclassed.

1005ICT Object Oriented Programming – 2015-2 223

9.3.7 Polymorphism

Polymorphism means many forms.

In programming is means situations where different kinds of data can behandled in what appears to be exactly the same way.

Overloading – ad hoc polymorphism

One form of polymorphism is using the one method name, but with manydifferent implementations to handle different data types.

For example in java.lang.Math we have abs(int), abs(long),abs(double), ...

Ad hoc (to this) polymorphism requires writing many many versions of thesame method.

1005ICT Object Oriented Programming – 2015-2 224

Inclusion polymorphism

This is an important and useful consequence of inheritance.

Since class Student extends class Member, an object which is an in-stance of Student would have all the fields and methods of a Member,and of a Person, for that matter.

A Student object could be used in every way that a Member or Personcould be used.

So a method that expects a Person object as a parameter, should workperfectly well, if given a Member, Student, Staff, or any of Person’ssubclasses.

Inclusion polymorphism means a method need only be written once, but canhandle many types.

1005ICT Object Oriented Programming – 2015-2 225

9.3.8 Abstract classes

In our university model, class Member is an oddity.

A Person might have no formal relationship with the university, yet stillappear in the system, e.g. as a next of kin.

But a Member would also necessarily have some formal relationship withthe university, e.g. as a Student or Councillor.

Therefore there is no need to actually instantiate Member objects.

The class modifier abstract makes it impossible to instantiate instancesof that class.

The class intended to be used by subclassing (extending) it only.

Abstract classes are useful for defining the limits of inclusion polymor-phism.

1005ICT Object Oriented Programming – 2015-2 226

In UML, abstract classes are italisised.

Person

Member

Councillor Staff Student Affiliate

1005ICT Object Oriented Programming – 2015-2 227

9.4 Section summary

This section covered:

• a summary of definitions of ideas we have met before, static, dy-namic, packages, classes, fields, methods, constructors, members,and instances;

• some new definitions crucial to object oriented programming, acces-sors, mutators, message passing object oriented programming, objectoriented design;

• inheritance, the extends keyword, java.lang.Object,protected, final classes, abstract classes;

• ad hoc polymorphism, inclusion polymorphism; and

• UML class diagrams with inheritance.

1005ICT Object Oriented Programming – 2015-2 228

9.5 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 229

10 Case Study: Number Classes

This section looks at an example set of classes that are associated by inher-itance.

Many of these classes seem to be interchangeable with some of Java’s sim-ple types.

Why do they exist at all?

1005ICT Object Oriented Programming – 2015-2 230

10.1 java.lang.Double

We are all familiar with Java’s simple type double, but Java also has theclass Double.

In the API, Double is declared as follows:

public final class Doubleextends Number

Its full list of its superclasses is depicted in the UMLclass diagram at right.

Object

Number

Double

1005ICT Object Oriented Programming – 2015-2 231

A common mistake is to type Double as the type of variables, instead ofjust double.

In early versions of Java this was indeed an error and the compiler wouldreport it.

Now however, the compiler is quite happy with either.

Because of the overheads involved in creating and destroying objects, forefficiency, double should usually be used.

So why does class Double exist at all, and why the change to the compiler?

1005ICT Object Oriented Programming – 2015-2 232

Class Double has always existed for two reasons:

• The class has lots of handy static constants and functions to dowith type double.

The constants are special values like the largest possible exponent,infinities and NaN (not a number).

The functions include Double.parseDouble(String), whichwe have already made good use of.

• The class can be used to create immutable objects that contain justone double value.

This is useful for storing double values in containers that can onlycontain objects, not simple types.

1005ICT Object Oriented Programming – 2015-2 233

10.2 Wrapper classes – boxing and unboxing

Along with class Double there are also classes Boolean, Byte,Character, Float, Integer, Long, and Short.

They all exist for the same reasons as Double.

Collectively they are all known as the wrapper classes, because they mayall be instantiated as immutable objects containing just one of their corre-sponding simple type.

The process of converting a simple type value to an object instantiated froma wrapper class is called boxing.

The reverse is called unboxing.

In early versions of Java, these had to be performed explicitly by using aconstructor or a function.

1005ICT Object Oriented Programming – 2015-2 234

But now, Java has autoboxing.

The language automatically converts the simple types to and from the wrap-per types as needed.

This is why you can declare variables as type Double instead of doublewithout error messages.

If you do however, your program will be less efficient.

1005ICT Object Oriented Programming – 2015-2 235

10.3 Abstract class Number

All of the wrapper classes for numbers are subclasses of abstract classjava.lang.Number, and so are a few more.

BigDecimal

Object

Number

Double

Byte

Float

Short LongInteger BigInteger

1005ICT Object Oriented Programming – 2015-2 236

The extras include java.math.BigInteger andjava.math.BigDecimal which are for arbitrary precision whole andfractional numbers respectively.

Class Number defines some conversion functions that must be defined foreach of its subclasses, thereby ensuring that all of these number types canbe converted into each other (even if losing information in the process).

This is an example of how inheritance is used to enforce a consistent inter-face among a group of classes.

1005ICT Object Oriented Programming – 2015-2 237

10.4 Optional parameters

Recent versions of Java have a new trick, the ability to write methods withvarying numbers of parameters.

The syntax of the formal parameter list has been extended:

formalParameterList

lastFormalParameter

,formalParameter

formalParameter

variableDeclaratorIdtype

variableModifier

1005ICT Object Oriented Programming – 2015-2 238

lastFormalParameter

variableDeclaratorId

...typevariableModifier

formalParameter

variableDeclaratorId

][

identifier

The important change is to the syntax for the last, and only the last, formalparameter.

It allows the addition of an ellipsis (...) to the type of the last argument.

The ellipsis implies that zero or more such parameters might be supplied.

1005ICT Object Oriented Programming – 2015-2 239

For example, this function returns the least of any number of ints.

public static int min(int a, int... bs) {int least = a;for (int i = 0; i < bs.length; i = i + 1) {

if (bs[i] < least) {least = bs[i];

} else {}

}return least;

}

For this example there must be at least one parameter, a, in order that aminimum is able to returned.

The last parameter bs... is treated inside the function as an array.

1005ICT Object Oriented Programming – 2015-2 240

These calls all succeed and print 1.

System.out.println(min(1));System.out.println(min(2, 1));System.out.println(min(2, 1, 3, 4));

1005ICT Object Oriented Programming – 2015-2 241

10.5 printf

C programmers have always enjoyed a very compact and flexible outputfunction, printf.

Java could never have such a method until optional parameters were intro-duced.

java.io.PrintStream.printf is defined as follows:

PrintStream printf(String format, Object... args)

The format string contains a mix of plain text and special patterns thatindicate how to format the optional args.

The optional arguments are all of type Object. In practice they will beinstances of subclasses of Object.

1005ICT Object Oriented Programming – 2015-2 242

Examples:

System.out.printf("Just the string.\n");System.out.printf("i = %d\n", 42);System.out.printf("mole = %.2e\n", 6.0221415e+23);System.out.printf("Reasons to be cheerful," +

" %d, %d, %d.\n", 1, 2, 3);

print:

Just the string.i = 42mole = 6.02e+23Reasons to be cheerful, 1, 2, 3.

1005ICT Object Oriented Programming – 2015-2 243

Why is printf a function that returns a reference to a PrintStreamobject?

It returns the very same reference that it was called with, so that calls maybe daisy chained like this, making just one statement:

System.out.printf("Just the string.\n").printf("i = %d\n", 42).printf("mole = %.2e\n", 6.0221415e+23).printf("Reasons to be cheerful," +

" %d, %d, %d.\n", 1, 2, 3);

making the code just a little less verbose.

Keep an eye out for other methods in the API that you might expect to beprocedures, but instead return a reference for this purpose. It is common.

1005ICT Object Oriented Programming – 2015-2 244

Lastly, the optional parameters are supposed to be Objects.

How was it possible to just provide int and double literals?

The answer is that the numbers were autoboxed to make Integers andDoubles, and these classes are subclasses of Object.

printf is a very sophisticated function. It exploits three advanced lan-guage features, optional parameters, autoboxing and inclusion polymor-phism.

We can also exploit these features.

See the API documentation for all the formatting options available in printf.

1005ICT Object Oriented Programming – 2015-2 245

10.6 String.format()

See also java.lang.String.format(String, Object...).

This uses a format string like printf, but is a function that returns aString instead of printing immediately.

1005ICT Object Oriented Programming – 2015-2 246

10.7 Section summary

This section covered:

• the inheritance relationship between Java’s number classes;

• the wrapper classes and autoboxing;

• optional parameters; and

• PrintStream.printf(String, Object...); and

• String.format(String, Object...).

1005ICT Object Oriented Programming – 2015-2 247

10.8 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 248

11 Errors and Exceptions

This section introduces the exceptions system in Java and shows how itreflects and enforces good practice.

1005ICT Object Oriented Programming – 2015-2 249

11.1 Kinds of errors

These kinds of errors are found in programs:

Syntax errors – any problems which are detected at compile time, includ-ing:

• true syntax errors involving the arrangement of symbols; and

• semantic errors (errors in the collective meaning of the sym-bols), for example:

– calling a method that does not exist;– type errors.

These errors are always eliminated before run time.

1005ICT Object Oriented Programming – 2015-2 250

Logical errors – errors made by the programmer that cause the programto not perform as required.

These errors can be removed with sufficient testing, or not made inthe first place with careful design.

1005ICT Object Oriented Programming – 2015-2 251

Run-time errors – problems that are detected at run time, including:

• run-time errors that are consequences of logical errors made bythe programmer, for example:

– "Hello".charAt(5)

– k = 0; i = j / k;

These should also be found and removed during testing.

• run-time errors that are consequences of circumstances beyondthe control of the programmer, for example:

– out of disk space;– can’t read a file; or– lost network connection.

Programs should be able to cope with these situations.

1005ICT Object Oriented Programming – 2015-2 252

11.2 Error handling in programs

It is good to write programs that can cope with all reasonably expected errorsituations, but it is not always good to clutter programs with unnecessaryprecautionary checks.

1005ICT Object Oriented Programming – 2015-2 253

11.2.1 Defensive programming

Here is a program with a problem.

public class Middle1 {

// middleChar(s) returns the character at the// middle of s.public static char middleChar(String s) {

return s.charAt(s.length() / 2);}

public static void main(String[] args) {System.out.println(middleChar(null));

}

}

1005ICT Object Oriented Programming – 2015-2 254

$ javac Middle1.java$ java Middle1Exception in thread "main"java.lang.NullPointerException

at Middle1.middleChar(Middle1.java:6)at Middle1.main(Middle1.java:10)

$

This is a run-time error caused because we tried to use a String methodusing a null String reference.

The JVM is very nice to us and tells us what line the error occured on, inwhich method and from which method was that called.

This report will be very useful in helping us fix the problem.

Which method is the one that is actually at fault?

1005ICT Object Oriented Programming – 2015-2 255

Same function, different problem.

public class Middle2 {

// middleChar(s) returns the character at the// middle of s.public static char middleChar(String s) {

return s.charAt(s.length() / 2);}

public static void main(String[] args) {System.out.println(middleChar(""));

}

}

1005ICT Object Oriented Programming – 2015-2 256

$ javac Middle2.java$ java Middle2Exception in thread "main"java.lang.StringIndexOutOfBoundsException:String index out of range: 0

at java.lang.String.charAt(String.java:444)at Middle2.middleChar(Middle2.java:5)at Middle2.main(Middle2.java:9)

$

A defensive programmer might get a bit nervous about the middleCharfunction, and try to make it safe by checking that the argument is valid...

1005ICT Object Oriented Programming – 2015-2 257

public class Middle3 {

// middleChar(s) returns the character at the// middle of s.public static char middleChar(String s) {

if (s != null && s.length() > 0) {return s.charAt(s.length() / 2);

} else {// What should I do here?

}}

public static void main(String[] args) {System.out.println(middleChar(""));

}

}1005ICT Object Oriented Programming – 2015-2 258

$ javac Middle3.javaMiddle3.java:11: missing return statement

1 error$

The compiler requires a function to return something, but in the else casethere is nothing sensible to return.

Even if there was, this testing is burdensome to add, slows the program, andmakes it harder to read.

We would be better off without it.

The method works perfectly for sensible inputs, so why not just demandthat the caller get it right!

1005ICT Object Oriented Programming – 2015-2 259

11.2.2 Programming by contract

A contract is a document that describes an agreement between two parties,obliging each to do something, to the benefit of both.

“If you build this shed for me, I’ll give you $500.”

If you don’t build the shed, I’m not obliged to pay.

We write a “contract” as preconditions and postconditions for a method.

precondition: If you give me a string with at least one character in it,postcondition: I’ll find the middle one for you.

If you don’t meet the preconditions of a method, then it’s not my fault thatit doesn’t work.

Pre- and postconditions are good places to be as precise as possible aboutwhat a method requires and does.

1005ICT Object Oriented Programming – 2015-2 260

public class Middle4 {

// middleChar(s) returns the character at the// middle of s.// precondition: s.length() > 0// postcondition: Returns the character at the// least position closest to the middle of s.public static char middleChar(String s) {

return s.charAt(s.length() / 2);}

public static void main(String[] args) {System.out.println(middleChar(""));

}

}

1005ICT Object Oriented Programming – 2015-2 261

That this program dies horribly with an error is a good thing.

It motivates us to fix the errors in calls to middleChar.

When all such errors are fixed, there is no point in having defensive errorchecking code.

This example has been a case where a logical error causes a run-time error.

We handle logical errors then by fixing them.

1005ICT Object Oriented Programming – 2015-2 262

11.2.3 Unavoidable, unexpected errors

There are still those run-time errors caused by unexpected events fromwhich a program could recover, such as missing files.

Should we be defensive?

Yes, but we should not let the code that handles rare problems clutter other-wise clear code.

Java lets us separate the code that does the job, from the code that handlesthe rare problems using the try and catch statements.

1005ICT Object Oriented Programming – 2015-2 263

11.3 Java’s Errors and Exceptions

11.3.1 Classes

Information about errors that occur is storedin objects. The superclass of all errors isjava.lang.Throwable.

Throwable

Error Exception

It has subclasses:

• java.lang.Error and its many subclasses are for totally unre-coverable errors that the programmer can’t be expected to deal with;and

• java.lang.Exception is for errors that can be avoided or re-covered from.

1005ICT Object Oriented Programming – 2015-2 264

java.lang.Exceptionhas many subclasses, onefor each kind of unexpectedsituation.

RuntimeException

Exception

IOException

NullPointerException

StringIndexOutOfBoundsException

...

...

An important subclass is java.lang.RuntimeException.

Its subclasses are the kinds of run-time errors that ensue from logical errorsin programs that should be corrected.

1005ICT Object Oriented Programming – 2015-2 265

All of the other subclasses of Exception are errors and situations fromwhich programs should be able to recover.

In fact the Java compiler insists that the potential for these situations mustbe addressed by the programmer.

To explore the ways in which the programmer can do this, we will nowrevisit an earlier example program we are now in a position to understandfully.

1005ICT Object Oriented Programming – 2015-2 266

11.3.2 OpenURI

Recall this program. This version has been stripped back to the basic code.

/*** file: OpenURI1.java

** author: Andrew Rock

** use: java OpenURI1 <URI>

** opens the <URI> in your default web

** browser.

*/

import java.net.*; // for class URIimport java.awt.*; // for class Desktop

1005ICT Object Oriented Programming – 2015-2 267

public class OpenURI1 {

public static void main(String [] args) {Desktop.getDesktop()

.browse(new URI(args[0]));}

}

Package java.awt is Java’s Abstract Window Toolkit, the first version ofthe graphical user interface library.

java.awt.Desktop contains methods for performing some actions onthe host PC’s desktop, such as opening files, applications and URIs.

There need only be one desktop object, so this class does not provide aconstructor.

1005ICT Object Oriented Programming – 2015-2 268

We can use this reference to call the useful Desktop methods, all of whichare dynamic.

A constructor would create more objects.

Instead it provides the static function getDesktop() that returns a refer-ence to the single instance of Desktop that already exists.

The one we’re using is browse(URI) to open a URI in the user’s defaultbrowser.

1005ICT Object Oriented Programming – 2015-2 269

Now to compile the program:

$ javac OpenURI1.javaOpenURI1.java:16: unreported exceptionjava.net.URISyntaxException;must be caught or declared to be thrown

.browse(new URI(args[0]));ˆ

OpenURI1.java:16: unreported exceptionjava.io.IOException;must be caught or declared to be thrown

.browse(new URI(args[0]));ˆ

2 errors$

1005ICT Object Oriented Programming – 2015-2 270

The compiler has warned us about two possible problems that may emergeat run time:

• java.net.URISyntaxException would be thrown if the URIwas syntactically incorrect; and

• java.io.IOException would be thrown if the URI could notactually be opened in a browser for some reason.

The compiler will not accept code that does not address these possibilities.

The error messages themselves tell us what to do.

1005ICT Object Oriented Programming – 2015-2 271

11.3.3 throws – passing the buck

If we don’t want to deal with possible errors, we can make them someoneelse’s problem.

These risky method calls may throw an exception, that is, they may fail andcreate an instance of an exception class.

We make our method fail and pass on the same exception by declaring itthrown.

This has to be done right up the chain of methods to main, unless somemethod catches it and deals with it.

1005ICT Object Oriented Programming – 2015-2 272

A throws clause lists the exception types that might be thrown by methodscalled by this method or this method itself.

throws

exceptionType,

exceptionTypethrows

Adding this satisfies the compiler, at the risk that the exception is passedright up to the JVM, which will report the error with a message.

1005ICT Object Oriented Programming – 2015-2 273

import java.net.*; // for class URIimport java.awt.*; // for class Desktopimport java.io.*; // for class IOException

public class OpenURI2 {

public static void main(String [] args)throws URISyntaxException, IOException {

Desktop.getDesktop().browse(new URI(args[0]));

}

}

1005ICT Object Oriented Programming – 2015-2 274

$ javac OpenURI2.java$ java OpenURI2 :Exception in thread "main"java.net.URISyntaxException:Expected scheme name at index 0: :

at java.net.URI$Parser.fail(URI.java:2810)at java.net.URI$

Parser.failExpecting(URI.java:2816)at java.net.URI$Parser.parse(URI.java:3008)at java.net.URI.<init>(URI.java:577)at OpenURI2.main(OpenURI2.java:17)

$

1005ICT Object Oriented Programming – 2015-2 275

$ java OpenURI2 hException in thread "main" java.io.IOException:Failed to mail or browse h. Error code: -10814

at apple.awt.CDesktopPeer.lsOpen(CDesktopPeer.java:52)

at apple.awt.CDesktopPeer.browse(CDesktopPeer.java:45)

at java.awt.Desktop.browse(Desktop.java:368)

at OpenURI2.main(OpenURI2.java:17)$

1005ICT Object Oriented Programming – 2015-2 276

Because of inclusion polymorphism, any superclass of the specific excep-tions will do.

import java.net.*; // for class URIimport java.awt.*; // for class Desktop

public class OpenURI3 {

public static void main(String [] args)throws Exception {

Desktop.getDesktop().browse(new URI(args[0]));

}

}

1005ICT Object Oriented Programming – 2015-2 277

11.3.4 try-catch – the buck stops here

It is not always possible to just throw exceptions.

A robust, quality program should recover from such errors.

And in some circumstances Java will not let you add a throws clause.

The try statement brackets code that may fail and throw exceptions.

If that happens, control is then transferred to the first catch statement thatdeclares an exception with a matching type, where it can be handled.

tryStatement

catchClauseblocktry

catchClause

block)identifierexceptionType(catch

1005ICT Object Oriented Programming – 2015-2 278

/*** file: OpenURI4.java

** author: Andrew Rock

** use: java OpenURI4 <URI>

** opens the <URI> in your default web

** browser.

*/

import java.net.*; // for class URIimport java.awt.*; // for class Desktopimport java.io.*; // for class IOException

public class OpenURI4 {

1005ICT Object Oriented Programming – 2015-2 279

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

Desktop.getDesktop().browse(new URI(args[0]));

} catch (URISyntaxException e) {System.err.println("OpenURI4 error: " +

"Could not parse \"" + args[0] + "\".");} catch (IOException e) {

System.err.println("OpenURI4 error: " +"Could not open \"" + args[0] + "\".");

}}

}

System.err is an alternate output stream just for error messages.

1005ICT Object Oriented Programming – 2015-2 280

$ javac OpenURI4.java$ java OpenURI4 :OpenURI4 error: Could not parse ":".$ java OpenURI4 hOpenURI4 error: Could not open "h".$

So now we know how to use any API method that throws exceptions.

Because of inclusion polymorphism, fewer catch clauses could be usedusing superclasses.

1005ICT Object Oriented Programming – 2015-2 281

11.3.5 throw

How do exceptions originate?

How do they get created?

Create an exception object, like any other.

They all have a constructor with a String argument, for a detailed de-scription of the problem.

A throw statement is used to throw the exception, and stop normal execu-tion.

For example:

1005ICT Object Oriented Programming – 2015-2 282

public class Thrower {

public static void main(String[] args)throws Exception {

throw new Exception("Test exception.");}

}

$ javac Thrower.java$ java ThrowerException in thread "main" java.lang.Exception:Test exception.

at Thrower.main(Thrower.java:5)$

1005ICT Object Oriented Programming – 2015-2 283

11.4 Section summary

This section covered:

• the categories of errors, syntax, logical, run-time;

• defensive programming;

• programming by contract;

• the Java exceptions class hierarchy;

• the try-catch statement for handling exceptions;

• the throws clause for not handling exceptions; and

• how to throw exceptions.

1005ICT Object Oriented Programming – 2015-2 284

11.5 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 285

12 Java Language Goodies

This section introduces a grab-bag of Java language features and elements.

Some of them are real enablers.

Some of them are ok to use judiciously, but can make code less clear ifoverused.

1005ICT Object Oriented Programming – 2015-2 286

12.1 Operator goodies

Java derives much of its design from that of C.

C had a very rich set of operators, and most of them have been included inJava, C++, C#, Perl, JavaScript, ActionScript, etc.

1005ICT Object Oriented Programming – 2015-2 287

12.1.1 Operator summary

In this table all of Java’s operators are listed with their operands in theplaces they are put.

The horizontal lines divide the operators into groups. Within each group allthe operators have the same precedence. The groups are listed from highestto lowest precedence.

object/class.member object/class member access /dereferencing

array[index] array element access

method(args) method invocation

variable++ post-increment

variable-- post-decrement++variable pre-increment

1005ICT Object Oriented Programming – 2015-2 288

--variable pre-decrement

+variable unary plus

-variable unary minus

˜integer bitwise complement

!boolean notnew class/array instantiation

(type) any type castnumber * number multiplication

number / number division

number % number modulonumber + number addition

number - number subtraction

string + any string catenation

1005ICT Object Oriented Programming – 2015-2 289

any + string string catenationinteger << integer left shift

integer >> integer right shift with sign extension

integer >>> integer right shift with zero extensionnumber < number less than

number <= number less than or equal

number > number greater than

number >= number greater than or equal

reference instanceof type type comparisonsimple == simple equal (same values)

simple != simple not equal (different values)

reference == reference equal (same object)

reference != reference not equal (different objects)

1005ICT Object Oriented Programming – 2015-2 290

integer & integer bitwise and

boolean & boolean boolean andinteger ˆ integer bitwise xor

boolean ˆ boolean boolean xor

integer | integer bitwise or

boolean | boolean boolean orboolean && boolean short circuit/conditional andboolean || boolean short circuit/conditional orboolean ? any : any conditional (ternary) operatorvariable = any assignment (gets)

variable *= any variable =variable * any

variable /= any variable =variable / any

1005ICT Object Oriented Programming – 2015-2 291

variable %= any variable =variable % any

variable += any variable =variable + any

variable -= any variable =variable - any

variable <<= any variable =variable << any

variable >>= any variable =variable >> any

variable >>>= any variable =variable >>> any

variable &= any variable =variable & any

1005ICT Object Oriented Programming – 2015-2 292

variable ˆ= any variable =variable ˆ any

variable |= any variable =variable | any

1005ICT Object Oriented Programming – 2015-2 293

12.1.2 Shorthand operators

Some of the operators are shorthands for common assignment statements.

For example, we can save a little typing from a new version of our averageprogram:

Scanner sc = new Scanner(System.in);double total = 0.0;int n = 0;while (sc.hasNextDouble()) {

total += sc.nextDouble();n++;

}System.out.println("Average = " + total / n);

Embedding ++ and -- in long expressions can be very hard to read later.

1005ICT Object Oriented Programming – 2015-2 294

12.1.3 instanceof

The instanceof operator helps us cope with inclusion polymorphism.

We can test whether a reference is currently pointing to an instance of aclass or one of its subclasses.

This program tests this out:

public class InstanceOf {

public static void test(Object o) {System.out.println(o instanceof Double);System.out.println(o instanceof Number);System.out.println(o instanceof Object);System.out.println(o instanceof Integer);

}

1005ICT Object Oriented Programming – 2015-2 295

public static void main(String[] args) {test (new Double(3.0));

}

}

$ javac InstanceOf.java$ java InstanceOftruetruetruefalse$

1005ICT Object Oriented Programming – 2015-2 296

12.2 this goodness right here

The this keyword is a way to refer to the current object.

It only makes sense to use it in dynamic (instance) methods and construc-tors.

12.2.1 For constructors and mutators

Using this enables the use of the same names for fields and arguments:

1005ICT Object Oriented Programming – 2015-2 297

public class Point1 {

private double x, y;

public Point1(double x, double y) {this.x = x;this.y = y;

}

public void setX(double x) {this.x = x;

}

}

1005ICT Object Oriented Programming – 2015-2 298

12.2.2 One constructor calling another

If a class has multiple constructors, then to avoid duplication of statements,one can call the other.

Normally calling a constructor requires the new keyword, but every timenew is used a whole new object gets instantiated.

This example shows how a constructor can call another, providing defaultvalues.

1005ICT Object Oriented Programming – 2015-2 299

public class Point2 {

private double x, y;

// Make any point.public Point2(double x, double y) {

this.x = x;this.y = y;

}

// Make the origin point (0,0).public Point2() {

this(0.0, 0.0); // calls the other constructor}

}

1005ICT Object Oriented Programming – 2015-2 300

12.3 Array goodies

12.3.1 java.util.Arrays

java.util.Arrays is a library of handy staticmethods for workingwith arrays.

See especially the sorting and searching methods.

12.3.2 The for-in statement

When you want to do something with all the elements of an array, the usualthing to use is a for loop like this:

1005ICT Object Oriented Programming – 2015-2 301

public static double sum1(double[] a) {double s = 0.0;for (int i = 0; i < a.length; i = i + 1) {

s = s + a[i];}return s;

}

or with the shorthand operators:

public static double sum2(double[] a) {double s = 0.0;for (int i = 0; i < a.length; i++) {

s += a[i];}return s;

}

1005ICT Object Oriented Programming – 2015-2 302

But there is an even better form of the for loop that does away with theneed for a loop index variable at all.

What we want to use is the elements, not the indices.

The for-in loop binds the declared variable to each of the elements in turn.

public static double sum3(double[] a) {double s = 0.0;for (double x : a) {

s += x;}return s;

}

1005ICT Object Oriented Programming – 2015-2 303

Read the colon as “in”. The word itself does not appear.

This also sometimes called the for-each loop, and its equivalent in otherlanguages often has an each keyword in its syntax.

This loop is of no use when only part of the array needs to be processed.

We can use this with arrays of any type, including objects, and not justsimple types.

1005ICT Object Oriented Programming – 2015-2 304

12.4 Section summary

This section covered:

• all of Java’s operators;

• how to use the generally useful new ones, shorthands and instanceof;

• the this keyword;

• java.util.Arrays for sorts and searches; and

• the for-in statement for arrays.

1005ICT Object Oriented Programming – 2015-2 305

12.5 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 306

13 UML Class Diagrams

This section focusses on the Unified Modelling Language class diagramsand their use in object oriented design.

1005ICT Object Oriented Programming – 2015-2 307

13.1 It’s about communication

UML is a collection of design notations.

UML is for people to use to communicate with each other.

13.1.1 Efficiency

To facilitate efficient communication:

• there are agreed conventions, like how boxes are drawn to mean cer-tain things;

• the diagrams show what they need to show and omit what they don’tneed to show; and

• they are extensible and adaptable to the needs of particular groups ofusers.

1005ICT Object Oriented Programming – 2015-2 308

13.1.2 Programming language independence

UML is used by software designers who will ultimately see their designsimplemented in different object oriented languages.

So UML does not follow the syntax of any one of those languages in par-ticular.

All of the mainstream object oriented languages have similar features.

It is, however, common to use the notation for a particular language if thatis the language that is going to be used.

For example, sometimes we will use Java notation inside class boxes.

1005ICT Object Oriented Programming – 2015-2 309

13.1.3 Illustration not definition

Diagrams by themselves are not an effective way to communicate.

Humans use natural language, but when that is not clear enough, we usepictures, diagrams or special notations (like mathematics) to supplementthe text.

A UML class diagram, by itself, does not constitute a design.

A written description of the class’s purpose, and those of its members shouldaccompany the diagram.

1005ICT Object Oriented Programming – 2015-2 310

13.2 Class diagram elements

13.2.1 Notes

A note is a dog-eared box that containsanything that helps explain something.

An optional dotted line connects it to thething it describes.

This is a note about MyClass.

MyClass

1005ICT Object Oriented Programming – 2015-2 311

13.2.2 Classes

Obviously, the most common feature of class dia-grams is the representation of classes.

A class is most commonly drawn as a box with threesections, stacked vertically.

area() : doubledraw() : void...

Circlecentre : Pointradius : double

The top section always contains the name of the class.

The other sections are for the members (attributes and methods) of the class.

The middle section is for the attributes (also known as fields or propertiesor variables).

The bottom section is for the methods (also known as operations, functions,procedures, constructors, destructors...)

An ellipsis (...) declares that there are more members than shown in thisdiagram, but without one there could still be more.1005ICT Object Oriented Programming – 2015-2 312

The lower sections are optional.

They may be omitted because a class has no attributes, has no methods, orjust because they are irrelevant to the discussion at hand.

Pointx : doubley : double

CompactCamerapoint() : voidshoot() : void MyClass

In the cases where just one of the lower boxes is shown, there should be noconfusion between whether the members are attributes or methods, as themethods will always have formal parameter lists, or at least empty paren-theses, after their names.

1005ICT Object Oriented Programming – 2015-2 313

13.2.3 Attribute basics

The basic notation for an attribute is to write the name, then a colon, thenthe type.

This lets us see the name of the attribute first, and then the type.

Java UML

double x x : double

int[] a a : int[]

String name name : String

1005ICT Object Oriented Programming – 2015-2 314

13.2.4 Method basics

Similarly the UML notation for methods moves the result type to the end,after a colon.

Arguments are written like attributes, name first.

Constructors have no result type.

Java UML

Point(int x, int y) Point(x : int, y : int)

void move(int distance) move(distance : int) : void

String getName() getName() : String

1005ICT Object Oriented Programming – 2015-2 315

13.2.5 Visibility of members

The members of a class may have the following visibilities:

visibility UML symbol descriptionpublic + visible from any classprotected # visible only from subclassesprivate - not visible from any other class

The symbols are more compact than the keywords.

Attributes are more often privateor protected than public.

Methods are more often publicthan private.

-x : double-y : double

Point

+Point(x : double, y : double)+transform(t : Transformation) : void

1005ICT Object Oriented Programming – 2015-2 316

A class can make its members visible only to its subclasses by giving themthe protected visibility.

Translation+Translation(delta_x : double, delta_y : double)

+sequence(t : Transformation) : Transformation#matrix : double[3][3]

Transformationsuperclass

subclass

1005ICT Object Oriented Programming – 2015-2 317

13.2.6 Attributes

With an attribute, the reader of a class diagram will want to know:

• its name;

• its type, which may be simple (like int) or another class;

• its visibility;

• its multiplicity; and

• perhaps other relevant properties.

1005ICT Object Oriented Programming – 2015-2 318

Inline attributes

Whether an attribute is inline or not is not a propertyof the attribute, just how the class diagram is drawn.

In this example, the centre attribute is listed (inline)in the middle box.

area() : doubledraw() : void...

Circlecentre : Pointradius : double

1005ICT Object Oriented Programming – 2015-2 319

Associated attributes

An associated attribute is just another way of drawing the diagram to showtwo classes working together.

+area() : double+draw() : void

Circle-radius : double Point

-x : double-y : double

-centre

In this example, a Circle still has a private attribute of type Point, namedcentre.

Using associated attributes makes a diagram bigger and more complex, butdoes allow the reader to see inside more than one class at a time, if that iswhat is needed for the discussion at hand.

1005ICT Object Oriented Programming – 2015-2 320

Keeping in mind that when a class has an attribute that’s type is a class, andthat that means there are two separate objects at run-time, then both classesmay contain references to the other.

Drawing them associated makes this clear.

-scrollBar ScrollBarWindow -container

1005ICT Object Oriented Programming – 2015-2 321

Multiplicity

We use multiplicity annotations to indicate that an attribute contains multi-ple values.

For example a polygon is defined by its many vertices, which are points,and each vertex belongs to only one polygon.

-vertex*1Polygon Point

Equivalently, inline:

-vertex : Point[*]Polygon

1005ICT Object Oriented Programming – 2015-2 322

The square brackets in the inline version imply that the vertices are storedin an array.

That may be, but equally they could be in a list or a set.

That decision can be left to the implementation in the final programminglanguage.

Some more example multiplicities:

annotation meaning1 exactly 15 exactly 5* many (0 or more)1.. 1 or more (some)1..5 1 to 5

1005ICT Object Oriented Programming – 2015-2 323

Properties

Attributes may have additional properties, enumerated in braces.

Common properties are:

property meaningreadOnly This can not be changed once it gets its default value,

a constant.ordered The multiple values must be stored as a sequence (per-

haps sorted).unique There may not be any duplicates among the multiple

values.

A better polygon:

-vertex : Point[3..] {ordered}Polygon

1005ICT Object Oriented Programming – 2015-2 324

In this example a RobotSensorPort associates a sensor port number witha Sensor.

A static constant defines how many ports there are (its default value isshown after =), and an extra property applied to portNumber declares arange of permissible values.

+PORTS : int = 4 {readOnly}-portNumber : int {1 ≤ portNumber ≤ PORTS}-sensor : Sensor

RobotSensorPort

1005ICT Object Oriented Programming – 2015-2 325

13.2.7 Methods

A method is declared by specifying, in the bottom section of a class’s box:

• its name;

• its formal parameter list

– with parentheses, enclosing

– a comma separated list of name-colon-types, or

– an ellipsis to show the parameters have been omitted;

• its return type (or void) following a colon.

Constructors have the same name as the class and the return type is omitted.

See any of the examples above or below that show methods.

1005ICT Object Oriented Programming – 2015-2 326

13.2.8 Static members

Static members are underlined.

+PORTS : int = 4 {readOnly}-portNumber : int {1 ≤ portNumber ≤ PORTS}-sensor : Sensor

RobotSensorPort

1005ICT Object Oriented Programming – 2015-2 327

13.3 Class relationships

13.3.1 Dependency

The weakest connection, dependency, between two classes is indicated bya dashed arrow.

In this example, perhaps a method in class Geometry calls a method inmethod in class Math, and so, depends upon it.

MathGeometry

1005ICT Object Oriented Programming – 2015-2 328

13.3.2 Association

Association has been described above under attributes.

In summary, association indicates that at least one class contains a referenceto instances of another.

Association is indicated by a solid line.

+area() : double+draw() : void

Circle-radius : double Point

-x : double-y : double

-centre

1005ICT Object Oriented Programming – 2015-2 329

13.3.3 Inheritance

Inheritance (or its opposite, generalisation) are indicated by an arrow witha triangle head.

In Java, a class may inherit from only one class.

Translation+Translation(delta_x : double, delta_y : double)

+sequence(t : Transformation) : Transformation#matrix : double[3][3]

Transformationsuperclass

subclass

1005ICT Object Oriented Programming – 2015-2 330

13.3.4 Abstract classes

Abstract classes have methods that are declared butnot implemented.

They are drawn like regular classes, except with ital-icized names, and the unimplemented methods ital-icized.

Shape+area() : double+draw() : void

Circle

Abstract classes are permitted to declare methods without actually imple-menting bodies for them.

It is required of subclasses that they actually do implement them.

1005ICT Object Oriented Programming – 2015-2 331

13.4 Tools

The diagrams in this section were produced with OmniGraffle.

They can be created with any vector graphics drawing program.

There are also dedicated tools for creating them, some expensive, some free,used by software engineers.

Never forget that design is a fluid process.

Don’t rush to a software drawing package.

The first few versions should be done on a whiteboard or with pencil andpaper.

1005ICT Object Oriented Programming – 2015-2 332

13.5 Section summary

This section covered:

• the UML notations for all the object oriented programming featureswe have learned so far.

1005ICT Object Oriented Programming – 2015-2 333

13.6 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 334

14 2D Graphics In a Window

This section shows how to open a window and draw into it.

It serves as an introduction to Swing, Java’s Graphical User Interface toolkit.

It is not the goal of this course to teach all of something as complicated asSwing, but rather to show it as another example of object oriented program-ming.

Many of its principles will carry over to other GUI frameworks.

1005ICT Object Oriented Programming – 2015-2 335

14.1 History: AWT and Swing

Java has a reputation for being difficult to program GUIs in.

It’s true!

Part of the problem is Java’s ambition to be completely platform indepen-dent.

The same bytecode is supposed to be able to run on different systems (Mac,Windows, Linux...) with the windows etc looking normal for each system.

The native GUI frameworks for each system do not have to be as compli-cated.

Components (buttons, fields...) can be laid out and tweaked by hand.

As we write a Java program, we don’t know exactly how big the componentsare going to be. Layout is performed programmatically.

1005ICT Object Oriented Programming – 2015-2 336

The other issue is that Java’s first GUI framework, Abstract Window Toolkit(AWT) was put together very quickly to exploit the new web opportunity,applets.

Within a short time, AWT was superseded by Swing, but:

• AWT is still in the API to support legacy code; and

• Swing is implemented on top of and depends on (literally extends)AWT.

So programmers have to use a mix of classes from java.awt andjavax.swing packages.

General GUI API advice: Start looking for what you want in javax.swing.If you need something from java.awt you will be led there.

1005ICT Object Oriented Programming – 2015-2 337

14.2 Top level containers

Swing GUI components all have to reside within one of the three top levelcontainers:

applets – javax.swing.JApplet a panel that is contained within someother applications window.

dialogs – javax.swing.JDialog a free window that looks like a pop-up dialog box.

frames – javax.swing.JFrame a free window that looks like an ap-plication’s main window.

The Swing versions of classes in the AWT start with J.

1005ICT Object Oriented Programming – 2015-2 338

The Swing classes extend the AWT classes as follows.

java.awt.Component

java.awt.Container

java.awt.Panel java.awt.Window

java.awt.Applet

javax.swing.JApplet

java.awt.Dialog java.awt.Frame

javax.swing.JDialog javax.swing.JFrame

1005ICT Object Oriented Programming – 2015-2 339

We will not be building applets, and probably not dialogs, in this course,but the principles that we will learn for adding components to frames applyequally to applets and dialogs.

All of these are top level containers.

We don’t draw into them directly, we place components into them, either:

• standard components, such as buttons, fields, controls;

• custom components that we build ourselves; or

• containers for other components, to help lay them out.

1005ICT Object Oriented Programming – 2015-2 340

14.3 Components

The root of the previous hierarchy is java.awt.Component.

A component is generally anything that appears on screen, either:

• because it has its own visual elements;

• because it contains other components; or

• both.

A component can also interact with the user, via events.

We will address events after we have learned about interfaces and innerclasses.

1005ICT Object Oriented Programming – 2015-2 341

The most important methods of any component are:

void paint(Graphics) – which draws this component, using thesupplied Graphics object, which provides the basic drawing meth-ods.

The system knows when the component needs to be redrawn, pro-grammers don’t call this directly.

void repaint() – call this when you know the component needs re-drawing.

The system then calls paint(Graphics) for you.

An actual java.awt.Component is blank.

All useful components are subclasses of this.

1005ICT Object Oriented Programming – 2015-2 342

14.4 Containers

java.awt.Container is the subclass of java.awt.Component thatis intended to contain other components (children).

The most important methods of any container are:

void add(Component) – which adds the Component as a new childcomponent.

void paint(Graphics) – inherited from Component.

For a container, its main job is to ensure all the childen get painted.

As always, don’t call it directly.

void repaint() – as per Component.

1005ICT Object Oriented Programming – 2015-2 343

14.5 JFrame

A javax.swing.JFrame contains just one or two components directly:

• an optional menu bar; and

• its content pane, which contains all of the components in the mainarea of the window.

JMenuBar

JFrame

Container

Association, not inheritance!

...

Content pane components

Content pane

1005ICT Object Oriented Programming – 2015-2 344

A JFrame is a fully functional window.

It can be used as is, and does not need to be subclassed to use it.

Important constructors:

JFrame() – creates a new frame, initially invisible.

JFrame(String title) – creates a new frame, with this title.

Important methods:

void add(Component) – being a container, a JFrame has anadd(Component) method, but it always adds them as children ofthe content pane.

void paint(Graphics) – it has one, but don’t use it directly.

1005ICT Object Oriented Programming – 2015-2 345

void repaint() – it has one, but don’t use it. Request the repaintingof individual child components instead.

void setSize(int width, int height) – sets the size (width× height) of the frame.

void setTitle(String title) – changes the window title.

void setDefaultCloseOperation(int) – sets the action to per-form if the close control of the window is clicked.

By default it is simply to hide the window and keep the program go-ing.

Use setDefaultCloseOperation(JFrame.EXIT ON CLOSE)to exit the program.

void setVisible(boolean) – makes the frame visible or not.

1005ICT Object Oriented Programming – 2015-2 346

Making a program put up a window starts the event handling thread.

A program does not terminate itself until all of its threads have ended them-selves.

The event handling thread does not terminate itself, so once a frame is cre-ated it is necessary to either call System.exit(int) or use the frame’sEXIT ON CLOSE option.

An example empty frame program:

/*** file: JustAFrame.java

** purpose: Puts up an empty frame and exits when

** that is closed.

*/

1005ICT Object Oriented Programming – 2015-2 347

import javax.swing.*;

public class JustAFrame {

public static void main(String[] args) {JFrame f = new JFrame("Just a Frame");f.setSize(200, 100);f.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);f.setVisible(true);

}

}

After main finishes, and it does so quickly, the program keeps running untilthe window is closed.

1005ICT Object Oriented Programming – 2015-2 348

14.6 JComponent

JComponent is the su-perclass of all the Swingreplacements for AWTcomponents.

We can subclass it our-selves to create customcomponents, for exampleto do some 2D graphics.

Component

Container

JComponent

JButton

AbstractButton JLabel

...

1005ICT Object Oriented Programming – 2015-2 349

An important difference between a Component and a JComponent isthat when you subclass it, you should implement avoid paintComponent(Graphics) method rather than apaint(Graphics) method.

1005ICT Object Oriented Programming – 2015-2 350

14.7 Graphics and Graphics2D

The intent of a Graphics object is that it maintains a lot of different set-tings such as drawing colours and text fonts, and also the drawing methods.

A Graphics object is passed to every paint and paintComponentmethod.

The Graphics objects is also the link to the underlying graphics enginefor the current system.

Graphics is abstract.

A component in a window can assume that theGraphics object is also an instance of Graphics2D(also abstract) which has many more drawing options.

The actual object will be an instance of some devicedependent subclass of Graphics2D.

Graphics

Graphics2D

?

1005ICT Object Oriented Programming – 2015-2 351

To get the additional features of a Graphics2D, it is usual to cast theGraphics parameter of a paintComponentmethod to a Graphics2D.

Also some of the setting that can be changed in the graphics object shouldnot be changed permanently, so it is also advisable to make a copy of thegraphics object.

The create() method is provided for this.

A statement like this is typical:

Graphics2D g2 = (Graphics2D) g.create();

and then only g2 is used to draw with.

Example:

1005ICT Object Oriented Programming – 2015-2 352

/*** file: ABox.java

** purpose: A component that paints a red box.

*/

import java.awt.*;import javax.swing.*;

public class ABoxextends JComponent {

1005ICT Object Oriented Programming – 2015-2 353

public void paintComponent(Graphics g) {Graphics2D g2 = (Graphics2D) g.create();g2.setColor(Color.RED);g2.fillRect(30, 30, 100, 100);

}

}

/*** file: JustABox.java

** purpose: Puts up a frame containing

** an ABox component.

*/

import javax.swing.*;

1005ICT Object Oriented Programming – 2015-2 354

public class JustABox {

public static void main(String[] args) {JFrame f = new JFrame("Just a Box");f.setSize(200, 200);f.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);f.add(new ABox());f.setVisible(true);

}

}

The APIs for Graphics and Graphics2D are quite straightforward, andyou should be able to read them unassisted now.

Have fun!

1005ICT Object Oriented Programming – 2015-2 355

14.8 Section summary

This section covered:

• the history of the AWT and Swing GUI frameworks;

• the Swing top level containers, frames, dialogs and applets;

• components and containers;

• JFrames and JComponents;

• Graphics and Graphics2D objects; and

• how to put it all together to draw something in a window.

1005ICT Object Oriented Programming – 2015-2 356

14.9 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 357

14.10 Self-practice exercises

1. Laboratory 9 from 1001ICT is always a selection of graphics exer-cises. You should now be able to do all of those exercises in Java, notMaSH.

1005ICT Object Oriented Programming – 2015-2 358

15 Advanced Data Structures

One of the major fields of Computer Science, since it has been a subject,has been the study of data structures and associated algorithms for evermore efficient ways to store, sift, sort, and retrieve information.

This section introduces useful abstract data types for storing collections ofobjects.

1005ICT Object Oriented Programming – 2015-2 359

15.1 Abstract data types

We sometimes use, and in this course have previously used, the term ab-stract data type as an antecedent to the class, as a module that defines atype and provides methods for operating upon it.

There is an older and more fundamental definition: a data structure that isdefined by the operations that can be performed with it.

This even more abstract idea does not depend at all upon its implementationin a programming language.

We can even see instances of many of them in real life situations, apart fromcomputing.

1005ICT Object Oriented Programming – 2015-2 360

15.2 The built-ins

We are by now well familiar with arrays and classes.

These are the basic compound data structures built into any object orientedlanguage.

Arrays are a container for many of the same type of elements.

Classes (when viewed simply as data types), or records, or structures, createassociations between a few fields, typically of different types.

1005ICT Object Oriented Programming – 2015-2 361

15.2.1 Arrays

Arrays themselves are an abstract data type.

An array is a collection of elements all of the same type, with a fixed length.

Each element is assigned a unique, sequential position number.

0 1 2 3 4 5 6 7 8 9

fixed length, set at creation

fixed position numbers

1005ICT Object Oriented Programming – 2015-2 362

Arrays are great when:

• you know how big to make the array in the first place; and

• you can find the element you want quickly by just its position; or

• you don’t intend to seek out individual elements, just use them all,one after the other in the order they already have.

1005ICT Object Oriented Programming – 2015-2 363

15.3 The built

With arrays and classes we can implement data structures defined not bythe language, but by the operations for storage and retrieval we define asmethods for them.

1005ICT Object Oriented Programming – 2015-2 364

15.3.1 Sets

Sets (that you know from mathe-matics) are an abstract data type.

Sets store a collection of things, likearrays, but not in any particular or-der.

Sets should contain no duplicates.

1005ICT Object Oriented Programming – 2015-2 365

The idea of a set is really defined by these basic operations:

• making an empty set;

• finding out how many things are in the set;

• adding something to a set;

• removing something from a set; and

• finding out if something is in a set.

1005ICT Object Oriented Programming – 2015-2 366

15.3.2 Bags

Bags or multisets are like sets, butallow duplicates. × 1

× 2

× 4

× 7

× 2

× 1

× 1

1005ICT Object Oriented Programming – 2015-2 367

The idea of a bag is defined by these basic operations:

• making an empty bag;

• finding out how many things are in the bag;

• adding something to a bag;

• removing something from a bag; and

• finding out how many times something occurs in the bag.

1005ICT Object Oriented Programming – 2015-2 368

15.3.3 Lists or sequences

A list or sequence is a collection of elements of the same type, like an array,but can grow or shrink as elements are inserted or removed.

The position number of a particular element in a list changes as elementsare inserted or removed.

A list can, but doesn’t have to be, maintained in a particular ordering.

Lists can contain duplicates.

1005ICT Object Oriented Programming – 2015-2 369

An element can be inserted at any location in a sequence.

All the elements to the right increase their position numbers by one.1005ICT Object Oriented Programming – 2015-2 370

An element can be removed from any location in a sequence.

1005ICT Object Oriented Programming – 2015-2 371

The idea of a list is defined by these basic operations:

• making an empty list;

• inserting something into the list;

• removing something from the list;

• finding out how many things are in the list; and

• finding something in the list.

1005ICT Object Oriented Programming – 2015-2 372

15.3.4 Stacks

Stacks are sequences that we intend to use in only certain constrained ways:

• making an empty stack;

• finding out how many things are in the stack;

• pushing – adding something to one end only (the top end);

• peeking at the most recently added thing; and

• popping – removing the most recently added thing.

The constraint is that the only element we ever want to examine or removeis the one most recently added to the stack.

Stacks are also known as LIFOs (last-in-first-out).

1005ICT Object Oriented Programming – 2015-2 373

push peek pop

1005ICT Object Oriented Programming – 2015-2 374

15.3.5 Queues

Queues are sequences that we intend to use in only these ways:

• making an empty queue;

• finding out how many things are in the queue;

• enqueue – add something to the back of the queue;

• peeking at the thing at the front of the queue; and

• dequeue – remove the least recently added thing from the front.

The constraint is that the only element we ever want to examine or removeis the one least recently added to the queue.

Queues are also known as FIFOs (first-in-first-out).

1005ICT Object Oriented Programming – 2015-2 375

enqueue

peek

dequeue

back front

1005ICT Object Oriented Programming – 2015-2 376

15.3.6 Deques – double ended queues

Double ended queues, deques, are queues with no defined front or back,for when quick access is required to either the most or least recently addedthing.

15.3.7 Priority queues

Priority queues are like queues, with the extra feature that each elementhas a priority, that gets them to the front of the queue faster than any otherelement with a lesser priority.

1005ICT Object Oriented Programming – 2015-2 377

15.3.8 Maps

A map is an abstract data type that allows us to store and retrieve values bytheir unique key.

They correspond to functions in mathematics.

unique keys associated values1005ICT Object Oriented Programming – 2015-2 378

With a map, we want to:

• make an empty map;

• find out how many things are in the map;

• add a (key, value) pair into the map;

• find out if a key exists in the map.

• retrieve a value matching a key; and

• remove a key and its value from the map.

Arrays, as a mapping from positions to values, are a special case of map.

A bag is a mapping from keys to counting numbers.

1005ICT Object Oriented Programming – 2015-2 379

15.4 Implementing advanced data types

15.4.1 With arrays

All of the above advanced data structures can be implemented using arrays,with the proviso that you know the limits of their growth, and can make thearray big enough in the first place.

Stacks and queues are easy to build with arrays, however lists from whichwe insert and delete at arbitrary positions are not efficient to implement witharrays.

A buffer (commonly used in input/output systems) is typically a queue im-plemented with an array.

If the key values of a map are simply sequential (and easy to convert intoan int), arrays can be efficient, but if as happens very often the key valuesare sparse, messy things like names, then arrays are very inefficient.

1005ICT Object Oriented Programming – 2015-2 380

15.4.2 With dynamic, linked, recursive data structures

Many of these advanced data structures are implemented more efficientlywith types defined by classes, not arrays.

The trick is to define classes with fields of the same type as the class!

1005ICT Object Oriented Programming – 2015-2 381

15.4.3 Singly linked lists

A singly linked list is based on objects where each object in the list (calleda node) contains a reference to the next object.

+SinglyLinkedList()+insertAtHead(value : Object)+size() : int...

-value : Object-next : SinglyLinkedList

SinglyLinkedList

1005ICT Object Oriented Programming – 2015-2 382

The first such object in the list is called the head of the list, and all of therest together as the tail.

The only reference to the list that is maintained external to the list is to thehead.

head tail

1005ICT Object Oriented Programming – 2015-2 383

Since there is only easy access to one end of a singly linked list, they are anobvious way to implement a stack.

If the whole list needs to be processed in order, lists are also a good replace-ment for arrays, with the advantage that their size is dynamic, growing andshrinking as needed.

1005ICT Object Oriented Programming – 2015-2 384

15.4.4 Doubly linked lists

A doubly linked list is based on objects where each object in the list containsa reference to both the next object and the previous one.

+ DoublyLinkedList()+insertAtBack(value : Object)+insertAtFront(value : Object)+size() : int...

-value : Object-next : DoublyLinkedList-prev : DoublyLinkedList

DoublyLinkedList

To make some of its methods easier to write, a doubly linked list is usuallyarranged in a circle with a dummy node.

1005ICT Object Oriented Programming – 2015-2 385

backfront

dummy

1005ICT Object Oriented Programming – 2015-2 386

Since there is easy access to both ends of a doubly linked list, they are anobvious way to implement either queues or deques.

We commonly define just the doubly linked list type and then use it forstacks as well.

1005ICT Object Oriented Programming – 2015-2 387

15.4.5 Binary search trees

Lists are good at preserving the order of their elements.

But when elements need to be stored in order (say lexicographic) but areobtained in a random order, the process of finding the right place to insertthem can be slow.

(See the section on searching in the ITP lecture notes.)

Finding the right place in a list requires a linear search.

But the binary search tree allows the search to be much faster, like a binarysearch in an ordered array.

1005ICT Object Oriented Programming – 2015-2 388

Each node in a binary search tree has two references to other nodes, like adoubly linked list, but each now refers to left and right subtrees.

+BinarySearchTree()+add(value : Object)+size() : int...

-value : Object-left : BinarySearchTree-right : BinarySearchTree

BinarySearchTree

For any given node, the values in the left subtree are less than the node’svalue, and the values in the right subtree are greater than the node’s value.

1005ICT Object Oriented Programming – 2015-2 389

leaf

root

leaf

leaf

1005ICT Object Oriented Programming – 2015-2 390

The only external reference points to the root node of the tree.

Nodes without subtrees are leaves.

A balanced tree is close to symmetrical with respect to the numbers ofnodes on the left and right.

A balanced tree is very efficient to search as half the tree can be eliminatedfrom the search with every comparison.

As new values get added at the leaves, the tree might become unbalanced,but there are tricks for maintaining the balance by shifting exactly whichnode is the root, for example red-black trees.

Binary search trees are good for implementing sets.

They are even better for implementing maps.

To do this order the nodes by a key field and save an associated value aswell for each node.

1005ICT Object Oriented Programming – 2015-2 391

15.4.6 Hash tables

Hash tables are a very fast way to store a lot of values.

They combine an array and linked lists.

A hash function performs some quick calculation of which element of anarray to store the value in.

The array elements themselves can store multiple values, because they arethemselves linked lists.

1005ICT Object Oriented Programming – 2015-2 392

collisionhash

function

1005ICT Object Oriented Programming – 2015-2 393

A good hash function evenly distributes values across the array to avoidhaving to store multiple values in the lists (collisions).

Hash functions do not order the values, so they are very good for imple-menting sets.

They are also good for maps, if the order of the keys is not important, justfast access.

1005ICT Object Oriented Programming – 2015-2 394

15.5 Section summary

This section covered:

• abstract data types:

– sets and bags (multisets);

– lists (sequences), stacks, queues, and deques;

– maps;

• their implementation with:

– arrays;

– singly and doubly linked lists;

– binary search trees; and

– hash tables.1005ICT Object Oriented Programming – 2015-2 395

15.6 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 396

16 Generics

This section introduces generics, or parameterised classes.

The main use for this is to define container classes, which define usefulabstract data types for storing collections of objects.

It does this by way of example code for a container class, a double endedqueue, and a program that uses it, with and without generics.

1005ICT Object Oriented Programming – 2015-2 397

16.1 Before parameterised classes

Early versions of Java provided classes that implemented collections suchas linked lists and hash tables.

They all declared the type Object for their contained values.

They did this so that the container classes could contain any object type,because they are all subclasses of Object.

Putting any object into a container was easy.

Getting an object out of a container was error prone, because it was up tothe programmer to ensure that the object that came out was actually the typethey thought they had put in.

The compiler could not help by doing its job – type checking.

1005ICT Object Oriented Programming – 2015-2 398

16.1.1 Example – Deque

This class defines a double ended queue(without generics).

It is implemented with a doubly linked listwith a dummy head.

+DequeO()-DequeO(value : Object)+addToBack(value : Object)+addToFront(value : Object)+front() : Object+back() : Object+dropBack() : void+dropFront() : void+isEmpty() : boolean+length() : int

-value : Object-prev : DequeO-next : DequeO-length : int

Deque0

1005ICT Object Oriented Programming – 2015-2 399

backfront

dummy

1005ICT Object Oriented Programming – 2015-2 400

/*** file: DequeO.java

** author: Andrew Rock

** purpose: A double ended queue implementation

** using a circular doubly linked list

** with a dummy head node. This version

** does not use generics, and saves only

** references to Object.

*/

import java.util.*;

public class DequeO {

// the value stored at each nodeprivate Object value;

1005ICT Object Oriented Programming – 2015-2 401

private DequeOprev, // previous node,

// previous of head is the frontnext; // next node,

// next of the head is the back

// length of the deque,// only used in the dummy headprivate int length = 0;

// new DequeO() makes a new empty deque with// a dummy head node.public DequeO() {

value = null;prev = next = this;

}

1005ICT Object Oriented Programming – 2015-2 402

// new DequeO(value) makes a real node to// save the value.private DequeO(Object value) {

this.value = value;}

// addToBack(value) adds this value to the back.public void addToBack(Object value) {

DequeO n = new DequeO(value);this.next.prev = n;n.next = this.next;n.prev = this;this.next = n;this.length++;

}

1005ICT Object Oriented Programming – 2015-2 403

// addToFront(value) adds this value to the// front.public void addToFront(Object value) {

DequeO n = new DequeO(value);this.prev.next = n;n.prev = this.prev;n.next = this;this.prev = n;this.length++;

}

1005ICT Object Oriented Programming – 2015-2 404

// front() returns the value at the front.public Object front() {

if (length > 0) {return prev.value;

} else {throw new NoSuchElementException();

}}

// back() returns the value at the back.public Object back() {

if (length > 0) {return next.value;

} else {throw new NoSuchElementException();

}}

1005ICT Object Oriented Programming – 2015-2 405

// dropFront() detaches the front value.public void dropFront() {

if (length > 0) {this.prev = prev.prev;prev.next = this;this.length--;

} else {throw new NoSuchElementException();

}}

1005ICT Object Oriented Programming – 2015-2 406

// dropBack() detaches the back value.public void dropBack() {

if (length > 0) {this.next = next.next;next.prev = this;this.length--;

} else {throw new NoSuchElementException();

}}

// isEmpty() returns true iff the deque is// empty.public boolean isEmpty() {

return length == 0;}

1005ICT Object Oriented Programming – 2015-2 407

// length() returns the number of values in the// deque currently.public int length() {

return length;}

}

1005ICT Object Oriented Programming – 2015-2 408

16.1.2 Example problem requiring a deque

An organisation has a strict human resources policy for staff.

The only person that can be fired, is the most recently hired.

The only person that can retire, is the least recently hired.

Write a staff management program that saves the names of new hires andreports the names of the person to fire or retire.

The program should be interactive, with the following commands:

• h name – hire a person with this name.

• f – fire the most recent hire.

• r – retire the least recent hire.

• q – save the staff list for the next session and quit.

1005ICT Object Oriented Programming – 2015-2 409

16.1.3 An employee

This class represents one employee.

Each employee is to be assigned aunique id number.

The static members support this.

Employee

+Employee(name : String)+Employee(id : int, name : String)+getNextId() : int+setNextId(next_id : int) : void+getId() : int+getName() : String

-next_id : int-id : int-name : String

The two different constructors are for a genuinely new employee to be as-signed the next id, and for an employee with an existing id.

1005ICT Object Oriented Programming – 2015-2 410

/*** file: Employee.java

** author: Andrew Rock

** purpose: A personnel record.

*/

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

public class Employee {

// the next available id numberprivate static int next_id = 1;

private int id; // employee id number

1005ICT Object Oriented Programming – 2015-2 411

private String name; // employee name

// new Employee(name) makes a new Employee with// this name and the next available id number.public Employee(String name) {

this.id = next_id;next_id++;this.name = name.trim();

}

// new Employee(id, name) makes a new Employee// with this id and name.public Employee(int id, String name) {

this.id = id;this.name = name.trim();

}

1005ICT Object Oriented Programming – 2015-2 412

// getNextId() returns the next available// id number.public static int getNextId() {

return next_id;}

// setNextId(next_id) sets the next available// id number.public static void setNextId(int next_id) {

Employee.next_id = next_id;}

// getId() returns this employee’s id.public int getId() {

return id;}

1005ICT Object Oriented Programming – 2015-2 413

// getName() returns this employee’s name.public String getName() {

return name;}

}

1005ICT Object Oriented Programming – 2015-2 414

16.1.4 The program

This class is the main program.

The private methods represent the major ac-tions:

+main(args : String[]) : void-load() : void-save() : void-interact() : void

CampbellO-d : DequeO

1. Load the employee list from a file if there is one.

2. Interact with the user, modifying the employee list.

3. Save the employee list to a file.

1005ICT Object Oriented Programming – 2015-2 415

/*** file: CampbellO.java

** author: Andrew Rock

** purpose: A dumb HRM system, without generics.

*/

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

public class CampbellO {

// A deque contains the employees.private static DequeO d = new DequeO();

1005ICT Object Oriented Programming – 2015-2 416

// saved data file nameprivate static final String FILE_NAME =

"Campbell.txt";

public static void main(String[] args) {load();interact();save();

}

1005ICT Object Oriented Programming – 2015-2 417

// save() saves the next_id and employees// for the next session.private static void save() {

try {PrintStream out =

new PrintStream(FILE_NAME);out.println(Employee.getNextId());while (!d.isEmpty()) {

Employee f = (Employee) d.front();out.println(f.getId() + " " +

f.getName());d.dropFront();

}out.close();

Note the required type cast.

1005ICT Object Oriented Programming – 2015-2 418

} catch (Exception e) {System.err.println("Could not save " +

FILE_NAME);System.err.println(e);

}}

1005ICT Object Oriented Programming – 2015-2 419

// load() loads the next_id and employees// left from the previous session.private static void load() {

try {Scanner in =

new Scanner(new File(FILE_NAME));Employee.setNextId(in.nextInt());while (in.hasNextInt()) {

d.addToBack(new Employee(in.nextInt(),

in.nextLine()));}in.close();

} catch (Exception e) {// skip (there was no data file)

}}

1005ICT Object Oriented Programming – 2015-2 420

// interact() prompts for and processes user// commands.private static void interact() {

Scanner sc = new Scanner(System.in);System.out.print("? ");String command = sc.next();while (!command.equals("q")) {

if (command.equals("h")) {Employee e =

new Employee(sc.nextLine());d.addToBack(e);System.out.println(e.getName() +

" is hired as employee number " +e.getId() + ".");

1005ICT Object Oriented Programming – 2015-2 421

} else if (command.equals("f")) {try {

Employee b = (Employee) d.back();System.out.println("Employee " +

b.getId() + ", " +b.getName() + ", is fired.");

d.dropBack();} catch (NoSuchElementException e) {

System.err.println("No-one to fire.");

}

1005ICT Object Oriented Programming – 2015-2 422

} else if (command.equals("r")) {try {

Employee f = (Employee) d.front();System.out.println("Employee " +

f.getId() + ", " +f.getName() + ", has retired.");

d.dropFront();} catch (NoSuchElementException e) {

System.err.println("No-one to retire.");

}

1005ICT Object Oriented Programming – 2015-2 423

} else {System.out.println("Bad command.");

}System.out.print("? ");command = sc.next();

}}

}

In this program, putting Employees into the deque is easy, but taking themout requires a type cast back to Employee.

The compiler can’t tell whether what was put in was really an Employee.

Mistakes won’t be discovered until run time.

1005ICT Object Oriented Programming – 2015-2 424

16.2 Parameterised classes

Arrays are an example of a parameterized type.

We always declare an array by specifying its element type.

Arrays with different element types are different types themselves.

The compiler can check that all uses of the elements are correct with respectto their types.

The deque example above is useful for elements of any type, but the com-piler can’t check that the elements are used properly, causing type errors atrun time.

A safe solution would be to write a new implementation of deque for everyelement type, but that would be labourious.

1005ICT Object Oriented Programming – 2015-2 425

Parameterised classes, generics, allow the compiler to do this for us.

In C++, this is done by the compiler literally creating new source files withthe actual types substituted.

C++ parameterised classes are called templates.

1005ICT Object Oriented Programming – 2015-2 426

16.2.1 Generics syntax

Creating a parameterised class is similar to creating a method.

A method has parameters, that are passed actual values at run time.

A parameterised class has a type parameter that is substituted for an actualtype at compile time.

These type parameters are written between angle brackets < > after theclass name.

Separate multiple type parameters with commas.

The term “generics”, comes from the idea that the type parameter is justsome unspecified, generic class.

1005ICT Object Oriented Programming – 2015-2 427

16.2.2 Deque with generics

This is how a parameterised class is rep-resented in UML.

The dummy parameter type, E (for ele-ment), is declared in the dashed box attop-right.

The members are declared in terms of thattype.

E has replaced all mentions of Object.

+DequeG()-DequeG(value : E)+addToBack(value : E)+addToFront(value : E)+front() : E+back() : E+dropBack() : void+dropFront() : void+isEmpty() : boolean+length() : int

-value : E-prev : DequeG<E>-next : DequeG<E>-length : int

DequeGE

1005ICT Object Oriented Programming – 2015-2 428

/*** file: DequeG.java

** author: Andrew Rock

** purpose: A double ended queue implementation

** using a circular doubly linked list

** with a dummy head node. This version

** uses generics.

*/

import java.util.*;

public class DequeG<E> {

The class name is parameterised in the class header.

This declares the dummy type, which can now be used throughout the restof the class.

1005ICT Object Oriented Programming – 2015-2 429

// the value stored at each nodeprivate E value;

The value field is now an E, rather than an Object.

private DequeG<E>prev, // previous node,

// previous of head is the frontnext; // next node,

// next of the head is the back

The references to the previous and next nodes must be declared with theirfull type, parameter and all.

1005ICT Object Oriented Programming – 2015-2 430

// new DequeG() makes a new empty deque with// a dummy head node.public DequeG() {

value = null;prev = next = this;

}

// new DequeG(value) makes a real node to// save the value.private DequeG(E value) {

this.value = value;}

The names of the constructors should not be parameterised.

1005ICT Object Oriented Programming – 2015-2 431

// addToBack(value) adds this value to the back.public void addToBack(E value) {

DequeG<E> n = new DequeG<E>(value);this.next.prev = n;n.next = this.next;n.prev = this;this.next = n;this.length++;

}

The methods are all modified in this manner, and the rest are omitted fromthese notes for brevity.

1005ICT Object Oriented Programming – 2015-2 432

16.2.3 The client program with generics

Now, the HRM program with the differences indicated.

+main(args : String[]) : void-load() : void-save() : void-interact() : void

CampbellG-d : DequeG<Employee>

/*** file: CampbellG.java

** author: Andrew Rock

** purpose: A dumb HRM system, using generics.

*/

1005ICT Object Oriented Programming – 2015-2 433

// A deque contains the employees.private static DequeG<Employee> d =

new DequeG<Employee>();

Now the deque is declared with the actual type parameter, Employee.

The rest of the program is the same, except that no type casts are requiredwhen elements are retrieved from the deque:

Employee f = d.front();

and the compiler is able to verify that the types are compatible.

1005ICT Object Oriented Programming – 2015-2 434

16.3 Section summary

This section covered:

• the problem of type checking as elements are retrieved from a con-tainer class;

• a doubly linked list deque implementation, with a sample client pro-gram;

• generics, parameterised classes; and

• an example container class and client with generics.

1005ICT Object Oriented Programming – 2015-2 435

16.4 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 436

17 Interfaces

This introduces interfaces, which provide a flexible alternative to abstractclasses.

Nearly all of the classes in the Java API implement some interfaces.

We can not understand the organisation of much of the API, particularly thecollections framework, without understanding interfaces.

Interfaces are also required for event handling in graphical user interfaces.

1005ICT Object Oriented Programming – 2015-2 437

17.1 More abstract than abstract classes

17.1.1 Abstract classes

Abstract classes are ordinary classes except that they have one or moremethods defined with a header, but not implemented with a body.

They can define fields and implement some of their methods, but they leavesome of the implementation to their subclasses.

All of the subclasses share the common method declarations, and so presenta common interface to their client classes.

Subclasses may only extend one class though.

The hierarchy of classes formed through inheritance is very rigid.

1005ICT Object Oriented Programming – 2015-2 438

17.1.2 Interfaces

A Java interface is an alternative to an abstract class that is a purer definitionof just interface, without any implementation at all.

An interface may define:

• method headers; and

• static constants;

but may not define:

• method bodies;

• fields (other than static constants); or

• constructors.

1005ICT Object Oriented Programming – 2015-2 439

The advantage of this restriction is that any class may implement as manyinterfaces as we like, as well as extending its one superclass.

Implementing an interface, ensures that the class has implemented methodswith the defined interface, and can be used in a context where those methodsare required.

Implementing an interface is also known as realisation.

1005ICT Object Oriented Programming – 2015-2 440

17.2 UML representation

Abstract classes and methods areitalicized.

Interfaces are tagged with≪Interface≫ in the title.

≪ and ≫ are French double quotes,or double guillemets.

The realisation arrow is dashed.

Italics aren’t needed in an inter-face as all methods are unimple-mented. Circle

Shape

«Interface»Planar

+area() : double

«Interface»Drawable

+draw(g2 : Graphics2D) : void

Polygon

1005ICT Object Oriented Programming – 2015-2 441

17.3 Defining an interface

An interface is defined by replacing the keyword classwith interfaceand then declaring method headers and (sometimes) constants.

Example:

public interface Planar {

public double area();

}

1005ICT Object Oriented Programming – 2015-2 442

17.4 Implementing an interface

This simple class imple-ments (realises) Planar.

The implementskeyword is used likeextends.

public class Squareimplements Planar {

private double side;

public Square(double side) {this.side = side;

}

public double area() {return side * side;

}

}

1005ICT Object Oriented Programming – 2015-2 443

In the following example the abstract class Shape implements two inter-faces, but because it is abstract, it does not actually have to implement themethods.

public abstract class Shapeimplements Planar, Drawable {

protected double x, y; // location

}

1005ICT Object Oriented Programming – 2015-2 444

Non-abstract subclasses of Shape do have to implement the methods.

import java.awt.*;

public class Circleextends Shape {

private double radius;

public Circle(double x, double y,double radius) {

this.x = x;this.y = y;this.radius = radius;

}

1005ICT Object Oriented Programming – 2015-2 445

public double area() {return Math.PI * radius * radius;

}

public void draw(Graphics2D g2) {int d = (int) Math.round(2 * radius);g2.drawOval((int) Math.round(x),

(int) Math.round(y), d, d);}

}

1005ICT Object Oriented Programming – 2015-2 446

17.5 Case study: java.lang.Runnable

java.lang.Runnable is a simple example of an interface in the JavaAPI.

It defines just one method:

public void run()

A class that implements Runnable is usually intended to be used as aseparate thread, but it does have other uses.

See java.util.Timer and java.util.TimerTask.

The latter is an abstract class that implements Runnable.

1005ICT Object Oriented Programming – 2015-2 447

17.6 Case study: Comparable and Comparator

We should by now be familiar with the method in class String,compareTo(String).

It it actually declared by an interface, so that any class may declare such amethod.

java.lang.String is declared to implementjava.lang.Comparable<String>.

Note that this interface is parameterised so that the type of object that canbe compared to may be specified.

1005ICT Object Oriented Programming – 2015-2 448

Comparable is declared something like this:

public interface Comparable<T> {

public int compareTo(T o);

}

Any class can define its own compareTo.

This becomes its natural or intrinsic comparison method.

This natural comparison will be used, for example, for sorting an array withjava.util.Arrays.sort(Object[] a).

1005ICT Object Oriented Programming – 2015-2 449

Comparable is implemented like this:

public class Blobimplements Comparable<Blob> {

private int value;

public int compareTo(Blob b) {return this.value - b.value;

}

}

1005ICT Object Oriented Programming – 2015-2 450

There is another related interface, java.util.Comparator, which isdeclared like this:

public interface Comparator<T> {

public int compare(T o1, T o2);

}

compare(T,T) is different to compareTo(T).

It compares two objects, not the current object with another.

This allows the use of a comparison that is extrinsic, and different to thenatural comparison provided by compareTo(T), injava.util.Arrays.sort(T[], Comparator<T>).

1005ICT Object Oriented Programming – 2015-2 451

A comparator class is defined by implementing Comparator.

import java.util.*;

// reverses the natural comparison for Blobs.public class BlobComparatorimplements Comparator<Blob> {

public int compare(Blob b1, Blob b2) {return b2.compareTo(b1);

}

}

An instance of this can be passed to a sorting method.

1005ICT Object Oriented Programming – 2015-2 452

17.7 Case study: Iterable and Iterator

A class that implements Iterable<T> implements this method.

public Iterator<T> iterator()

which returns some instance of a class that implements Iterator.

1005ICT Object Oriented Programming – 2015-2 453

A class that implements Iterator<E> implements these methods:

public boolean hasNext()

public E next()

These methods should be familiar.

Scanner implements Iterator<String>.

An Iterator can produce elements one after the other until they are ex-hausted.

1005ICT Object Oriented Programming – 2015-2 454

If a class implements Iterable then it can be used with a for-in state-ment, as arrays can.

Most of the classes in the Java collections framework do this.

1005ICT Object Oriented Programming – 2015-2 455

17.8 Section summary

This section covered:

• interfaces;

• representing interfaces and realisation in UML;

• defining interfaces;

• implementing interfaces;

• the Runnable interface;

• the Comparable and Comparator interfaces; and

• the Iterable and Iterator interfaces and their relationship tofor-in statements.

1005ICT Object Oriented Programming – 2015-2 456

17.9 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 457

18 The Collections Framework

This section provides an overview of Java’s collections framework.

The collections framework consists of many of the classes and interfaces inpackage java.util.

The main aim is to provide just enough guidance so that you can pick theright classes to use for your applications.

There are more interfaces and classes in the framework than are describedhere, but they are for more specialised applications.

1005ICT Object Oriented Programming – 2015-2 458

18.1 The interfaces

The framework has been designed to provide a clear separation between theabstract data types (sets, queues, maps, etc., as described in section 15.3)and their implementations (with arrays, linked lists, trees, or hash tables, asdescribed in section 15.4).

The abstract data types are defined by interfaces, and the implementationswith classes.

All of the modern versions of the interfaces and classes use generics.

There are two hierarchies of interfaces: collections and maps.

1005ICT Object Oriented Programming – 2015-2 459

18.1.1 Collections

The collections are all containers for multiple elements.

They are all parameterised with respect to the generic element type E.

They are all subinterfaces of Iterable, and so may be used with for-inloops.

The subinterfaces of Collection are kinds of Sets, List, Queue andDeque.

1005ICT Object Oriented Programming – 2015-2 460

«Interface»Iterable

«Interface»NavigableSet

E

«Interface»SortedSet

E

«Interface»Set

E

«Interface»Collection

E

«Interface»Deque

E

«Interface»Queue

E«Interface»List

E

1005ICT Object Oriented Programming – 2015-2 461

Collection

A collection is the ba-sic container, with meth-ods for adding, removing,and testing for elements.

Elements may be added orremoved in bulk from an-other collection.

The <?> wildcard isused to indicate aCollection withany kind of element.

«Interface»Collection

add(e : E) : booleanaddAll(c : Collection<? extends E>) : booleanclear() : voidcontains(o : Object) : booleancontainsAll(c : Collection<?>) : booleanequals(o : Object) : booleanisEmpty() : booleanremove(Object : o) : booleanremoveAll(c : Collection<?>) : booleanretainAll(c : Collection<?>) : booleansize() : inttoArray(a : T[]) : <T> T[]

E

<? extends E> indicates any element type that is or extends E.

1005ICT Object Oriented Programming – 2015-2 462

Set

Interface Set has exactly the same methods as Collection, but thewording of the descriptions of the methods in the API are different anddeclare that the elements will be unique, as they should be for a set.

The operations that we expect to be able to perform with a set, are all there,but with the more general names.

operation symbol method nameis-an-element-of ∈ containsunion ∪ addAllintersection ∩ retainAlldifference − removeAllsubset-or-equals ⊆ containsAllcardinality # size

1005ICT Object Oriented Programming – 2015-2 463

SortedSet

Interface SortedSet is a set, but internally the elements are maintainedin order.

So it becomes possible to obtain the least and greatest elements, or subsetsbased on the ordering.

«Interface»SortedSet

...first() : EheadSet(toElement : E) : SortedSet<E>last() : EsubSet(fromElement : E, toElement : E) : SortedSet<E>tailSet(fromElement : E) : SortedSet<E>

E

1005ICT Object Oriented Programming – 2015-2 464

NavigableSet

Interface NavigableSet is a sorted set with extra methods for gettingfrom one element to the next, following the ordering.

«Interface»NavigableSet

...ceiling(e : E) : Efloor(e : E) : Ehigher(e : E) : Elower(e : E) : E

E

1005ICT Object Oriented Programming – 2015-2 465

List

Interface List extends Collection by adding methods that allow ac-cess to elements by their index (position).

«Interface»List

...add(index : int, element : E) : voidget(index : int) : EindexOf(o : Object) : intlastIndexOf(o : Object) : intremove(index : int) : Eset(index : int, element : E) : EsubList(fromIndex : int, toIndex : int) : List<E>

E

1005ICT Object Oriented Programming – 2015-2 466

Queue

Interface Queue extends Collection and behaves as we expect for aqueue.

Elements are added at the back, and we can only peek at or remove elementsfrom the front.

«Interface»Queue

...add(element : E) : booleanremove() : Epeek() : E

E

1005ICT Object Oriented Programming – 2015-2 467

Deque

Interface Deque extends Queue and behaves as we expect for a deque.

It also adds stack-like methods, there being no separate stack interface.

«Interface»Deque

...addFirst(e : E) : voidaddLast(e : E) : voidpeekFirst() : EpeekLast() : EremoveFirst() : EremoveLast() : Epop() : Epush(e : E) : void

E

1005ICT Object Oriented Programming – 2015-2 468

18.1.2 Maps

The map interfaces are all parameterised withrespect to two generic types:

• K – the unique key; and

• V – the value associated with each key.

«Interface»Map

K,V

«Interface»SortedMap

K,V

«Interface»NavigableMap

K,V

The relationships between Map, SortedMap, and NavigableMap aresimilar to the relationships between Set, SortedSet, andNavigableSet.

1005ICT Object Oriented Programming – 2015-2 469

Map

Interface Map provides the basic operations required for a map.

Note that the keys and values may be extracted as collections.

«Interface»Map

get(key : Object) : Vput(key : K, value : V) : VputAll(m : Map<? extends K,? extends V>) : voidcontainsKey(key : Object) : booleancontainsValue(value : Object) : booleanremove(key : Object) : VisEmpty() : booleansize() : intkeySet() : Set<K>values() : Collection<V>

K,V

1005ICT Object Oriented Programming – 2015-2 470

SortedMap

Interface SortedSet is a map, but internally the keys are maintained inorder.

So it becomes possible to obtain the least and greatest keys, or submapsbased on the ordering.

«Interface»SortedMap

...firstKey() : KlastKey() : KheadMap(toKey : K) : SortedMap<K,V>subMap(fromKey : K, toKey : K) : SortedMap<K,V>tailMap(fromKey : K) : SortedMap<K,V>

K,V

1005ICT Object Oriented Programming – 2015-2 471

NavigableMap

Interface NavigableMap is a sorted map with extra methods for gettingfrom one key to the next, following the ordering.

«Interface»NavigableMap

...ceilingKey(key : K) : KfloorKey(key : K) : KhigherKey(key : K) : KlowerKey(key : K) : K

K,V

1005ICT Object Oriented Programming – 2015-2 472

18.2 The classes

The classes that implement the interfaces above, typically have a two-partname.

The first part indicates the underlying implementation, and the second theabstract data type being implemented.

For example a HashMap uses a hash table to implement a map.

From what we know about how a hash table works, we can guess that itimplements Map, and not SortedMap.

There are two main groups of classes, those that are essentially linear datastructures, and those that are non-linear.

1005ICT Object Oriented Programming – 2015-2 473

The linear data structures versus the interfaces they implement:

array linked listList ArrayList LinkedListQueue ArrayDeque LinkedListDeque ArrayDeque LinkedList

The non-linear data structures versus the interfaces they implement:

tree hash tableSet TreeSet HashSetSortedSet TreeSetNavigableSet TreeSetMap TreeMap HashMapSortedMap TreeMapNavigableMap TreeMap

1005ICT Object Oriented Programming – 2015-2 474

18.2.1 ArrayList

ArrayList is a good general-purpose replacement for an array, with theadvantage that it can grow as needed.

«Interface»List

E

ArrayListArrayList()ArrayList(c : Collection<? extends E>)ArrayList(initialCapacity : int)...

E

1005ICT Object Oriented Programming – 2015-2 475

18.2.2 ArrayDeque

This is an array-based imple-mentation of queue, deque, orstack.

It can grow as needed.

«Interface »Deque

E

ArrayDequeArrayDeque()ArrayDeque(c : Collection<? extends E>)ArrayDeque(numElements : int)...

E

«Interface»Queue

E

1005ICT Object Oriented Programming – 2015-2 476

18.2.3 LinkedList

This is a linked-list-based im-plementation of list, queue,deque, or stack.

It can grow as needed, but itwill grow one node at a time,which might be less efficientthan ArrayDeque.

For lists, where elementswill be inserted in the mid-dle, it is more efficient thanArrayDeque.

«Interface»Deque

E

LinkedListLinkedList()LinkedList(c : Collection<? extends E>)...

E

«Interface»Queue

E«Interface»List

E

1005ICT Object Oriented Programming – 2015-2 477

18.2.4 TreeSet

This is a binary search tree-based implementation of aset.

It maintains the elements inorder, so use it if that matters.Otherwise, use HashSet.

«Interface»NavigableSet

E

TreeSetTreeSet()TreeSet(c : Collection<? extends E>)TreeSet(comparator : Comparator<E>)TreeSet(s : SortedSet<E>)...

E

«Interface»SortedSet

E

«Interface»Set

E

1005ICT Object Oriented Programming – 2015-2 478

18.2.5 TreeMap

This is a binary search tree-based implementation of amap.

It maintains the elements inorder, so use it if that matters.Otherwise, use HashMap.

TreeMapTreeMap()TreeMap(comparator : Comparator<K>)TreeMap(m : Map<K, V>)TreeMap(m : SortedMap<K, V>)...

K,V

«Interface»Map

K,V

«Interface»SortedMap

K,V

«Interface»NavigableMap

K,V

1005ICT Object Oriented Programming – 2015-2 479

18.2.6 HashSet

This is a hash table-based set. It is very efficient, but does not keep theelements in order.

«Interface»Set

E

HashSetHashSet()HashSet(c : Collection<? extends E>)HashSet(initialCapacity : int)...

E

1005ICT Object Oriented Programming – 2015-2 480

18.2.7 HashMap

This is a hash table-based map. It is very efficient, but does not keep theelements in order.

HashMapHashMap()HashMap(initialCapacity : int)HashMap(Map<K, V>)...

K,V

«Interface»Map

K,V

1005ICT Object Oriented Programming – 2015-2 481

18.3 Examples

Following are a couple of examples, using the collections framework.

1005ICT Object Oriented Programming – 2015-2 482

18.3.1 Dumb HRM example

Problem

Modify our dumb HRM system to use a collections framework class, in-stead of our own deque implementation.

Implementation

For this problem, we already know a deque is required.

The only question is which class is the best implementation, ArrayDequeor LinkedList?

Since there is no need to insert elements in the middle of the list, anArrayDeque will need to grow less often than a LinkedList, and isprobably preferable.

1005ICT Object Oriented Programming – 2015-2 483

+main(args : String[]) : void-load() : void-save() : void-interact() : void

Campbell-d : ArrayDeque<Employee>

/*** file: Campbell.java

** author: Andrew Rock

** purpose: A dumb HRM system, using the

** collections framework.

*/

1005ICT Object Oriented Programming – 2015-2 484

// A deque contains the employees.private static Deque<Employee> d =

new ArrayDeque<Employee>();

Note particularly that we declare d to be a Deque, the interface that definesthe operations that may be performed with a deque and no others.

This limits us to only be able to use d as a deque.

We then instantiate it as an instance of ArrayDeque, choosing the bestimplementation for our purpose.

1005ICT Object Oriented Programming – 2015-2 485

The rest of the program is the same, except that:

• the deque method names are changed to those used in Deque inter-face (for example addToBack becomes addLast); and

• different exceptions are caught when the the deque is empty(NullPointerException).

1005ICT Object Oriented Programming – 2015-2 486

18.4 Indicating container classes in UML

Use a dashed line beween a container class and the association line to indi-cate how one class’s instances associate with others via the container class.

AccountAccountManager

SortedMap<AccountNumber, Account>

*

1005ICT Object Oriented Programming – 2015-2 487

18.5 A more complex example: CrossRef

See the CrossRef example program.

It features a HashSet, and a TreeMap of Queues.

1005ICT Object Oriented Programming – 2015-2 488

18.6 Section summary

This section covered:

• an overview of the collection framework’s

– interfaces; and

– classes;

• and guidance on which one to pick when.

1005ICT Object Oriented Programming – 2015-2 489

18.7 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 490

19 Inner Classes

This section introduces inner, or nested classes.

These are useful for very small classes that need access to the members oftheir parent class.

There are four distinct kinds of inner classes:

• static member classes;

• dynamic member classes;

• local classes; and

• anonymous local classes.

The last one is the most useful for building programs with GUIs.

1005ICT Object Oriented Programming – 2015-2 491

19.1 General costs and benefits

An inner class is one that is defined inside another class.

An inner class should be considered over another separate class when:

• it is likely to be small (a few simple members);

• it is unlikely to be reusable outside the context of its parent class;

• it needs privileged access to the members of its parent class; and

• no other class needs access to it.

It can save having a separate source file for a simple class, but comes at thecost of not being reusable.

1005ICT Object Oriented Programming – 2015-2 492

19.2 Static member classes

A static member class is what it sounds like: a class defined as a member(inside) of another class, with the modifier static.

It behaves like an ordinary class, but it has access to the static members ofits parent class, even the private ones.

It does not have access to the dynamic members of the parent class, and cannot use this to refer to an instance of the parent class.

The parent class also has access to all the inner class’s members, even theprivate ones.

1005ICT Object Oriented Programming – 2015-2 493

19.3 Dynamic member classes

A dynamic member class is what it sounds like: a class defined as a member(inside) of another class, without the modifier static.

It behaves like an ordinary class, but it has access to the static and dynamicmembers of its parent class, even the private ones.

19.3.1 Example with UML representation

To demonstrate an member class, here is a slightly improved version of ourimplementation of a deque.

1005ICT Object Oriented Programming – 2015-2 494

The version with generics has one inefficiency, every node has a lengthfield, but only the one in the dummy head is ever used.

+DequeG()-DequeG(value : E)+addToBack(value : E)+addToFront(value : E)+front() : E+back() : E+dropBack() : void+dropFront() : void+isEmpty() : boolean+length() : int

-value : E-prev : DequeG<E>-next : DequeG<E>-length : int

DequeG E

1005ICT Object Oriented Programming – 2015-2 495

The length can be retained in the deque class, with a inner class used todefine the nodes.

+DequeI()+addToBack(value : E)+addToFront(value : E)+front() : E+back() : E+dropBack() : void+dropFront() : void+isEmpty() : boolean+length() : int

-length : int-head : Node

DequeI E

-value : E-prev : Node-next : Node

Node

Note the UML notation for an inner class.

1005ICT Object Oriented Programming – 2015-2 496

/*** file: DequeI.java

** author: Andrew Rock

** purpose: A double ended queue implementation

** using a circular doubly linked list

** with a dummy head node. This version

** uses generics, and an inner class.

*/

import java.util.*;

public class DequeI<E> {

// length of the dequeprivate int length = 0;

1005ICT Object Oriented Programming – 2015-2 497

// A node in the circular linked list.private class Node {

// the value stored at each nodeprivate E value;

private Nodeprev, // previous node,

// previous of head is the frontnext; // next node,

// next of the head is the back

}

// the dummy head nodeprivate Node head = new Node();

1005ICT Object Oriented Programming – 2015-2 498

Now we only need the one public constructor.

// new DequeI() makes a new empty deque with// a dummy head node.public DequeI() {

head.value = null;head.prev = head.next = head;

}

We can now always refer to the dummy head explicitly, instead of justthis, which is a bit clearer.

1005ICT Object Oriented Programming – 2015-2 499

// addToBack(value) adds this value to the back.public void addToBack(E value) {

Node n = new Node();n.value = value;head.next.prev = n;n.next = head.next;n.prev = head;head.next = n;length++;

}

The rest of the code is modified in a similar way.

1005ICT Object Oriented Programming – 2015-2 500

19.4 Local classes

Local classes are local in the same sense that local variables are local –declared inside a method.

The syntax is the same as a normal class, but without any of the modifiers(static, private, etc.) which can’t be applied to local variables either.

The class has access to all of the methods local variables and parameters.

If only one instance of this local class is needed, which is the usual case, itis usually better to use an anonymous local class.

For this reason, this kind of inner class is rarely used.

1005ICT Object Oriented Programming – 2015-2 501

19.5 Anonymous local classes

An anonymous local class is defined, and its single instance instantiated, allin one expression.

This expression can be used anywhere an expression of that type can beused, even and commonly as an actual parameter in a method call.

We will complete the introduction of this type of inner class, by example,in the next section on GUIs.

We will use it to define event handlers.

1005ICT Object Oriented Programming – 2015-2 502

19.6 Section summary

This section defined:

• the four kinds of inner class;

• how to represent an inner class in UML; and

• showed an example of dynamic member class.

1005ICT Object Oriented Programming – 2015-2 503

19.7 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 504

20 GUI Components and Events

This section develops a program with a graphical user interface, built fromSwing components.

20.1 The problem

Our client wants the Human Resource Management (HRM) system we builtto retain its existing functionality, but with a Graphical user interface (GUI).

They do want one extra feature. They would like to be able to view thecurrent staff roster within the interface.

1005ICT Object Oriented Programming – 2015-2 505

20.2 Design

For this program, there are two aspects to the design:

• the layout of the the GUI; and

• the class design.

20.2.1 GUI design

We should plan the components, and how they will function.

This requires both a diagram and explanatory notes.

1005ICT Object Oriented Programming – 2015-2 506

This is a mock up of the desired interface, a window featuring labels, a textfield, a scrollable text area, and buttons.

Campbell

1 Hank Zappa2 Lady Dada

1New name:

2Rick Aspley

3Hire

4Roster:

5

6 7Fire Retire

8X

1005ICT Object Oriented Programming – 2015-2 507

Component descriptions and behaviours:

1. Label New name: indicates the purpose of the text field.

2. Text field where the name of a new employee may be entered.

Should be able to hire on pressing the return/enter key.

3. Button Hire hires the new employee whose name in the text area.

4. Label Roster: indicates the purpose of the text area.

5. Text area where staff roster is displayed.

It should be scrollable to accommodate a long list.

6. Button Fire fires the newest employee.

7. Button Retire retires the oldest employee.

8. Lastly, closing the frame, saves the roster and quits the program.1005ICT Object Oriented Programming – 2015-2 508

20.2.2 Class designs

We are not starting this program from scratch.

We already have a variety of existing console implementations to choosefrom.

We should start from the version that uses java.util.ArrayDeque,because that class has more flexibility and features than our own dequeimplementations.

It will allow us access to all the employees, not just the first and last.

It is good practice to try to reuse as much of the existing program as possi-ble, and to avoid having duplication of code.

That is, the console and GUI versions should share as much common codeas possible.

1005ICT Object Oriented Programming – 2015-2 509

This is how the classes are associated in the old console version.

+main(args : String[]) : void-load() : void-save() : void-interact() : void

Campbell

Employee

ArrayDeque

*-d

The problem with this, as a starting point for development of the GUI ver-sion, is that the main class has two roles combined: managing the staffroster and providing the console user interface.

Separating those into two separate classes will allow the reuse of the staffroster in the GUI version.

1005ICT Object Oriented Programming – 2015-2 510

The rearrangement of existing code into different classes is called refactor-ing.

+main(args : String[]) : void-interact() : void

-APP_NAME : String {readOnly}-FILE_NAME : String {readOnly}

CampbellT

Employee

ArrayDeque

*-d

+save(fileName : String) : void+load(fileName : String) : void+hire(who : String) : Employee+fire() : Employee+retire() : Employee

Roster

1-roster

1005ICT Object Oriented Programming – 2015-2 511

class Employee – no change.

class Roster – new, manages the roster. New methods for hiring andfiring return the affected employee so that the client program can out-put information if it wants to.

+save(fileName : String) : void– load the roster from a disk file, if it exists.

+load(fileName : String) : void– saves the roster to the disk file.

+hire(who : String) : Employee– hires a new employee.Returns the new employee, or null if who is blank.

+fire() : Employee– returns the fired employee or null.

+retire() : Employee– returns the retired employee or null.

1005ICT Object Oriented Programming – 2015-2 512

class CampbellT – modified, now only performs the I/O.

-APP NAME : String {readOnly}– the name of the app.

-FILE NAME : String {readOnly}– the name of the file to save the roster to.

-roster : Roster– manages the staff roster.

+main(args : String[]) : void– main method.

-interact() : void– accepts user commands and prints messages as actions arecarried out.

1005ICT Object Oriented Programming – 2015-2 513

Now we can replace the console version of the main class with a GUI ver-sion. (We don’t yet know the details of required new members.)

+main(args : String[]) : void...

-APP_NAME : String {readOnly}-FILE_NAME : String {readOnly}...

CampbellGUI

Employee

ArrayDeque

*-d

+save(fileName : String) : void+load(fileName : String) : void+hire(who : String) : Employee+fire() : Employee+retire() : Employee

Roster

1-roster

1005ICT Object Oriented Programming – 2015-2 514

20.3 New console implementation

/*** file: Roster.java

** author: Andrew Rock

** purpose: Roster for a dumb HRM system.

*/

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

public class Roster {

// A deque contains the employees.private Deque<Employee> d =

new ArrayDeque<Employee>();

1005ICT Object Oriented Programming – 2015-2 515

These are changed to make them use the filename parameter.

// save(fileName) saves the names left for the// next session.public void save(String fileName) {

// load(fileName) loads the names left from the// previous session.public void load(String fileName) {

Next the new methods for hiring, firing and retiring.

1005ICT Object Oriented Programming – 2015-2 516

// hire(who) hires a new employee.// Returns the new employee or null.public Employee hire(String who) {

who = who.trim();if (who.length() > 0) {

Employee e = new Employee(who);d.addLast(e);return e;

} else {return null;

}}

1005ICT Object Oriented Programming – 2015-2 517

// fire() fires the newest employee.// Returns the fired employee or null.public Employee fire() {

try {return d.removeLast();

} catch (Exception e) {return null;

}}

1005ICT Object Oriented Programming – 2015-2 518

// retire() retires the oldest employee.// Returns the retired employee or null.public Employee retire() {

try {return d.removeFirst();

} catch (Exception e) {return null;

}}

1005ICT Object Oriented Programming – 2015-2 519

/*** file: CampbellT.java

** author: Andrew Rock

** purpose: A dumb HRM system text version.

*/

import java.util.*;

public class CampbellT {

// app nameprivate static final String APP_NAME =

"Campbell";

// saved data file nameprivate static final String FILE_NAME =

APP_NAME + ".txt";1005ICT Object Oriented Programming – 2015-2 520

// the staff rosterprivate static Roster roster = new Roster();

public static void main(String[] args) {roster.load(FILE_NAME);interact();roster.save(FILE_NAME);

}

1005ICT Object Oriented Programming – 2015-2 521

// interact() prompts for and processes user// commands.private static void interact() {

Scanner sc = new Scanner(System.in);System.out.print("? ");String command = sc.next();while (!command.equals("q")) {

if (command.equals("h")) {Employee e = roster.hire(sc.nextLine());if (e != null) {

System.out.println(e.getName() +" is hired as employee number " +e.getId() + ".");

} else {System.err.println(

"No name to hire.");}

1005ICT Object Oriented Programming – 2015-2 522

} else if (command.equals("f")) {Employee f = roster.fire();if (f != null) {

System.out.println("Employee " +f.getId() + ", " +f.getName() + ", is fired.");

} else {System.err.println(

"No-one to fire.");}

} else if (command.equals("r")) {Employee r = roster.retire();if (r != null) {

System.out.println("Employee " +r.getId() + ", " +r.getName() + ", has retired.");

} else {1005ICT Object Oriented Programming – 2015-2 523

System.err.println("No-one to retire.");

}} else {

System.out.println("Bad command.");}System.out.print("? ");command = sc.next();

}}

}

1005ICT Object Oriented Programming – 2015-2 524

20.4 GUI implementation

20.4.1 main and frame

We start by creating the main method and the code for putting up the frame.

Mostly this is the same as we have done before in the 2D graphics examples.

/*** file: CampbellGUI.java

** author: Andrew Rock

** purpose: A dumb HRM system, with a GUI.

*/

import java.awt.*;import javax.swing.*;

1005ICT Object Oriented Programming – 2015-2 525

public class CampbellGUI {

Same as the console version:

// app nameprivate static final String APP_NAME =

"Campbell";

// saved data file nameprivate static final String FILE_NAME =

APP_NAME + ".txt";

// the staff rosterprivate static Roster roster = new Roster();

1005ICT Object Oriented Programming – 2015-2 526

The frame, and any components that we need to access from multiple meth-ods, we make global.

// the frameprivate static JFrame frame =

new JFrame(APP_NAME);

public static void main(String[] args) {roster.load(FILE_NAME);layoutComponents();addListeners();frame.setDefaultCloseOperation(

JFrame.EXIT_ON_CLOSE);frame.pack();frame.setVisible(true);

}

1005ICT Object Oriented Programming – 2015-2 527

In the main method, we:

• load the roster from disk;

• delegate the layout of the components, and the setting up of eventhandling to other methods;

• set the program to quit when the window is closed;

• set the size of the window (using pack() to set the minimum sizethat fits all the components); and

• make the frame visible.

1005ICT Object Oriented Programming – 2015-2 528

20.4.2 Components and layout

In our previous graphics examples, we only had one component to put intothe frame and it filled the content area of the frame.

When we have multiple components in a frame, or any container, there aremany ways that the components could be placed relative to each other.

In GUI frameworks that do not have to be platform independent, the com-ponents can be placed manually using graphical tools.

Such tools exist for Java, but to use them, you need to understand the codethat they will generate.

We will lay out our components with just Java code.

1005ICT Object Oriented Programming – 2015-2 529

A Container delegates the layout of the Components it contains to aLayoutManager.

There are many different classes that implement the LayoutManager in-terface.

Some are simple and only work for simple cases.

The best one, for flexibility and total control, is GridBagLayout.

The simplest one that is still quite powerful is javax.swing.BoxLayout,and that is the only one we will use in these lecture notes.

A BoxLayout can be used to lay out com-ponents along the x-axis.

1005ICT Object Oriented Programming – 2015-2 530

A BoxLayout can also be used to layout components along the y-axis.

By nesting Containers withBoxLayouts components may belaid out in all kinds of 2-dimensionalarrangements.

1005ICT Object Oriented Programming – 2015-2 531

This shows how we can nest box layouts to make our GUI.

Campbell

1 Hank Zappa2 Lady Dada

New name: Rick Aspley HireRoster:

Fire Retire

X

We will use JPanels as the containers that use the BoxLayouts.

1005ICT Object Oriented Programming – 2015-2 532

Here are the components that we need to declare globally:

// input text fieldprivate static JTextField nameField =

new JTextField(20);

// Output text area:private static JTextArea rosterArea =

new JTextArea(10, 25);

// buttons:private static JButton

hireBtn = new JButton("Hire"),fireBtn = new JButton("Fire"),retBtn = new JButton("Retire");

1005ICT Object Oriented Programming – 2015-2 533

Set up the panels and the box layouts and their orientations.

// layoutComponents() lays out the components.private static void layoutComponents() {

JPanel box0 = new JPanel(),box1 = new JPanel(),box2 = new JPanel(),box3 = new JPanel();

box0.setLayout(new BoxLayout(box0,BoxLayout.Y_AXIS));

box1.setLayout(new BoxLayout(box1,BoxLayout.X_AXIS));

box2.setLayout(new BoxLayout(box2,BoxLayout.Y_AXIS));

box3.setLayout(new BoxLayout(box3,BoxLayout.X_AXIS));

1005ICT Object Oriented Programming – 2015-2 534

Add box0 to the frame’s content area, and then nest the other three boxes.

frame.add(box0);box0.add(box1);box0.add(box2);box0.add(box3);

Center the nested boxes within box0.

box1.setAlignmentX(Component.CENTER_ALIGNMENT);

box2.setAlignmentX(Component.CENTER_ALIGNMENT);

box3.setAlignmentX(Component.CENTER_ALIGNMENT);

1005ICT Object Oriented Programming – 2015-2 535

Adding a border to each box allows a little spacing out.

box1.setBorder(new EmptyBorder(5, 5, 5, 5));box2.setBorder(new EmptyBorder(5, 5, 5, 5));box3.setBorder(new EmptyBorder(5, 5, 5, 5));

Need to add this to the top:

import javax.swing.border.*;

Add the components to the top box.

box1.add(new JLabel("New name:"));box1.add(nameField);box1.add(hireBtn);

1005ICT Object Oriented Programming – 2015-2 536

Add and align the label in the middle box.

JLabel rosterLbl = new JLabel("Roster:");box2.add(rosterLbl);rosterLbl.setAlignmentX(

Component.LEFT_ALIGNMENT);

The text area is for output only.

rosterArea.setEditable(false);

Fill it with the text to display. (A toString() method needs to be addedto class Roster.)

rosterArea.setText(roster.toString());

1005ICT Object Oriented Programming – 2015-2 537

We don’t add the text area directly.

It does not have its own scrolling functionality.

We embed it in a JScrollPane and add and align that.

JScrollPane scroller =new JScrollPane(rosterArea);

box2.add(scroller);scroller.setAlignmentX(

Component.LEFT_ALIGNMENT);

Finally, add the hire and retire buttons to the bottom box.

box3.add(fireBtn);box3.add(retBtn);

}

1005ICT Object Oriented Programming – 2015-2 538

20.4.3 Event handling

Now we need to get the components to trigger the actions we want per-formed.

This is done with event handling.

We will set up event handling in this method.

// addListeners() adds event listeners to the// components and the frame.private static void addListeners() {

and we’ll need to add this at the top:

import java.awt.event.*;

1005ICT Object Oriented Programming – 2015-2 539

This is what happens when a user clicks a mouse with the pointer over abutton in a Java program’s window:

• The mouse hardware sends a message via its connection (say USB)to the PC hardware.

• The operating system combines the fact that the mouse was clickedwith the current location of the pointer (which it manages) to form anevent.

• The operating system determines what area of the display the locationis in, and so what program needs to deal with the event.

1005ICT Object Oriented Programming – 2015-2 540

• The event is sent to the program that needs it.

It is sent as a message. That is, the operating system calls a methodwithin the program.

If the program is a Java program, then the message is sent to the JVM.

• The JVM determines which window the mouse was clicked in, andthe event is sent as a message to that window.

• The message is sent down through the nested containers, until it reachesthe button.

So if we want the button to initiate some action, we have to provide themethod that will be called and passed the event as an argument.

1005ICT Object Oriented Programming – 2015-2 541

In Java we can’t just supply a method on its own to receive the event.

All Java methods have to be defined in a class.

For buttons, the class must implement the ActionListener interface.

That interface defines just one method to implement.

There will only be one instance of this class.

These conditions are just right for using an anonymous inner class!

«anonymous»ActionListener

«interface»ActionListener

+actionPerformed(e : ActionEvent) : void

Component

button, text field, ...

1005ICT Object Oriented Programming – 2015-2 542

We’ll add a listener to the fire button first, as it is the simplest case.

fireBtn.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {roster.fire();rosterArea.setText(

roster.toString());}

});

1005ICT Object Oriented Programming – 2015-2 543

In one statement, we have

• defined a new, anonymous class that implements ActionListener;

• implemented its actionPerformed method, in which:

– someone gets fired; and

– the roster text area gets updated;

• instantiated a single instance of the new class; and

• passed that instance as a parameter to addActionListener toadd this listener object to the fire button.

So now the fire button can accept the event and trigger the actions we want.

1005ICT Object Oriented Programming – 2015-2 544

Similarly for the retire button:

retBtn.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {roster.retire();rosterArea.setText(

roster.toString());}

});

1005ICT Object Oriented Programming – 2015-2 545

The hire button, and pressing enter in the input text field, both need to initi-ate the same action, so they can share the same listener.

ActionListener hireAL =new ActionListener() {

public void actionPerformed(ActionEvent e) {roster.hire(nameField.getText());nameField.setText("");rosterArea.setText(

roster.toString());}

};nameField.addActionListener(hireAL);hireBtn.addActionListener(hireAL);

1005ICT Object Oriented Programming – 2015-2 546

Our program can now hire and fire, but there is one problem remaining.

The program will exit when the window is closed.

We need an opportunity to save the roster before the program quits.

We do this by listening for a window event.

The process is similar.

The interface WindowListener defines a windowClosing methodthat we can use to call roster.save, in our implementation.

However WindowListener defines lots of other methods that we don’twant to have to implement.

1005ICT Object Oriented Programming – 2015-2 547

For this reason, there is an abstract class WindowAdapter that imple-ments all of those methods with dummy handlers.

Extending that only requires implementing the method we want.

«anonymous»WindowAdapter

«interface»WindowListener

+windowClosing(e : WindowEvent) : void...

JFrame

WindowAdapter

1005ICT Object Oriented Programming – 2015-2 548

This completes our program.

frame.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e) {roster.save(FILE_NAME);

}});

}

Go play!

1005ICT Object Oriented Programming – 2015-2 549

20.5 Section summary

This monster section covered:

• GUI design with a sketch and textual description;

• refactoring;

• separating the user interface from the rest, so it can be replaced;

• laying out components with BoxLayouts;

• components JPanel, Jlabel, JButton, JTextField,JTextArea, and EmptyBorder;

• event handling with interface ActionListener and abstract classWindowAdapter; and

• anonymous inner classes for event listeners.1005ICT Object Oriented Programming – 2015-2 550

20.6 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 551

21 Sundries

This section is small collection of topics that will help you deepen yourunderstanding of Java.

1005ICT Object Oriented Programming – 2015-2 552

21.1 Expressions as statements

In C-like languages, the commonest kind of statement is the expressionstatement.

Any expression followed by a semi-colon is a statement.

This includes these familiar kinds of statements:

• a procedure call;

System.out.println("Boo!");

• an expression that includes the assignment operator (=), making anassignment statement;

line = sc.nextLine();

1005ICT Object Oriented Programming – 2015-2 553

and also these unfamiliar kinds of statements:

• just an expression;

i++; // useful3 + 4; // calculates 7, then throws it away

• just an expression that is a function call;

sc.nextLine(); // skip the next line

These are just expressions, and the results are always thrown away aftercalculation, but they can have useful side-effects.

(MaSH did not include such statements, as they can hinder the learning ofthe more common kinds of statements and the critical difference between aprocedure and a function.)

1005ICT Object Oriented Programming – 2015-2 554

21.2 Order of field initialisation

The order with which the fields of a class are initialised is set as follows:

1. When a class is loaded, the static fields are initialised immedi-ately.

This happens before the main method if there is one.

2. When an object is instantiated the dynamic fields are initialised im-mediately.

This happens before the statements in the constructor execute.

1005ICT Object Oriented Programming – 2015-2 555

This can be illustrated with the following class which has static and dynamicfields.

public class Order {

private static int a = echo("a");private static final int B = echo("B");private static int c = echo("c");private int d = echo("d");private final int E = echo("E");private int f = echo("f");private int g;

1005ICT Object Oriented Programming – 2015-2 556

The function order(String) has type int, so it can be used to initialiseall of the fields.

It also has the side-effect of printing a string, so we can see when each callto it is executed.

private static int echo(String s) {System.out.println(s);return 0;

}

1005ICT Object Oriented Programming – 2015-2 557

A main method invokes the constructor.

public static void main(String[] args) {Order o = new Order();

}

private Order() {g = echo("g");

}

}

1005ICT Object Oriented Programming – 2015-2 558

Output:

$ javac Order.java$ java OrderaBcdEfg$

1005ICT Object Oriented Programming – 2015-2 559

21.3 Advanced inheritance

21.3.1 Overriding

When a class extends another, or implements an interface it must im-plement any abstract methods in the superclass or interface, unless it is anabstract class itself.

When a class extends another it may also replace the implementation ofthe non-abstract methods in its superclass.

Either case is called overriding the method.

The subclass overrides the method in the superclass.

1005ICT Object Oriented Programming – 2015-2 560

21.3.2 super-duper

A problem when overriding is that if we want the implementation of amethod in a subclass to be nearly the same as the implementation in thesuperclass, we will have to repeat much of the same code in the subclass.

It might not be possible to re-implement that same code if it needs accessto private members in the superclass.

In these cases the super keyword is useful.

super is used a lot like this.

It refers to the current object, but as if it was an instance of its immediatesuperclass.

1005ICT Object Oriented Programming – 2015-2 561

21.3.3 super in constructors

Just as

this(...);

can be used to invoke one of the current object’s other constructors, so can

super(...);

be used to invoke one of the superclass’s constructors.

It must be the first statement in the subclass’s constructor.

This is such good practice, ensuring all the fields defined by the superclassare initialised properly, that the compiler actually makes it mandatory.

1005ICT Object Oriented Programming – 2015-2 562

If the subclass’s constructor does not call a superclass’s constructor, thecompiler will call

super(); // superclass’s no-arg constructor

automatically before any of the other statements in the subclass’s construc-tor.

1005ICT Object Oriented Programming – 2015-2 563

21.3.4 super to access superclass fields

Just as a local variable eclipses a global variable, if a subclass defines a fieldwith the same name as one in its superclass, it eclipses it.

The superclass field can’t be accessed any more, because use of the namerefers to the subclass field.

super can be used like this to get around this.

The following program, made up of two classes, demonstrates this.

Note the order of all of the output.

1005ICT Object Oriented Programming – 2015-2 564

public class Super {

protected double x;

public Super() {System.out.println("In Super.Super().");x = 3.3;

}

}

public class Subextends Super {

private int x;

1005ICT Object Oriented Programming – 2015-2 565

public Sub () {System.out.println("In Sub.Sub().");x = 2;

}

public void show() {System.out.println("In Sub.show():");System.out.println(" this.x = " + this.x);System.out.println(" super.x = " + super.x);

}

public static void main(String[] args) {System.out.println("In Sub.main().");Sub sub = new Sub();sub.show();

}}1005ICT Object Oriented Programming – 2015-2 566

$ javac *.java$ java SubIn Sub.main().In Super.Super().In Sub.Sub().In Sub.show():this.x = 2super.x = 3.3

$

1005ICT Object Oriented Programming – 2015-2 567

21.3.5 super to access overridden methods

super can also be used to invoke the version of a method that has beenoverridden.

It can only be invoked within the subclass.

1005ICT Object Oriented Programming – 2015-2 568

21.4 Section summary

This section covered:

• the ways expressions make statements;

• the order in which fields get initialised; and

• overriding and the super keyword.

1005ICT Object Oriented Programming – 2015-2 569

21.5 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 570

22 Fit and Finish

We can now build Java applications, but just using javac leaves us with amessy folder full of .java and .class files.

This is not ready for deployment or shipping to a client.

What can we do to lift our work to a professional standard?

• Comment and document the code to professional standards.

• Deploy the compiled code only, as a single file.

• Make the program easy to launch, following the normal conventionsof the target platform.

1005ICT Object Oriented Programming – 2015-2 571

22.1 Use an IDE

Professional applications are built with professional tools.

Most developers work within an integrated development environment (IDE).

Traditionally an IDE provides at least:

• an editor that knows the conventions of the language and can:

– highlight syntax;

– match braces;

– help layout the code neatly;

– type some code automatically;

• a one-click way to compile and run a program.

1005ICT Object Oriented Programming – 2015-2 572

But those things are mere conveniences, and not enough reason to use asystem dedicated to just one programming language.

For Java the main reasons for using an IDE are to do with using all of theJava development tools, not just the compiler, particularly:

• javadoc, for automatically generating HyperText Markup Language(HTML) documentation (as per the API) from the source code, withspecially formatted comments;

• jar, to combine all of the .class files and other resources into asingle file for deployment; and

• source-level debugging.

javadoc and jar tools can be used from the command line, like javac,but they are much easier to use via an IDE.

1005ICT Object Oriented Programming – 2015-2 573

22.2 Doc comments

javadoc parses the actual Java code to determine much of the informationit displays, but also relies on specially formatted comments created by theprogramer.

A doc comment appears just before the class or member that it describes,and has an extra asterisk at the start:

/*****/

The extra asterixes down the left are conventional as well.

1005ICT Object Oriented Programming – 2015-2 574

22.2.1 Summary sentence

The first sentence in a doc comment should be a summary that describes thepurpose of the class or member.

This sentence will appear at the start of the class’s documentation, and also,by itself in the summary of all classes.

22.2.2 Additional paragraphs

After the first sentence, can come as much text as you like.

Mark it up with simple HTML to format it.

1005ICT Object Oriented Programming – 2015-2 575

22.2.3 Tags

After the descriptive text, come important descriptions of aspects of theclass or method.

Each short description is tagged with a symbol starting with @.

Different declarations need different tags.

One of the things a good IDE can do is suggest for you which tags areneeded.

Important tags for classes:

@author namethe name of the author. Use multiple times if there are multiple au-thors.

@version textsomething that identifies the version of the class.

1005ICT Object Oriented Programming – 2015-2 576

Important tags for methods/constructors:

@param parameter-name descriptionthe name and purpose of each parameter

@exception exception-class-name descriptionshows that this method throws this exception and why

Important tags for functions:

@return descriptionwhat does the function return

There are many more, though less frequently used.

See Oracle’s on-line documentation for javadoc.

1005ICT Object Oriented Programming – 2015-2 577

22.3 Packaging as a jar file

jar (Java Archive) is a modified version of the zip tool.

It is for creating a compressed archive of all of the class files and otherresources that comprise a Java application.

The JVM can run the program from within the archive.

The .jar file contains metadata that say which class is the main class,containing the main method.

Preparing this metadata is difficult and best done automatically by the IDE.

1005ICT Object Oriented Programming – 2015-2 578

22.3.1 Running a jar file

To run a program that has been packaged in a .jar file:

$ java -jar Program.jar

On a Mac, you can just double-click the .jar file.

To really make a Java program look like a native application, there areplatform-specific tools for bundling the .jar file with an icon and a wrap-per script that runs the .jar file.

1005ICT Object Oriented Programming – 2015-2 579

22.4 Debugging

The key to understanding a debugger is the breakpoint.

It does not make sense to single-step though all of the lines of a large pro-gram.

So before running the program with a debugger, we set points in the codewhere the program should be paused.

Once it has paused, the debugger allows the inspection of the variables cur-rently in scope.

1005ICT Object Oriented Programming – 2015-2 580

22.5 NetBeans demonstration

Using NetBeans:

1. Show how to create a project for the CampbellGUI program.

2. Walk through the doc commenting.

3. Run the program.

4. Generate javadoc documentation with private members shown andnot shown.

5. Package the program as a .jar file and run it.

6. Set a breakpoint and inspect the deque.

1005ICT Object Oriented Programming – 2015-2 581

22.6 Last words

22.6.1 Thanks!

Thank-you for staying to the end of this course.

I hope it has lived up to its title, Object Oriented Programming.

The concepts of classes, objects, instances, members, and all the rest, arecommon to all of the mainstream object oriented programming languages,and should be helpful for whatever programming you go on to do next.

1005ICT Object Oriented Programming – 2015-2 582

22.6.2 What to do next

• The difference between programmers that get good at programmingfaster than others is that they write more programs.

We can only set so much work during the semester.

You should start your own programming projects.

What do you want a program to do? Do something, anything, overthe Summer.

It does not have to be in Java. Programming is programming.

• Get a book on Java, and fill yourself in on some of the Java languagedetails, that have been skipped in this course.

Discover the murky world of breaks and switches, but don’t askme to debug that stuff.

1005ICT Object Oriented Programming – 2015-2 583

• Have fun with the rest of your degree!

• If you like programming, and you really want to learn a strange andwonderful way to do it, do my Honours course on functional pro-gramming.

Cheers,Rock.

1005ICT Object Oriented Programming – 2015-2 584

22.7 Section summary

This section covered:

• how to write javadoc comments;

• how to generate the docs;

• how to package a program in a .jar file; and

• how to debug with breakpoints.

1005ICT Object Oriented Programming – 2015-2 585

22.8 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 586

A Conventions Used In these Notes

This appendix explains the typographic conventions used in these lecturenotes, laboratory exercises, etc.

1005ICT Object Oriented Programming – 2015-2 587

A.1 Typefaces

Proportionally spaced, serif typeface is used for the body (English) textof these notes.

Example: Study hard.

Equally (mono-)spaced, serif typeface is used to show plain text as itwould appear in a program (in any programming language) or fortextual inputs or outputs from programs.

Example: println("Study hard.");

Sans-serif typeface is used for naming applications, menu items and otherelements in graphical user interfaces.

Example: File ▶ Save As...

1005ICT Object Oriented Programming – 2015-2 588

A.2 Program code

Program code (whole programs or snippets) is displayed in mono-spacedtypeface without any further adornment.

Example:

import console;

println("Programming should be fun!");

1005ICT Object Oriented Programming – 2015-2 589

A.3 Program code templates

Sometimes a code snippet is generalised, with some text not to be copiedliterally, but to be replaced with other text.

The text to be replaced is italicised.

Example:

initialisation statement(s)while (condition) {

body statement(s)}

1005ICT Object Oriented Programming – 2015-2 590

A.4 Console sessions

The console could be the Command Prompt in Windows, or the Terminalin Mac OS X or Linux.

To distinguish console sessions from program code, an outline is used.

Example:

$ java AdderEnter two numbers: 3 4Sum = 7$

Input, including commands, typed by the user is underlined.

1005ICT Object Oriented Programming – 2015-2 591

The command prompt (for example, C:\> on Windows) that these pro-grams display, varies from system to system, and as the current workingdirectory is changed. It is always represented by a shortened version.

For Windows-only examples, > is used.

For Mac OS X and Linux examples, ] is used.

When the example works on any system, $ is used.

As in program code templates, italics are used to show generic commandexamples, where the italicised text should be substituted for, say, a specificfile name.

1005ICT Object Oriented Programming – 2015-2 592

A.5 Section summary

This section covered:

• how code and code templates are displayed; and

• how console examples are displayed in these lecture notes.

1005ICT Object Oriented Programming – 2015-2 593

A.6 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 594

B Syntax Diagram Notation

This appendix summarises the syntax diagram notation.

1005ICT Object Oriented Programming – 2015-2 595

To describe, formally, the syntax of a programming language we will use isthe syntax or railroad diagram.

If you can appreciate that a train on a train track can not make sharp turns,then you can read these diagrams.

Start at the left. Any path you take that gets to the right end will produce asyntactically correct text.

1005ICT Object Oriented Programming – 2015-2 596

As you traverse the path, you meet text in boxes, the elements:

• Text that appears in a round-cornered (green-filled) rectangle appearsas-is (literally) in the program.

• Text that appears in a rectangle (orange-filled) represents a syntacticelement that is defined in another syntax diagram, the one with thatname at its top-left.

• Italicised text in a rectangle (yellow-filled) is an informal description.

The path can be red or black:

• A black path indicates that there can be whitespace between the ele-ments.

• A red path indicates that there can be no whitespace between the ele-ments. This is used exclusively for lexical syntax.

1005ICT Object Oriented Programming – 2015-2 597

B.1 Section summary

This section covered:

• the basic rules of syntax diagrams.

1005ICT Object Oriented Programming – 2015-2 598

B.2 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 599

C Installing the JDK

This appendix describes how to obtain and install the Java development kit(JDK) standard edition (SE), on your own computer (Windows, Mac OS X,or Linux).

1005ICT Object Oriented Programming – 2015-2 600

C.1 JDK versus JRE

You most likely already have Java installed on your computer, in the formof the Java runtime environment (JRE).

This contains all of the resources required to run Java software, but not tocompile it.

The JRE contains the Java virtual machine, java, but not the Java com-piler, javac, which is only included in the JDK.

1005ICT Object Oriented Programming – 2015-2 601

C.2 For Windows

Obtain the JDK from Oracle web site:www.oracle.com/technetwork/java/javase/downloads/

Get the latest version that appears to match your system.

If you have problems with the 64 bit version, download the 32 bit versioninstead.

The download is a self extracting installer. Just install like any application,leaving all of the settings at their defaults.

1005ICT Object Oriented Programming – 2015-2 602

C.2.1 Setting the path

The installer does everything required to use the JDK, except make javacand the other bundled tools available for use in the Command Prompt.

The Command Prompt needs to be told where the tools are.

This is done by modifying the path system environment variable so that itincludes the path to the folder that contains javac.exe.

1005ICT Object Oriented Programming – 2015-2 603

Use the Windows Explorer to locate where the JDK has been installed inthe Program Files folder.

Locate the bin folder that contains javac.exe.

Copy the full path of that folder.

Open up the system control panel.

Look for the advanced system setting, and the button, Environment Vari-ables.

That opens a dialogue box where the variables may be edited.

At the top are the user variables that you should modify, and at the bottomare system-wide variables that you should not modify.

1005ICT Object Oriented Programming – 2015-2 604

If there is no pre-existing user Path variable, create one, and set its valueto the path to the bin folder you copied.

If one already exists, edit it, and add the copied path to the end of the ex-isting value. Use a semicolon to separate the new path from the precedingone.

Close the control panels, and make a new Command Prompt window.

Type javac to confirm that it runs.

1005ICT Object Oriented Programming – 2015-2 605

C.3 For Mac OS X

The only source for an up-to-date Java is now Oracle.

Apple used to make its own port of Java to Mac OS X, but it has stoppeddoing this. This is a good thing, as the Apple version was always a bitbehind the others.

Download the latest JDK SE for Mac OS X from the same source as forWindows, and install like any other app.

That’s it.

1005ICT Object Oriented Programming – 2015-2 606

C.4 For Linux

The best source for Linux, is via the package manager for your distro.

1005ICT Object Oriented Programming – 2015-2 607

C.5 Section summary

This section covered:

• the basic rules of syntax diagrams.

1005ICT Object Oriented Programming – 2015-2 608

C.6 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 609

D UML Class Diagrams Summary

This is a summary of a subset of the conventions for the Unified ModellingLanguage (UML) class diagrams.

This is a reference, not a tutorial, so example diagrams may use elementsthat are defined later.

1005ICT Object Oriented Programming – 2015-2 610

D.1 It’s about communication

UML is a collection of design notations.

UML is for people to use to communicate with each other.

D.1.1 Efficiency

To facilitate efficient communication:

• there are agreed conventions, like how boxes are drawn to mean cer-tain things;

• the diagrams show what they need to show and omit what they don’tneed to show; and

• they are extensible and adaptable to the needs of particular groups ofusers.

1005ICT Object Oriented Programming – 2015-2 611

D.1.2 Programming language independence

UML is used by software designers who will ultimately see their designsimplemented in different object oriented languages.

So UML does not follow the syntax of any one of those languages in par-ticular.

All of the mainstream object oriented languages have similar features.

D.1.3 Illustration not definition

Diagrams by themselves are not an effective way to communicate.

Humans use natural language, but when that is not clear enough, we usepictures, diagrams or special notations (like mathematics) to supplementthe text.

A UML class diagram, by itself, does not constitute a design.1005ICT Object Oriented Programming – 2015-2 612

D.2 Class diagram elements

D.2.1 Notes

A note is a dog-eared box that containsanything that helps explain something.

An optional dotted line connects it to thething it describes.

This is a note about MyClass.

MyClass

1005ICT Object Oriented Programming – 2015-2 613

D.2.2 Classes

Obviously, the most common feature of class dia-grams is the representation of classes.

A class is most commonly drawn as a box with threesections, stacked vertically.

area() : doubledraw() : void...

Circlecentre : Pointradius : double

The top section always contains the name of the class.

The other sections are for the members (attributes and methods) of the class.

The middle section is for the attributes (also known as fields or propertiesor variables).

The bottom section is for the methods (also known as operations, functions,procedures, constructors, destructors...)

An ellipsis (...) declares that there are more members than shown in thisdiagram, but without one there could still be more.1005ICT Object Oriented Programming – 2015-2 614

The lower sections are optional.

They may be omitted because a class has no attributes, has no methods, orjust because they are irrelevant to the discussion at hand.

Pointx : doubley : double

CompactCamerapoint() : voidshoot() : void MyClass

In the cases where just one of the lower boxes is shown, there should be noconfusion between whether the members are attributes or methods, as themethods will always have formal parameter lists, or at least empty paren-theses, after their names.

1005ICT Object Oriented Programming – 2015-2 615

D.2.3 Visibility of members

The members of a class may have the following visibilities:

visibility UML symbol descriptionpublic + visible from any classprotected # visible only from subclassesprivate - not visible from any other class

Attributes are more often privateor protected than public.

Methods are more often publicthan private.

-x : double-y : double

Point

+Point(x : double, y : double)+transform(t : Transformation) : void

1005ICT Object Oriented Programming – 2015-2 616

A class can make its members visible only to its subclasses by giving themthe protected visibility.

Translation+Translation(delta_x : double, delta_y : double)

+sequence(t : Transformation) : Transformation#matrix : double[3][3]

Transformationsuperclass

subclass

1005ICT Object Oriented Programming – 2015-2 617

D.2.4 Attributes

With an attribute, the reader of a class diagram will want to know:

• its name;

• its type, which may be simple (like int) or another class;

• its visibility;

• its multiplicity; and

• perhaps other relevant properties.

1005ICT Object Oriented Programming – 2015-2 618

Inline attributes

Whether an attribute is inline or not is not a propertyof the attribute, just how the class diagram is drawn.

In this example, the centre attribute is listed (inline)in the middle box.

area() : doubledraw() : void...

Circlecentre : Pointradius : double

The names of attributes come first, followed by their type, separated bycolons.

1005ICT Object Oriented Programming – 2015-2 619

Associated attributes

An associated attribute is just another way of drawing the diagram to showtwo classes working together.

+area() : double+draw() : void

Circle-radius : double Point

-x : double-y : double

-centre

In this example, a Circle still has a private attribute of type Point, namedcentre.

Using associated attributes makes a diagram bigger and more complex, butdoes allow the reader to see inside more than one class at a time, if that iswhat is needed for the discussion at hand.

1005ICT Object Oriented Programming – 2015-2 620

Keeping in mind that when a class has an attribute whose type is a class, andthat that means there are two separate objects at run-time, then both classesmay contain references to the other.

Drawing them associated makes this clear.

-scrollBar ScrollBarWindow -container

1005ICT Object Oriented Programming – 2015-2 621

Multiplicity

We use multiplicity annotations to indicate that an attribute contains multi-ple values.

For example a polygon is defined by its many vertices, which are points,and each vertex belongs to only one polygon.

-vertex*1Polygon Point

Equivalently, inline:

-vertex : Point[*]Polygon

1005ICT Object Oriented Programming – 2015-2 622

The square brackets in the inline version imply that the vertices are storedin an array.

That may be, but equally they could be in a list or a set.

That decision can be left to the implementation in the final programminglanguage.

Some more example multiplicities:

annotation meaning1 exactly 15 exactly 5* many (0 or more)1.. 1 or more (some)1..5 1 to 5

1005ICT Object Oriented Programming – 2015-2 623

Properties

Attributes may have additional properties, enumerated in braces.

Common properties are:

property meaningreadOnly This can not be changed once it gets its default value,

a constant.ordered The multiple values must be stored as a sequence (per-

haps sorted).unique There may not be any duplicates among the multiple

values.

A better polygon:

-vertex : Point[3..] {ordered}Polygon

1005ICT Object Oriented Programming – 2015-2 624

In this example a RobotSensorPort associates a sensor port number witha Sensor.

A static constant defines how many ports there are (its default value isshown after =), and an extra property applied to portNumber declares arange of permissible values.

+PORTS : int = 4 {readOnly}-portNumber : int {1 ≤ portNumber ≤ PORTS}-sensor : Sensor

RobotSensorPort

1005ICT Object Oriented Programming – 2015-2 625

D.2.5 Methods

A method is declared by specifying, in the bottom section of a class’s box:

• its name;

• its formal parameter list

– with parentheses, enclosing

– a comma separated list of name-colon-types, or

– an ellipsis to show the parameters have been omitted;

• its return type (or void) following a colon.

Constructors have the same name as the class and the return type is omitted.

See any of the examples above or below that show methods.

1005ICT Object Oriented Programming – 2015-2 626

D.2.6 Static members

Static members are underlined.

+PORTS : int = 4 {readOnly}-portNumber : int {1 ≤ portNumber ≤ PORTS}-sensor : Sensor

RobotSensorPort

1005ICT Object Oriented Programming – 2015-2 627

D.3 Class relationships

D.3.1 Dependency

The weakest connection, dependency, between two classes is indicated bya dashed arrow.

In this example, perhaps a method in class Geometry calls a method inmethod in class Math, and so, depends upon it.

MathGeometry

1005ICT Object Oriented Programming – 2015-2 628

D.3.2 Association

Association has been described above under attributes.

In summary, association indicates that at least one class contains a referenceto instances of another.

Association is indicated by a solid line.

+area() : double+draw() : void

Circle-radius : double Point

-x : double-y : double

-centre

1005ICT Object Oriented Programming – 2015-2 629

D.3.3 Aggregation

Aggregation is a specific kind of association.

It means that one class has an association with another.

Fox Rabbitlunch

If the Fox was deleted, the Rabbit could continue to exist.

1005ICT Object Oriented Programming – 2015-2 630

D.3.4 Composition

Composition is a specific kind of association.

It means that one class owns an instance of another.

Fox Tail

If the Fox was deleted, the Tail should be deleted too.

1005ICT Object Oriented Programming – 2015-2 631

D.3.5 Inheritance

Inheritance (or its opposite, generalisation) are indicated by an arrow witha triangle head.

In Java, a class may inherit from only one class.

Translation+Translation(delta_x : double, delta_y : double)

+sequence(t : Transformation) : Transformation#matrix : double[3][3]

Transformationsuperclass

subclass

A Translation is a Transformation.

1005ICT Object Oriented Programming – 2015-2 632

D.3.6 Abstract classes

Abstract classes have methods that are declared butnot implemented.

They are drawn like regular classes, except with ital-icized names, and the unimplemented methods ital-icized.

Shape+area() : double+draw() : void

Circle

Abstract classes can not be instantiated.

The opposite of an abstract class, one that can be instantiated, is a concreteclass.

1005ICT Object Oriented Programming – 2015-2 633

D.3.7 Interfaces

Interfaces define methods likeabstract classes, but a class mayrealise (the word for inheritingfrom interfaces) more than oneinterface.

Interfaces are tagged with≪Interface≫ in the title.

The realisation arrow is dashed.

Italics aren’t needed in an inter-face as all methods are unimple-mented.

Circle

Shape

«Interface»Planar

+area() : double

«Interface»Drawable

+draw() : void

Polygon

1005ICT Object Oriented Programming – 2015-2 634

D.3.8 Parameterised classes

Parameterised classes (or templates, or generic types) are classes that willbe associated with another class, but we don’t know or care which one.

They are useful particularly for containers.

In this example, the container class Set willcontain many elements.

The element class could be any class, and isrepresented by the dummy class name E.

+add(e : E) : void+delete(e : E) : void+isIn(e : E) : boolean

-elements : E[*] {unique}Set

E

The dummy class name is drawn in a dashed box at the top-right of theparameterized class’s box.

1005ICT Object Oriented Programming – 2015-2 635

D.3.9 Container classes

When two classes have an association, not directly, but via an intermediateclass which acts only as a container, use this notation.

PhoneAccountAccountManager

TreeMap

*

1005ICT Object Oriented Programming – 2015-2 636

D.3.10 Inner classes

A class defined and declared inside another class is an inner class.

For example a class Node might be declared privately inside a list class.

NodeList

1005ICT Object Oriented Programming – 2015-2 637

D.3.11 Anonymous inner classes

A class that is created inside another class, by subclassing another class orrealising an interface, for the purpose of instantiating a single instance, istypically not given a new name.

Anything without a name is anonymous.

Indicate anonymous classes with≪anonymous≫.

«interface»Adorable

«anonymous»Adorable

1005ICT Object Oriented Programming – 2015-2 638

D.4 Section summary

This section covered:

• A summary of the conventions used to draw UML class diagrams.

1005ICT Object Oriented Programming – 2015-2 639

D.5 End of section feedback questions

Send us your answers to these questions any time you like by clicking onthem.

• What was the most useful topic in this section?

• What was the least useful topic in this section?

• What was the least clear topic in this section?

• What topic in this section would you like to like to know more about?

• Did you find an error in this section?

1005ICT Object Oriented Programming – 2015-2 640

top related