1 cos 260 day 9 tony gauvin. 2 agenda questions? 3 rd mini quiz good results -all as threw out...
DESCRIPTION
3 Overloading Name overloading –this.name = name; Method overloading –this.name() = name(); Operator overloading – – –“3” + “4” Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael KöllingTRANSCRIPT
1
COS 260 DAY 9
Tony Gauvin
2
Agenda• Questions? • 3rd Mini quiz
– Good results ->All A’s– Threw out question on name overloading
• 4th Mini quiz next class– Chapter 4
• Assignment 2 posted – Due Oct 5 prior to class (next Monday)
• Capstone Discussion– Capstone Project Description Fall 2015.pdf
• Finish Discussion on Grouping objects • Begin Discussion on More Sophisticated Behaviors
3
Overloading• Name overloading
– this.name = name;• Method overloading
– this.name() = name();• Operator overloading
– 3 + 4 – 3.0 + 4.0 – “3” + “4”
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Grouping objects
Introduction to collections
5.0
5
Review• Collections allow an arbitrary
number of objects to be stored.• Class libraries usually contain tried-
and-tested collection classes.• Java’s class libraries are called
packages.• We have used the ArrayList class
from the java.util package.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
6
ArrayList 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.– Can store any object type
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
7
Review
• Loop statements allow a block of statements to be repeated.
• The for-each loop allows iteration over a whole collection. • for (ElementType element : collection) { do stuff }
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
8
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.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
9
The auction project• The auction project provides
further illustration of collections and iteration.
• Examples of using null.• Anonymous objects.• Chaining method calls.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
10
The auction project
11
null• Used with object types.• Used to indicate, 'no object'.• We can test if an object variable
holds the null value:
if(highestBid == null) …
• Used to indicate ‘no bid yet’.
12
Anonymous objects• Objects are often created and
handed on elsewhere immediately:Lot furtherLot = new Lot(…);lots.add(furtherLot);
• We don’t really need furtherLot:lots.add(new Lot(…));
13
Chaining method calls• Methods often return objects.• We often immediately call a
method on the returned object.Bid bid = lot.getHighestBid();Person bidder = bid.getBidder();
• We can use the anonymous object concept and chain method calls:lot.getHighestBid().getBidder()
14
Chaining method calls
String name = lot.getHighestBid().getBidder().getName();
• Each method in the chain is called on the object returned from the previous method call in the chain.
Returns a Bid object from the Lot
Returns a Person object from the Bid
Returns a String object from the Person
Grouping objects
Arrays(fixed size collection)
16
Fixed-size collections• Sometimes the maximum collection
size can be pre-determined.• A special fixed-size collection type is
available: an array.• Unlike the flexible List collections,
arrays can store object references or primitive-type values. (generic collections can only store object references)
• Arrays use a special syntax. [ ]Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
17
The weblog-analyzer project
• Web server records details of each access.
• Supports analysis tasks:– Most popular pages.– Busiest periods.– How much data is being delivered.– Broken references.
• Analyze accesses by hour.• u_ex150930.log
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
18 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
19
Creating an array object
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public class LogAnalyzer{ private int[] hourCounts; private LogfileReader reader; public LogAnalyzer() { hourCounts = new int[24]; reader = new LogfileReader(); } ...}
Array object creation
— specifies size
Array variable declaration— does not contain size
20
The hourCounts array
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
21
Using an array• Square-bracket notation is used to
access an array element: hourCounts[...]• Elements are used like ordinary
variables.• The target of an assignment:
hourCounts[hour] = ...;• In an expression:
hourCounts[hour]++;adjusted = hourCounts[hour] – 3;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
22
Standard array use
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private int[] hourCounts;private String[] names;
... hourCounts = new int[24];
...
hourcounts[i] = 0;hourcounts[i]++;System.out.println(hourcounts[i]);
declaration
creation
use
23
Array literals
• Array literals in this form can only be used in declarations.
• Related uses require new:
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private int[] numbers = { 3, 15, 4, 5 };declaration, creation and initialization
numbers = new int[] { 3, 15, 4, 5};
• The size is inferred from the data.
24
Array length
• NB: length is a field rather than a method!
• It cannot be changed – ‘fixed size’.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private int[] numbers = { 3, 15, 4, 5 };
int n = numbers.length;no brackets!
25
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.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
26
For loop pseudo-code
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
for(initialization; condition; post-body action) { statements to be repeated}
General form of the for loop
Equivalent in while-loop form
initialization;while(condition) { statements to be repeated post-body action}
27
A Java example
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
for(int hour = 0; hour < hourCounts.length; hour++) { System.out.println(hour + ": " + hourCounts[hour]);}
int hour = 0;while(hour < hourCounts.length) { System.out.println(hour + ": " + hourCounts[hour]); hour++;}
for loop version
while loop version
28
Practice• Given an array of numbers, print out all
the numbers in the array, using a for loop.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int[] numbers = { 4, 1, 22, 9, 14, 3, 9};
for ...
29
Practice• Fill an array with the Fibonacci sequence.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int[] fib = new int[100];
fib[0] = 0;fib[1] = 1;
for ...
0 1 1 2 3 5 8 13 21 34 ...
30
for loop with bigger step
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
// Print multiples of 3 that are below 40.
for(int num = 3; num < 40; num = num + 3) {
System.out.println(num);
}
31
Review• Arrays are appropriate where a
fixed-size collection is required.• Arrays use a special syntax.• For loops are used when an index
variable is required.• For loops offer an alternative to
while loops when the number of repetitions is known.
• Used with a regular step size.Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
32
Chapter Terms• Collections• Array• Iterator• For-each• For• While• index
• Import statement• Library• Package• Anonymous
object• Definite Iteration• Indefinite
Iteration
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
More sophisticated behavior
Using library classes to implement some more advanced
functionality
5.0
34
Main concepts to be covered
• Using library classes• Reading documentation
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
35
The Java class library• Thousands of classes.• Tens of thousands of methods.• Many useful classes that make life
much easier.• Library classes are often inter-
related.• Arranged into packages.• https://docs.oracle.com/javase/8/docs/api/
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
36
Working with the library• A competent Java programmer must
be able to work with the libraries.• 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.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
37
A Technical Support System
• A textual, interactive dialog system
• Idea based on ‘Eliza’ by Joseph Weizenbaum (MIT, 1960s)– http://www.masswerk.at/elizabot/
• Explore tech-support-complete …
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
38
Main loop structureboolean finished = false;
while(!finished) {
do something
if(exit condition) { finished = true; } else { do something more }}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
A common iteration pattern.
39
Main loop body
String input = reader.getInput();...String response = responder.generateResponse();System.out.println(response);
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
40
The exit conditionString input = reader.getInput();
if(input.startsWith("bye")) { finished = true;}
• Where does ‘startsWith’ come from?
• What is it? What does it do?• How can we find out?
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
41
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
42 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
43
Interface vs implementation
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 methodthe interface of the class
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
44
Interface vs implementation
The documentation does not include
• private fields (most fields are private)• private methods• the bodies (source code) of methods
the implementation of the class
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
45
Documentation for startsWith
• startsWith– public boolean startsWith(String prefix)
• Tests if this string starts with the specified prefix.
• Parameters:– prefix - the prefix.
• Returns:– true if the …; false otherwise
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
46
Methods from String• contains• endsWith• indexOf• substring• toUpperCase• trim• Beware: strings are immutable!
• Cannot be changed!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
47
Using library classes• Classes organized into packages.• Classes from the library must be
imported using an import statement (except classes from the java.lang package).
• They can then be used like classes from the current project.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
48
Fixing the Support System termination input
• Trim input <get rid of white spaces>– “bye” vs. “ bye ”
• Handle change in case– “Bye” vs “bye”
• Check for equality instead of “startsWith”
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
49
Packages and import• Single classes may be imported:import java.util.ArrayList;
• Whole packages can be imported:import java.util.*;
• Importation does not involve source code insertion.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
50
Using Random (need for games)
• The library class Random can be used to generate random numbers (look up in documentation)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
import java.util.Random;...Random rand = new Random();...int num = rand.nextInt();int value = 1 + rand.nextInt(100);int index = rand.nextInt(list.size());
random-check.zip
51
Selecting random responses for TechSupport
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public Responder(){ randomGenerator = new Random(); responses = new ArrayList<String>(); fillResponses();}
public void fillResponses(){ fill responses with a selection of response strings}
public String generateResponse(){ int index = randomGenerator.nextInt(responses.size()); return responses.get(index);}
52
Parameterized classes• The documentation includes
provision for a type parameter:– ArrayList<E>
• These type names reappear in the parameters and return types:– E get(int index)– boolean add(E e)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
53
Parameterized classes• The types in the documentation are
placeholders for the types we use in practice:– An ArrayList<TicketMachine>
actually has methods:– TicketMachine get(int index)– boolean add(TicketMachine e)– Replace “E” with the type you will
use Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
54
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 (its interface).
• Some classes are parameterized with additional types.• Parameterized classes are also known as
generic classes or generic types.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
More sophisticated behavior
Using library classes to implement some more advanced functionality
56
Main concepts to be covered
• Further library classes• Set• Map
• Writing documentation• javadoc
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
57
Using setsimport java.util.HashSet;
...HashSet<String> mySet = new HashSet<String>();
mySet.add("one");mySet.add("two");mySet.add("three");
for(String element : mySet) { do something with element}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Compare with code
for an ArrayList!
58
Tokenising Stringspublic HashSet<String> getInput() { System.out.print("> "); String inputLine = reader.nextLine().trim().toLowerCase();
String[] wordArray = inputLine.split(" "); HashSet<String> words = new HashSet<String>();
for(String word : wordArray) { words.add(word); } return words;}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
59
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.• Example: a telephone book.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
60
Using maps• A map with strings as keys and values
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
"Charles Nguyen"
:HashMap
"(531) 9392 4587""Lisa Jones" "(402) 4536 4674"
"William H. Smith" "(998) 5488 0123"
61
Using mapsHashMap <String, String> phoneBook =
new HashMap<String, String>();
phoneBook.put("Charles Nguyen", "(531) 9392 4587");phoneBook.put("Lisa Jones", "(402) 4536 4674");phoneBook.put("William H. Smith", "(998) 5488 0123");
String phoneNumber = phoneBook.get("Lisa Jones");System.out.println(phoneNumber);
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
62
List, Map and Set• Alternative ways to group objects.• Varying implementations available:
– ArrayList, LinkedList– HashSet, TreeSet
• But HashMap is unrelated to HashSet, despite similar names.
• The second word reveals organizational relatedness.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
63
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 potential 'library class'!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
64
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
65
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
66
javadocClass comment:
/** * The Responder class represents a response * generator object. It is used to generate an * automatic response. * * @author Michael Kölling and David J. Barnes * @version 1.0 (2011.07.31) */
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
67
javadocMethod comment:/** * Read a line of text from standard input (the text * terminal), and return it as a set of words. * * @param prompt A prompt to print to screen. * @return A set of Strings, where each String is * one of the words typed by the user */public HashSet<String> getInput(String prompt) { ...}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
68
Public vs private• Public elements are accessible to
objects of other classes:• Fields, constructors and methods
• Fields should not be public.• Private elements are accessible
only to objects of the same class.• Only methods that are intended
for other classes should be public.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
69
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.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
70
Code completion• The BlueJ editor supports lookup
of methods.• Use Ctrl-space after a method-
call dot to bring up a list of available methods.
• Use Return to select a highlighted method.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
71
Code completion in BlueJ
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
72
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 on its own (class comment, method comments).
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Class and constant variables
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
74
Class variables• A class variable is shared between
all instances of the class.• In fact, it belongs to the class and
exists independent of any instances.• Designated by the static keyword.• Public static variables are accessed
via the class name; e.g.:– Thermometer.boilingPoint
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
75
Class variables
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
76
Constants• A variable, once set, can have its
value fixed.• Designated by the final keyword.
– final int max = list.size();• Final fields must be set in their
declaration or the constructor.• Combing static and final is
common.Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
77
Class constants• static: class variable• final: constantprivate static final int gravity = 3;
• Public visibility is less of an issue with final fields.
• Upper-case names often used for class constants:
public static final int BOILING_POINT = 100;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling