Transcript Powerpoint

More sophisticated behavior
Using library classes to implement some
more advanced functionality
Main concepts to be covered
• Using library classes
• Reading documentation
• Writing documentation
11/11/2004
Lecture 5: More Sophisticated
Behavior
2
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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
3
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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
4
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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
5
A Technical Support System
11/11/2004
Lecture 5: More Sophisticated
Behavior
6
A Technical Support System
11/11/2004
Lecture 5: More Sophisticated
Behavior
7
Main loop structure
// from the start method in SupportSystem
boolean finished = false;
while(!finished) {// sentinel controlled loop
do something
if(exit condition) {
finished = true;
}
else {
do something more
}
}
11/11/2004
Lecture 5: More Sophisticated
Behavior
8
Main loop body
String input = reader.getInput();
...
String response = responder.generateResponse();
System.out.println(response);
11/11/2004
Lecture 5: More Sophisticated
Behavior
9
The exit condition
String 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?
11/11/2004
Lecture 5: More Sophisticated
Behavior
10
String Info
11/11/2004
Lecture 5: More Sophisticated
Behavior
11
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.3/docs/api/
11/11/2004
Lecture 5: More Sophisticated
Behavior
12
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 method
the interface of the class
11/11/2004
Lecture 5: More Sophisticated
Behavior
13
Interface vs implementation
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
11/11/2004
Lecture 5: More Sophisticated
Behavior
14
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
11/11/2004
Lecture 5: More Sophisticated
Behavior
15
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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
16
Packages and import
• Classes are organised in packages.
• Single classes may be imported:
import java.util.ArrayList;
• Whole packages can be imported:
import java.util.*;
11/11/2004
Lecture 5: More Sophisticated
Behavior
17
Side Note 1: Strings
• Strings are immutable objects
• immutable objects cannot change content or
state once they have been created
String input = reader.getInput();
input = input.trim;
if(input.startsWith(“bye”)){
finished = true;
}
else {
… Code omitted
}
11/11/2004
Lecture 5: More Sophisticated
Behavior
18
Side Note 1: StringBuffer
• A string buffer implements a mutable
sequence of characters. A string buffer 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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
19
Side note 2: String equality
if(input == "bye") {
...
}
tests identity
if(input.equals("bye")) {
...
}
tests equality
•
Strings should (almost) always be compared with .equals
11/11/2004
Lecture 5: More Sophisticated
Behavior
20
Identity vs equality 1
Other (non-String) objects:
:Person
:Person
“Fred”
“Jill”
person1
person2
person1 == person2 ?
11/11/2004
Lecture 5: More Sophisticated
Behavior
21
Identity vs equality 2
Other (non-String) objects:
:Person
:Person
“Fred”
“Fred”
person1
person2
person1 == person2 ?
11/11/2004
Lecture 5: More Sophisticated
Behavior
22
Identity vs equality 3
Other (non-String) objects:
:Person
:Person
“Fred”
“Fred”
person1
person2
person1 == person2 ?
11/11/2004
Lecture 5: More Sophisticated
Behavior
23
Identity vs equality (Strings)
String input = reader.getInput();
if(input == "bye") {
...
}
:String
"bye"
==
input
11/11/2004
== tests identity
:String
"bye"
?
 (may be) false!
Lecture 5: More Sophisticated
Behavior
24
Identity vs equality (Strings)
equals tests
equality
String input = reader.getInput();
if(input.equals("bye")) {
...
}
:String
"bye"
:String
equals
input
11/11/2004
"bye"
?
 true!
Lecture 5: More Sophisticated
Behavior
25
Using Random
• The library class Random can be used to
generate random numbers
import java.util.Random;
...
Random randomGenerator = new Random();
...
int index1 = randomGenerator.nextInt();
int index2 = randomGenerator.nextInt(100);
11/11/2004
Lecture 5: More Sophisticated
Behavior
26
Generating random responses
public Responder()
{
randomGenerator = new Random();
responses = new ArrayList();
fillResponses();
}
public String generateResponse()
{
int index = randomGenerator.nextInt(responses.size());
return (String) responses.get(index);
}
public void fillResponses()
...
11/11/2004
Lecture 5: More Sophisticated
Behavior
27
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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
28
Using maps
• A map with Strings as keys and values
:HashMap
11/11/2004
"Charles Nguyen"
"(531) 9392 4587"
"Lisa Jones"
"(402) 4536 4674"
"William H. Smith"
"(998) 5488 0123"
Lecture 5: More Sophisticated
Behavior
29
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.println(number);
11/11/2004
Lecture 5: More Sophisticated
Behavior
30
Maps in TechSupport
public class Responder
{
private HashMap responseMap;
… Code Omitted
public String generateResponse(String word)
{
String response = (String) responseMap.get(word);
if(response != null) {
return response;
}
else {
return pickDefaultResponse();
}
}
11/11/2004
Lecture 5: More Sophisticated
Behavior
31
Using sets
import java.util.HashSet;
import java.util.Iterator;
...
HashSet mySet = new HashSet();
mySet.add("one");
mySet.add("two");
mySet.add("three");
Compare this
to ArrayList
code!
Iterator it = mySet.iterator();
while(it.hasNext()) {
call it.next() to get the next object
do something with that object
}
11/11/2004
Lecture 5: More Sophisticated
Behavior
32
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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
33
Tokenizing Strings
public HashSet getInput()
{
System.out.print("> ");
String inputLine =
readInputLine().trim().toLowerCase();
StringTokenizer tokenizer =
new StringTokenizer(inputLine);
HashSet words = new HashSet();
while(tokenizer.hasMoreTokens()) {
words.add(tokenizer.nextToken());
}
return words;
}
11/11/2004
Lecture 5: More Sophisticated
Behavior
34
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'!
11/11/2004
Lecture 5: More Sophisticated
Behavior
35
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
11/11/2004
Lecture 5: More Sophisticated
Behavior
36
javadoc
Class 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 (1.Feb.2002)
*/
11/11/2004
Lecture 5: More Sophisticated
Behavior
37
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
11/11/2004
Lecture 5: More Sophisticated
Behavior
38
javadoc
Method 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 getInput(String prompt)
{
...
}
11/11/2004
Lecture 5: More Sophisticated
Behavior
39
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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
40
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.
11/11/2004
Lecture 5: More Sophisticated
Behavior
41
The Balls Project
11/11/2004
Lecture 5: More Sophisticated
Behavior
42
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 company’s details
11/11/2004
Lecture 5: More Sophisticated
Behavior
43
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 Java’s syntax to define class
variables
• methods at object level can access static variables
11/11/2004
Lecture 5: More Sophisticated
Behavior
44
Class and Object Level
public class BouncingBall
{
private static final int gravity = 3;
private int ballDegradation = 2;
private Ellipse2D.Double circle;
private Color color;
private int diameter;
private int xPosition;
private int yPosition;
private final int groundPosition;
private Canvas canvas;
private int ySpeed = 1;
11/11/2004
// effect of gravity
// y position of ground
Lecture 5: More Sophisticated
Behavior
45
Class variables
11/11/2004
Lecture 5: More Sophisticated
Behavior
46
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 Java’s syntax to express constants
• Once given a value, initialized, they can change value
• Trying to do so will result in a syntax error.
11/11/2004
Lecture 5: More Sophisticated
Behavior
47
Constants
private static final int gravity = 3;
• private: access modifier, as usual
• static: class variable
• final: constant
11/11/2004
Lecture 5: More Sophisticated
Behavior
48
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).
11/11/2004
Lecture 5: More Sophisticated
Behavior
49
Concepts
• Interface
• Signature
•
•
•
•
•
• javadoc
• documentation
class level
static variables
class variables
object level
constants
11/11/2004
• final
• static
Lecture 5: More Sophisticated
Behavior
50