Principles of Programming CM10227 Lecture D.8.: Java: Groups of - - PowerPoint PPT Presentation

principles of programming cm10227
SMART_READER_LITE
LIVE PREVIEW

Principles of Programming CM10227 Lecture D.8.: Java: Groups of - - PowerPoint PPT Presentation

Grouping Objects Object Behaviour Principles of Programming CM10227 Lecture D.8.: Java: Groups of Objects - Object Behaviour Dr. Marina De Vos University of Bath Ext: 5053 Academic Year 2012-2013 Lecture D.8. (MDV) Programming I Academic


slide-1
SLIDE 1

Grouping Objects Object Behaviour

Principles of Programming CM10227

Lecture D.8.: Java: Groups of Objects - Object Behaviour

  • Dr. Marina De Vos

University of Bath Ext: 5053

Academic Year 2012-2013

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 1 / 110

slide-2
SLIDE 2

Grouping Objects Object Behaviour

Resources

Objects First with Java. David J. Barnes and Michael K¨

  • lling. Third edition

How to Think Like a Computer Scientist: Java. http://www.greenteapress.com/thinkapjava/ Big Java. Gay Horstman. Thinking in Java. Bruce Eckel’s www.mindview.net/Books/TIJ4 Sun Java Tutorials Series http://java.sun.com/ docs/books/tutorial/index.html

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 2 / 110

slide-3
SLIDE 3

Grouping Objects Object Behaviour

Outline

1

Grouping Objects

2

Object Behaviour

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 3 / 110

slide-4
SLIDE 4

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Main concepts to be covered

Collections Loops Iterators Arrays

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 5 / 110

slide-5
SLIDE 5

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The requirement to group objects

Many applications involve collections of objects:

Personal organizers. Library catalogs. Student-record system.

The number of items to be stored varies.

Items added. Items deleted.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 6 / 110

slide-6
SLIDE 6

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

A personal notebook

Notes may be stored. Individual notes can be viewed. There is no limit to the number of notes. It will tell how many notes are stored. Explore the notebook1 project.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 7 / 110

slide-7
SLIDE 7

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Class libraries

Collections of useful classes. We do not have to write everything from scratch. Java calls its libraries: Packages. In Python they were called Modules Grouping objects is a recurring requirement. The java. util package contains classes for doing this.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 8 / 110

slide-8
SLIDE 8

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Class Libraries

Learning to program is to learn how to reuse code written by other. There is no point in reinventing the wheel. Java comes with a library of useful classes, which are referred to as the Java API They are organized in packages that follow a directory structure

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 9 / 110

slide-9
SLIDE 9

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Class Libraries

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 10 / 110

slide-10
SLIDE 10

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Class Libraries

You can access the classes from your code, using the import statement

import java. util .Vector; import java. util .∗;

Grouping objects is a recurring requirement. The java. util package contains classes for doing this. We will use ArrayList as a first example

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 11 / 110

slide-11
SLIDE 11

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Class libraries

import java . u t i l . ArrayList ; /∗∗ ∗ . . . ∗/ public class Notebook { / / Storage f o r an a r b i t r a r y number of notes . private ArrayList<String> notes ; /∗∗ ∗ Perform any i n i t i a l i z a t i o n required f o r the ∗ notebook . ∗/ public Notebook ( ) { notes = new ArrayList<String >() ; } . . . }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 12 / 110

slide-12
SLIDE 12

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Collections

We specify:

the type of collection: ArrayList the type of objects it will contain: <String>

We say, ArrayList of String.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 13 / 110

slide-13
SLIDE 13

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Object structures with collections

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 14 / 110

slide-14
SLIDE 14

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Adding a third note

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 15 / 110

slide-15
SLIDE 15

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Features of the collection

It increases its capacity as necessary. It keeps a private count (size() accessor). It keeps the objects in order. Details of how all this is done are hidden.

Does that matter? Does not knowing how prevent us from using it?

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 16 / 110

slide-16
SLIDE 16

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Using the collection

public class Notebook { private ArrayList <String> notes ; . . . public void storeNote ( String note ) { notes . add ( note ) ; } public int numberOfNotes ( ) { return notes . size ( ) ; } . . . }

⌦ ⌃ ⇧

Adding a new note Returning the number

  • f notes (delegation)

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 17 / 110

slide-17
SLIDE 17

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Index numbering

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 18 / 110

slide-18
SLIDE 18

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Retrieving an object

public void showNote ( int noteNumber ) { i f ( noteNumber < 0) { / / This i s not a v a l i d note number . } else i f ( noteNumber < numberOfNotes ( ) ) { System . out . p r i n t l n ( notes . get ( noteNumber ) ) ; } else { / / This i s not a v a l i d note number . } }

⌦ ⌃ ⇧

Index validity check Retrieve and print the note

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 19 / 110

slide-19
SLIDE 19

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Removal may affect numbering

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 20 / 110

slide-20
SLIDE 20

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Generic classes

Collections are known as parameterized or generic types.

ArrayList implements list functionality: add, get, size, etc.

The type parameter says what we want a list of:

ArrayList<Person> ArrayList<TicketMachine>

etc.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 21 / 110

slide-21
SLIDE 21

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Review

Collections allow an arbitrary number of objects to be stored. Class libraries usually contain tried-and-tested collection classes. Javas class libraries are called packages. We have used the ArrayList class from the java. util package.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 22 / 110

slide-22
SLIDE 22

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Review

Items may be added and removed. Each item has an index. Index values may change if items are removed (or further items added). The main ArrayList methods are add, get, remove and size.

ArrayList is a parameterized or generic type.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 23 / 110

slide-23
SLIDE 23

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Iteration

We often want to perform some actions an arbitrary number of times.

E.g., print all the notes in the notebook. How many are there?

Most programming languages include loop statements to make this possible. Java has several sorts of loop statement. We will start with its for-each loop.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 24 / 110

slide-24
SLIDE 24

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Iteration fundamentals

We often want to repeat some actions over and over. Loops provide us with a way to control how many times we repeat those actions. With collections, we often want to repeat things once for every object in a particular collection.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 25 / 110

slide-25
SLIDE 25

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

For-each loop pseudo code

General form of the for-each loop

for ( ElementType element : c o l l e c t i o n ) { loop body }

⌦ ⌃ ⇧

for keyword loop header Statement(s) to be repeated Pseudo-code expression of the actions of a for-each loop For each element in collection, do the things in the loop body.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 26 / 110

slide-26
SLIDE 26

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

A Java example

/∗ ∗ ∗ L i s t a l l notes in the notebook . ∗/ public void l i s t N o t e s ( ) { for ( String note : notes ) { System . out . p r i n t l n ( note ) ; } }

⌦ ⌃ ⇧

for each note in notes, print out noted

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 27 / 110

slide-27
SLIDE 27

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The while loop

A for-each loop repeats the loop body for each object in a collection. Sometimes we require more variation than this. We can use a boolean condition to decide whether or not to keep going. A while loop provides this control.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 28 / 110

slide-28
SLIDE 28

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

While loop pseudo code

General form of a while loop

while ( loop condition ) { loop body }

⌦ ⌃ ⇧

while keyword boolean test Statement(s) to be repeated Pseudo-code expression of the actions of a while loop while we wish to continue, do the things in the loop body.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 29 / 110

slide-29
SLIDE 29

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

A Java example

/∗ ∗ ∗ L i s t a l l notes in the notebook . ∗/ public void l i s t N o t e s ( ) { int index = 0; while ( index < notes . size ( ) ) { System . out . p r i n t l n ( notes . get ( index ) ) ; index ++; } }

⌦ ⌃ ⇧

while the value of index is less than the size of the collection, print the next note, and then increment index

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 30 / 110

slide-30
SLIDE 30

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Increments

i++ : the value of i is used first before it is being incremented with one

a = 5; b = a++; a == 6; b == 5;

⌦ ⌃ ⇧

++i: increments i with one, the new value of i is then used.

a = 5; b = ++a ; a == 6; b == 6;

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 31 / 110

slide-31
SLIDE 31

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

for-each versus while

for-each:

easier to write. safer: it is guaranteed to stop.

while:

we do not have to process the whole collection. does not even have to be used with a collection. take care: could be an infinite loop.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 32 / 110

slide-32
SLIDE 32

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

While without a collection

/ / P r i n t a l l even numbers from 0 to 30. int index = 0; while ( index <= 30) { System . out . p r i n t l n ( index ) ; index = index + 2; }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 33 / 110

slide-33
SLIDE 33

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Searching a collection

int index = 0; boolean found = false ; while ( index < notes . size ( ) && ! found ) { String note = notes . get ( index ) ; i f ( note . contains ( searchString ) ) { / / We don ’ t need to keep looking . found = true ; } else { index ++; } } / / Either we found i t ,

  • r we searched the whole

/ / c o l l e c t i o n .

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 34 / 110

slide-34
SLIDE 34

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Using an Iterator object

I t e r a t o r <ElementType> i t = myCollection . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { c a l l i t . next ( ) to get the next

  • bject

do something with that

  • bject

}

⌦ ⌃ ⇧

java.util.Iterator returns an Iterator object

public void l i s t N o t e s ( ) { I t e r a t o r <String> i t = notes . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { System . out . p r i n t l n ( i t . next ( ) ) ; } }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 35 / 110

slide-35
SLIDE 35

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Iterators

An iterator is an object that provides functionality to iterate

  • ver all elements of a collection or container class
  • java. util . Iterator

two main methods: hasNext() to check if the Iterator has more elements and next() to take the next object from the Iterator. You can access an iterator for all java collections. Not all collections can be accessed using indexes.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 36 / 110

slide-36
SLIDE 36

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Index versus Iterator

Ways to iterate over a collection:

for-each loop.

Use if we want to process every element.

while loop.

Use if we might want to stop part way through. Use for repetition that doesn’t involve a collection.

Iterator object.

Use if we might want to stop part way through. Often used with collections where indexed access is not very efficient, or impossible.

Iteration is an important programming pattern.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 37 / 110

slide-37
SLIDE 37

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The auction project

The auction project provides further illustration of collections and iteration. Two further points to follow up:

The null value.

  • Casting. Used to store the result of get into a variable:

String message = ( String ) notes . get (0) ;

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 38 / 110

slide-38
SLIDE 38

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The auction project

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 39 / 110

slide-39
SLIDE 39

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The Lot Class

public void bidFor ( Person bidder , long value ) { i f ( ( highestBid == null ) || ( highestBid . getValue ( ) < value ) ) { / / This bid i s the best so f a r . setHighestBid (new Bid ( bidder , value ) ) ; } else { System . out . p r i n t l n ( ” Lot number : ” + getNumber ( ) + ” ( ” + getDescription ( ) + ” ) ” + ” already has a bid

  • f :

” + highestBid . getValue ( ) ) ; } }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 40 / 110

slide-40
SLIDE 40

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The null Keyword

highestBid == null;

The Java keyword null is used to mean no object when a variable is not currently holding a reference to a particular

  • bject.

setHighestBid(new Bid(bidder, value));

two things are done here:

we create a new object Bid we pass this new object immediately to the method

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 41 / 110

slide-41
SLIDE 41

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The Auction Class

public void showLots ( ) { I t e r a t o r i t = l o t s . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { Lot l o t = ( Lot ) i t . next ( ) ; System . out . p r i n t l n ( l o t . getNumber ( ) + ” : ” + l o t . getDescription ( ) ) ; / / Include any d e t a i l s

  • f a highest

bid . Bid highestBid = l o t . getHighestBid ( ) ; i f ( highestBid != null ) { System . out . p r i n t l n ( ” Bid : ” + highestBid . getValue ( ) ) ; } else { System . out . p r i n t l n ( ” (No bid ) ” ) ; } } }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 42 / 110

slide-42
SLIDE 42

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Type Casting I

Lot lot = (Lot) it.next();

the return value of the Iterator method next() is an object of type Object. To store this in an object of type Lot we need to explicitly convert it that type. This is called Casting This can only been done if the objects we have added to the container were originally of type Lot.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 43 / 110

slide-43
SLIDE 43

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Type Casting II

Collections in Java allow for the storage of any type of

  • bjects. In order to do so it transforms everything you add

into an object of type Object. When retrieving objects from a collection we normally cast them back into their original types.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 44 / 110

slide-44
SLIDE 44

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Wrapper Classes

Container classes in Java can only contain objects. Primitive types can therefore not be added. To solve this, Java provides wrapper classes: Integer, Float, Double

Integer a = new Integer(10); int b = a.intValue() ;

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 45 / 110

slide-45
SLIDE 45

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The auction project

The auction project provides further illustration of collections and iteration. One further point to follow up: the null value.

Used to indicate, ’no object’. We can test if an object variable holds the null variable.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 46 / 110

slide-46
SLIDE 46

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Review

Loop statements allow a block of statements to be repeated. The for−each loop allows iteration over a whole collection. The while loop allows the repetition to be controlled by a boolean expression. All collection classes provide special Iterator objects that provide sequential access to a whole collection.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 47 / 110

slide-47
SLIDE 47

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Fixed-size collections

Sometimes the maximum collection size can be pre-determined. Programming languages usually offer a special fixed-size collection type: an array. Java arrays can store objects or primitive-type values. arrays use a special syntax.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 48 / 110

slide-48
SLIDE 48

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The weblog-analyzer project

Web server records details of each access. Supports webmasters tasks.

Most popular pages. Busiest periods. How much data is being delivered. Broken references.

Analyze accesses by hour.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 49 / 110

slide-49
SLIDE 49

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Creating an array object

public class LogAnalyzer { private int [ ] hourCounts ; private LogfileReader reader ; public LogAnalyzer ( ) { hourCounts = new int [ 2 4 ] ; reader = new LogfileReader ( ) ; } . . . }

⌦ ⌃ ⇧

Array variable declaration Array object creation

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 50 / 110

slide-50
SLIDE 50

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The hourCounts array

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 51 / 110

slide-51
SLIDE 51

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Using an array

Square-bracket notation is used to access an array element: hourCounts[...] Elements are used like ordinary variables.

On the left of an assignment:

hourCounts[hour] = ...;

In an expression:

adjusted = hourCounts[hour] − 3; hourCounts[hour]++;

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 52 / 110

slide-52
SLIDE 52

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

The for loop

There are two variations of the for loop, for-each and for. The for loop is often used to iterate a fixed number of times. Often used with a variable that changes a fixed amount on each iteration.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 53 / 110

slide-53
SLIDE 53

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

For loop pseudo-code

General form of a for loop

for ( i n i t i a l i z a t i o n ; condition ; post−body action ) { statements to be repeated }

⌦ ⌃ ⇧

Equivalent in while-loop form

i n i t i a l i z a t i o n ; while ( condition ) { statements to be repeated post−body action }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 54 / 110

slide-54
SLIDE 54

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

A Java example

General form of a for loop

for ( int hour = 0; hour < hourCounts . length ; hour ++) { System . out . p r i n t l n ( hour + ” : ” + hourCounts [ hour ] ) ; }

⌦ ⌃ ⇧

Equivalent in while-loop form

int hour = 0; while ( hour < hourCounts . length ) { System . out . p r i n t l n ( hour + ” : ” + hourCounts [ hour ] ) ; hour ++; }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 55 / 110

slide-55
SLIDE 55

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

for loop with bigger step

/ / P r i n t multiples

  • f 3 that

are below 40. for ( int num = 3; num < 40; num = num + 3) { System . out . p r i n t l n (num) ; }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 56 / 110

slide-56
SLIDE 56

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Review

arrays are appropriate where a fixed-size collection is required. arrays use special syntax. For loops offer an alternative to while loops when the number of repetitions is known. For loops are used when an index variable is required.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 57 / 110

slide-57
SLIDE 57

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Coding Conventions

Iterations

Always use { , even if there is only one statement to be repeated

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 58 / 110

slide-58
SLIDE 58

Grouping Objects Object Behaviour Class Libraries Collections Iteration Fixed-size collections

Glossary

Java API packages import ArrayList Iterator Generic classes type cast

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 59 / 110

slide-59
SLIDE 59

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Main concepts to be covered

Using library classes Reading documentation Writing documentation

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 61 / 110

slide-60
SLIDE 60

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

The Java class library

Thousands of classes Tens of thousands of methods Many useful classes that make life much easier A competent Java programmer must be able to work with the libraries.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 62 / 110

slide-61
SLIDE 61

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Working with the library

You should:

know some important classes by name; know how to find out about other classes.

Remember:

We only need to know the interface, not the implementation.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 63 / 110

slide-62
SLIDE 62

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

A Technical Support System

A textual dialog system Idea based on ‘Eliza’ by Joseph Weizenbaum (MIT, 1960s) This is a system that when entering questions will try to answer them in an “intelligent” way.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 64 / 110

slide-63
SLIDE 63

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

A Technical Support System

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 65 / 110

slide-64
SLIDE 64

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

A Technical Support System Output

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 66 / 110

slide-65
SLIDE 65

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Main loop structure

/ / from the s t a r t method in SupportSystem boolean fi ni s h ed = false ; while ( ! f i n i sh e d ) { / / se n t i n e l c o n t r o l l e d loop do something i f ( e x i t condition ) { fi ni s h ed = true ; } else { do something more } }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 67 / 110

slide-66
SLIDE 66

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Main loop body

String input = reader . getInput ( ) ; . . . String response = responder . generateResponse ( ) ; System . out . p r i n t l n ( response ) ;

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 68 / 110

slide-67
SLIDE 67

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

The exit condition

String input = reader . getInput ( ) ; i f ( input . startsWith ( ” bye ” ) ) { fi ni s h ed = true ; }

⌦ ⌃ ⇧

Where does startsWith come from? What is it? What does it do? How can we find out?

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 69 / 110

slide-68
SLIDE 68

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

String Info

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 70 / 110

slide-69
SLIDE 69

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Reading class documentation

Documentation of the Java libraries in HTML format; Readable in a web browser Class API: Application Programmers Interface Interface description for all library classes http://java.sun.com/j2se/1.5.0/docs/api/

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 71 / 110

slide-70
SLIDE 70

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Interface vs implementation I

The documentation includes: the name of the class; a general description of the class; a list of constructors and methods return values and parameters for constructors and methods a description of the purpose of each constructor and method

⇒ the interface of the class

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 72 / 110

slide-71
SLIDE 71

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Interface vs implementation II

The documentation does not include private fields (most fields are private) private methods the bodies (source code) for each method

⇒ the implementation of the class

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 73 / 110

slide-72
SLIDE 72

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Interface vs implementation

The interface of a method consists of

signature

access modifier return type method name a list of parameters

comment

discussion of all signature items purpose of method

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 74 / 110

slide-73
SLIDE 73

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Using library classes

Classes from the library must be imported using an import statement (except classes from java.lang). They can then be used like classes from the current project.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 75 / 110

slide-74
SLIDE 74

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Packages and import

Classes are organised in packages. Single classes may be imported:

import java . u t i l . ArrayList ;

⌦ ⌃ ⇧

Whole packages can be imported:

import java . u t i l . ∗ ;

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 76 / 110

slide-75
SLIDE 75

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Side Note 1: Strings

Strings are immutable objects - just like in Python immutable objects cannot change content or state once they have been created

String input = reader . getInput ( ) ; input = input . trim ; i f ( input . startsWith ( ‘ ‘ bye ’ ’ ) ) { fi n i sh e d = true ; } else { Code omitted }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 77 / 110

slide-76
SLIDE 76

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Side Note 1: StringBuffer

A string buffer implements a mutable sequence of characters. A StringBsuffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 78 / 110

slide-77
SLIDE 77

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Side note 2: String equality

i f ( input == ” bye ” ) { . . . }

⌦ ⌃ ⇧

tests identity

i f ( input . equals ( ” bye ” ) ) { . . . }

⌦ ⌃ ⇧

tests equality

⇒ Strings should (almost) always be compared with .equals

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 79 / 110

slide-78
SLIDE 78

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Identity vs equality 1

Other (non-String) objects: :Person :Person “Fred“ “Jill“ person1 == person2 ?

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 80 / 110

slide-79
SLIDE 79

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Identity vs equality 2

Other (non-String) objects: :Person :Person “Fred“ “Fred“ person1 == person2 ?

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 81 / 110

slide-80
SLIDE 80

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Identity vs equality 3

Other (non-String) objects: :Person :Person “Fred“ “Fred“ person1 == person2 ?

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 82 / 110

slide-81
SLIDE 81

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Identity vs equality (Strings)

= tests identity

String input = reader . getInput ( ) ; i f ( input == ” bye ” ) { . . . }

⌦ ⌃ ⇧

== ??

:String :String “bye“ “bye“ input

⇒ (may be) false!

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 83 / 110

slide-82
SLIDE 82

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Identity vs equality (Strings)

equals tests equality (content)

String input = reader . getInput ( ) ; i f ( input . equals ( ” bye ” ) ) { . . . }

⌦ ⌃ ⇧

equals ??

:String :String “bye“ “bye“ input

⇒ true!

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 84 / 110

slide-83
SLIDE 83

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Using Random

The library class Random can be used to generate random numbers

import java . u t i l .Random; . . . Random randomGenerator = new Random ( ) ; . . . int index1 = randomGenerator . n e xtIn t ( ) ; int index2 = randomGenerator . n e xtIn t (100) ;

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 85 / 110

slide-84
SLIDE 84

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Generating random responses

public Responder ( ) { randomGenerator = new Random ( ) ; responses = new ArrayList ( ) ; fillResponses ( ) ; } public String generateResponse ( ) { int index = randomGenerator . n e xtIn t ( responses . size ( ) ) ; return ( String ) responses . get ( index ) ; } public void fillResponses ( ) . . .

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 86 / 110

slide-85
SLIDE 85

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Maps

Maps are collections that contain pairs of values. Pairs consist of a key and a value. Lookup works by supplying a key, and retrieving a value. An example: a telephone book. Just like the Python dictionary

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 87 / 110

slide-86
SLIDE 86

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Using maps

A map with Strings as keys and values :HashMap ”Charles Nguyen” ”Lisa Jones” ”William H. Smith” ”(531) 9392 4587” ”(402) 4536 4674” ”(998) 5488 0123”

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 88 / 110

slide-87
SLIDE 87

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Using maps

HashMap phoneBook = new HashMap ( ) ; phoneBook . put ( ” Charles Nguyen ” , ” (531) 9392 4587 ” ) ; phoneBook . put ( ” Lisa Jones ” , ” (402) 4536 4674 ” ) ; phoneBook . put ( ” William H. Smith ” , ” (998) 5488 0123 ” ) ; String number = ( String ) phoneBook . get ( ” Lisa Jones ” ) ; System . out . p r i n t l n ( number ) ;

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 89 / 110

slide-88
SLIDE 88

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Maps in TechSupport

public class Responder { private HashMap responseMap ; Code Omitted public String generateResponse ( String word ) { String response = ( String ) responseMap . get ( word ) ; i f ( response != null ) { return response ; } else { return pickDefaultResponse ( ) ; } }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 90 / 110

slide-89
SLIDE 89

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Using sets

import java . u t i l . HashSet ; import java . u t i l . I t e r a t o r ; . . . HashSet mySet = new HashSet ( ) ; mySet . add ( ” one ” ) ; mySet . add ( ” two ” ) ; mySet . add ( ” three ” ) ; I t e r a t o r i t = mySet . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { c a l l i t . next ( ) to get the next

  • bject

do something with that

  • bject

}

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 91 / 110

slide-90
SLIDE 90

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Sets and List

A Set is a collection that stores each individual element at most once. It does not maintain any specific order. A List is a collection that stores all elements it is been giving regardless of duplication. It maintains a order at all times.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 92 / 110

slide-91
SLIDE 91

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Writing class documentation

Your own classes should be documented the same way library classes are. Other people should be able to use your class without reading the implementation. Make your class a ’library class’!

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 93 / 110

slide-92
SLIDE 92

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Elements of documentation

Documentation for a class should include: the class name a comment describing the overall purpose and characteristics of the class a version number the authors names documentation for each constructor and each method

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 94 / 110

slide-93
SLIDE 93

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

javadoc

Class comment:

/∗ ∗ ∗ The Responder class represents a response ∗ generator

  • bject .

I t i s used to generate an ∗ automatic response . ∗ ∗ @author Michael K l l i n g and David J . Barnes ∗ @version 1.0 ( 1 . Feb.2002) ∗/

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 95 / 110

slide-94
SLIDE 94

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Elements of documentation

The documentation for each constructor and method should include: the name of the method the return type the parameter names and types a description of the purpose and function of the method a description of each parameter a description of the value returned

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 96 / 110

slide-95
SLIDE 95

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

javadoc

Method comment:

/∗ ∗ ∗ Read a l i n e

  • f

t e x t from standard input ( the t e x t ∗ terminal ) , and return i t as a set

  • f words .

∗ ∗ @param prompt A prompt to p r i n t to screen . ∗ @return A set

  • f

Strings , where each String i s ∗

  • ne of

the words typed by the user ∗/ public HashSet getInput ( String prompt ) { . . . }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 97 / 110

slide-96
SLIDE 96

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Public vs private

Public attributes (fields, constructors, methods) are accessible to other classes. Fields should not be public.

Data encapsulation

Private attributes are accessible only within the same class. Only methods that are intended for other classes should be public.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 98 / 110

slide-97
SLIDE 97

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Information hiding

Data belonging to one object is hidden from other objects. Know what an object can do, not how it does it. Information hiding increases the level of independence. Independence of modules is important for large systems and maintenance.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 99 / 110

slide-98
SLIDE 98

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

The Balls Project

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 100 / 110

slide-99
SLIDE 99

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Class and Object Level

So far we have created classes for the sake of objects which should have each a state of their own. Sometimes, objects should be able to share common properties

For People this could be the gravitational pull For Employees of the same company this could be the companys details

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 101 / 110

slide-100
SLIDE 100

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Class and Object Level

Instead of having these details stored in each object it would be better to store this at one central point:

THE CLASS

Classes themselves can also have state

class variables or static variables Exactly one copy exists of a class variable at all times, independent of the number of created instances The key word static is Javas syntax to define class variables methods at object level can access static variables

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 102 / 110

slide-101
SLIDE 101

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Class and Object Level

public class BouncingBall { private static f i n a l int g r a v i t y = 3; / / e f f e c t

  • f

g r a v i t y private int ballDegradation = 2; private Ellipse2D . Double c i r c l e ; private Color color ; private int diameter ; private int xPosition ; private int yPosition ; private f i n a l int groundPosition ; / / y p o si ti o n

  • f ground

private Canvas canvas ; private int ySpeed = 1;

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 103 / 110

slide-102
SLIDE 102

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Class variables

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 104 / 110

slide-103
SLIDE 103

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Constants

Variables can change their value by means of assignment. Sometimes, when programming you need a mechanism that can guarantee you that the value does not change at all Constants provide you a way in doing so

similar to maths or physics: pi, i, The key word final is Javas syntax to express constants Once given a value, initialized, they can change value Trying to do so will result in a syntax error.

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 105 / 110

slide-104
SLIDE 104

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Constants

private static f i n a l int g r a v i t y = 3;

⌦ ⌃ ⇧

private: access modifier, as usual static: class variable final: constant

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 106 / 110

slide-105
SLIDE 105

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Static Methods I

Previous we discussed class and object level. We introduced class variables static keyword A similar thing can be done for methods providing services for the class instead an object

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 107 / 110

slide-106
SLIDE 106

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Static Methods II

public class StaticTest { static count = 0; public StaticTest ( ) { count ++; } public static int giveCount ( ) { return count ; }

⌦ ⌃ ⇧

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 108 / 110

slide-107
SLIDE 107

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Review

Java has an extensive class library. A good programmer must be familiar with the library. The documentation tells us what we need to know to use a class (interface). The implementation is hidden (information hiding). We document our classes so that the interface can be read

  • n its own (class comment, method comments).

Classes can have variables and methods. We use the keyword static to indicate this

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 109 / 110

slide-108
SLIDE 108

Grouping Objects Object Behaviour Java API More Collections Documentation Class&Object Level

Glossary

Interface javadoc class level

  • bject level

static variables class variables constants final static

Lecture D.8. (MDV) Programming I Academic Year 2012-2013 110 / 110