More Sophisticated Behaviour 2 Using library classes to implement more advanced functionality. Also...
-
date post
21-Dec-2015 -
Category
Documents
-
view
214 -
download
0
Transcript of More Sophisticated Behaviour 2 Using library classes to implement more advanced functionality. Also...
More Sophisticated Behaviour 2
Using library classes to implement Using library classes to implement more advanced functionality.more advanced functionality.
Also … class (Also … class (staticstatic) fields.) fields.
class Notebook {
private ArrayList<String> notes;
public Notebook () { ArrayList<String> notes = new ArrayList<String> (); }
public void addNote (String note) { notes.add (note); }
}
What’s Wrong with This?
class Notebook {
private ArrayList<String> notes;
public Notebook () { ArrayList<String> notes = new ArrayList<String> (); }
public void addNote (String note) { notes.add (note); }
}
What’s Wrong with This?class Notebook {
private ArrayList<String> notes;
public Notebook () { ArrayList<String> notes = new ArrayList<String> (); }
public void addNote (String note) { notes.add (note); }
}
Delete !!!Delete !!!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Main Concepts to be Covered
• More library classesMore library classes– sets and maps (sets and maps (HashSetHashSet and and HashMapHashMap) )
• Information hidingInformation hiding– publicpublic versus versus privateprivate
• Class fieldsClass fields– staticstatic and and finalfinal
• Writing documentationWriting documentation
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
ArrayListArrayList<String> <String> myListmyList = new = new ArrayListArrayList<String> ();<String> ();
myListmyList.add ("one"); .add ("one"); myListmyList.add ("two"); .add ("two"); myListmyList.add ("one");.add ("one");
Iterator<String> it = Iterator<String> it = myListmyList.iterator ();.iterator ();while (it.hasNext ()) {while (it.hasNext ()) { String s = it.next (); String s = it.next (); ... do something with s... do something with s}}
Using listslists
import java.util.import java.util.ArrayListArrayList;;import java.util.Iterator;import java.util.Iterator;
Seen Seen beforebefore
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using setssets
import java.util.import java.util.HashSetHashSet;;import java.util.Iterator;import java.util.Iterator;
HashSetHashSet<String> <String> mySetmySet = new = new HashSetHashSet<String> ();<String> ();
mySetmySet.add ("one"); .add ("one"); mySetmySet.add ("two"); .add ("two"); mySetmySet.add ("one");.add ("one");
Iterator<String> it = Iterator<String> it = mySetmySet.iterator ();.iterator ();while (it.hasNext ()) {while (it.hasNext ()) { String s = it.next (); String s = it.next (); ... do something with s... do something with s}}
NewNew
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using sets sets and listslists
All varieties of All varieties of setset and and listlist are examples of are examples of collectioncollection classes. We can use classes. We can use for-eachfor-each loops and loops and IteratorsIterators on on them. Of course, we can also use them. Of course, we can also use get (index)get (index) methods methods on them as well (or instead).on them as well (or instead).
One difference is that a One difference is that a setset one holds one holds one instance one instance of of objects that are objects that are equalequal – i.e. if – i.e. if aa and and bb have both been have both been added to a added to a setset and and a.equals(b)a.equals(b), then only one of , then only one of them will be there. It is not guaranteed which one is them will be there. It is not guaranteed which one is kept. So, never search a kept. So, never search a setset using using ====..
import java.util.import java.util.HashSetHashSet;;import java.util.Iterator;import java.util.Iterator;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using sets sets and listslists
A second difference is that A second difference is that the orderthe order in which elements in which elements are kept in a are kept in a setset is not defined. For example, the order is not defined. For example, the order of elements returned by a of elements returned by a for-eachfor-each loop or loop or Iterator Iterator is is not necessarilynot necessarily the same order in which they were the same order in which they were added. added.
All varieties of All varieties of setset and and listlist are examples of are examples of collectioncollection classes. We can use classes. We can use for-eachfor-each loops and loops and IteratorsIterators on on them. Of course, we can also use them. Of course, we can also use get (index)get (index) methods methods on them as well (or instead).on them as well (or instead).
import java.util.import java.util.HashSetHashSet;;import java.util.Iterator;import java.util.Iterator;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using sets sets and listslists
Go look them up in the Java API documentation !!!
import java.util.import java.util.HashSetHashSet;;import java.util.Iterator;import java.util.Iterator;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ ProjectSeen Seen
beforebefore
InputReaderInputReader ResponderResponder
SupportSystemSupportSystem
See Chapter05, tech-support projectsSee Chapter05, tech-support projectsSee Chapter05, tech-support projectsSee Chapter05, tech-support projects
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ Main Loopboolean finished = false;boolean finished = false;
while while (!finished(!finished) {) {
String input = reader.getInput ();
if (if (input.startsWith ("bye")) {) { finished = true;finished = true; } } else { else { String response = responder.generateResponse (); System.out.println (response); } }
}}Chapter05, tech-support1, Chapter05, tech-support1, SupportSystem.start()SupportSystem.start()Chapter05, tech-support1, Chapter05, tech-support1, SupportSystem.start()SupportSystem.start()
Seen Seen beforebefore
This returns the lineThis returns the lineof text typed by the of text typed by the
customer.customer.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Go look this up Go look this up ((java.util.HashSetjava.util.HashSet))
boolean finished = false;boolean finished = false;
while while (!finished(!finished) {) {
HashSet<String> input = reader.getInput ();
if (if (input.contains ("bye")) {) { finished = true;finished = true; } } else { else { String response = responder.generateResponse (input); System.out.println (response); } }
}}
‘Eliza’ Main Loop
Chapter05, tech-support-complete, Chapter05, tech-support-complete, SupportSystem.start()SupportSystem.start()Chapter05, tech-support-complete, Chapter05, tech-support-complete, SupportSystem.start()SupportSystem.start()
NewNew
This returns the set of This returns the set of different words typed by different words typed by
the customer.the customer.
Now, “bye” can be any Now, “bye” can be any word – not just the first.word – not just the first.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ Main Loopboolean finished = false;boolean finished = false;
while while (!finished(!finished) {) {
HashSet<String> input = reader.getInput ();
if (if (input.contains ("bye")) {) { finished = true;finished = true; } } else { else { String response = responder.generateResponse (input); System.out.println (response); } }
}}Chapter05, tech-support-complete, Chapter05, tech-support-complete, SupportSystem.start()SupportSystem.start()Chapter05, tech-support-complete, Chapter05, tech-support-complete, SupportSystem.start()SupportSystem.start()
NewNew
This is the first time the This is the first time the response is dependant response is dependant
upon the enquiry!upon the enquiry!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Note: in the project code, Note: in the project code, scannerscanner is (confusingly) called is (confusingly) called reader reader ……Note: in the project code, Note: in the project code, scannerscanner is (confusingly) called is (confusingly) called reader reader ……
This is aThis is a StringString
‘Eliza’ InputReaderpublic String getInput ()public String getInput (){{
System.out.print ("> "); System.out.print ("> "); String inputLine = String inputLine = scanner.nextLine(); scanner.nextLine();
return inputLine;return inputLine; }}
Chapter05, tech-support1, Chapter05, tech-support1, InputReader.getInput()InputReader.getInput()Chapter05, tech-support1, Chapter05, tech-support1, InputReader.getInput()InputReader.getInput()
NewNew
private Scanner scanner;private Scanner scanner;private Scanner scanner;private Scanner scanner;
import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;
go look this up go look this up ((java.util.Scannerjava.util.Scanner))
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Note: in the project code, Note: in the project code, scannerscanner is (confusingly) called is (confusingly) called reader reader ……Note: in the project code, Note: in the project code, scannerscanner is (confusingly) called is (confusingly) called reader reader ……
‘Eliza’ InputReaderpublic HashSet<String> getInput ()public HashSet<String> getInput (){{
System.out.print ("> ") ; System.out.print ("> ") ; String inputLine = String inputLine = scanner.nextLine().trim().toLowerCase(); scanner.nextLine().trim().toLowerCase();
... more stuff... more stuff }}
Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()
NewNew
private Scanner scanner;private Scanner scanner;private Scanner scanner;private Scanner scanner;
import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ InputReaderpublic HashSet<String> getInput ()public HashSet<String> getInput (){{
System.out.print ("> ") ; System.out.print ("> ") ; String inputLine = String inputLine = scanner.nextLine().trim().toLowerCase(); scanner.nextLine().trim().toLowerCase();
... more stuff ... more stuff }}
NewNew
Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()
This is aThis is a StringString
private Scanner scanner;private Scanner scanner;private Scanner scanner;private Scanner scanner;
import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ InputReaderpublic HashSet<String> getInput ()public HashSet<String> getInput (){{
System.out.print ("> ") ; System.out.print ("> ") ; String inputLine = String inputLine = scanner.nextLine().trim().toLowerCase(); scanner.nextLine().trim().toLowerCase();
... more stuff ... more stuff }}
NewNew
Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()
So is this …So is this …
private Scanner scanner;private Scanner scanner;private Scanner scanner;private Scanner scanner;
import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private Scanner scanner;private Scanner scanner;private Scanner scanner;private Scanner scanner;
import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;import java.util.Scanner;
‘Eliza’ InputReaderpublic HashSet<String> getInput ()public HashSet<String> getInput (){{
System.out.print ("> ") ; System.out.print ("> ") ; String inputLine = String inputLine = scanner.nextLine().trim().toLowerCase(); scanner.nextLine().trim().toLowerCase();
... more stuff ... more stuff }}
NewNew
go look these up go look these up ((java.lang.Stringjava.lang.String))
Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()
So is this …So is this …go look this up go look this up
((java.util.Scannerjava.util.Scanner))
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
go look this up go look this up ((java.lang.Stringjava.lang.String))
public HashSet<String> getInput ()public HashSet<String> getInput (){{
System.out.print ("> "); System.out.print ("> "); String inputLine = String inputLine = scanner.nextLine().trim().toLowerCase(); scanner.nextLine().trim().toLowerCase();
String[] wordArray = inputLine.split (" ");String[] wordArray = inputLine.split (" ");
HashSet<String> wordSet = new HashSet<String> ();HashSet<String> wordSet = new HashSet<String> (); for (String word : wordArray) { for (String word : wordArray) { wordSet.add (word); wordSet.add (word); } }
return wordSet; return wordSet;
}}
‘Eliza’ InputReaderNewNew
which eliminates repeated words
which eliminates repeated words
converts the converts the array to a setarray to a set
Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Maps
• Maps are Maps are collectionscollections that contain that contain pairs of valuespairs of values..
• A pair consists of a A pair consists of a keykey and a and a valuevalue..
• Lookup works by supplying a key, Lookup works by supplying a key, and retrieving the corresponding and retrieving the corresponding value.value.
• An example: An example: a telephone booka telephone book..
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using Maps
• A map with A map with StringStringss both as both as keyskeys and and valuesvalues::
phoneBook:HashMap
"Rick Blaine" "(531) 9392 4587"
"Ilsa Lund" "(402) 4536 4674"
"Victor Laszlo" "(998) 5488 0123"
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
HashMapHashMap<String, String> <String, String> phoneBookphoneBook = = new new HashMapHashMap<String, String> ();<String, String> ();
Using Maps
phoneBookphoneBook.put ( "Rick Blaine", "(531) 9392 4587");.put ( "Rick Blaine", "(531) 9392 4587");phoneBookphoneBook.put ( "Ilsa Lund", "(402) 4536 4674");.put ( "Ilsa Lund", "(402) 4536 4674");phoneBookphoneBook.put ("Victor Laszlo", "(998) 5488 0123");.put ("Victor Laszlo", "(998) 5488 0123");
String phoneNumber = String phoneNumber = phoneBookphoneBook.get ("Rick Blaine");.get ("Rick Blaine");......System.out.println (phoneNumber);System.out.println (phoneNumber);
valuevaluekeykey
keykeyvaluevalue
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
HashMapHashMap<String, String> <String, String> phoneBookphoneBook = = new new HashMapHashMap<String, String> ();<String, String> ();
Using Maps
phoneBookphoneBook.put ( "Rick Blaine", "(531) 9392 4587");.put ( "Rick Blaine", "(531) 9392 4587");phoneBookphoneBook.put ( "Ilsa Lund", "(402) 4536 4674");.put ( "Ilsa Lund", "(402) 4536 4674");phoneBookphoneBook.put ("Victor Laszlo", "(998) 5488 0123");.put ("Victor Laszlo", "(998) 5488 0123");
String phoneNumber = String phoneNumber = phoneBookphoneBook.get ("Ricky Blaine");.get ("Ricky Blaine");......
valuevaluekeykey
Important:Important: invoking invoking getget with a with a keykey that does not exist that does not exist in the in the HashMapHashMap object returns object returns nullnull. This can be useful!. This can be useful!
keykeyvaluevalue
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
HashMapHashMap<String, String> <String, String> phoneBookphoneBook = = new new HashMapHashMap<String, String> ();<String, String> ();
Using Maps
phoneBookphoneBook.put ( "Rick Blaine", "(531) 9392 4587");.put ( "Rick Blaine", "(531) 9392 4587");phoneBookphoneBook.put ( "Ilsa Lund", "(402) 4536 4674");.put ( "Ilsa Lund", "(402) 4536 4674");phoneBookphoneBook.put ("Victor Laszlo", "(998) 5488 0123");.put ("Victor Laszlo", "(998) 5488 0123");
String phoneNumber = String phoneNumber = phoneBookphoneBook.get ("Ricky Blaine");.get ("Ricky Blaine");if (phoneNumber == null) {...}if (phoneNumber == null) {...}else {...}else {...}
valuevaluekeykey
Important:Important: invoking invoking getget with a with a keykey that does not exist that does not exist in the in the HashMapHashMap object returns object returns nullnull. This can be useful!. This can be useful!
keykeyvaluevalue
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
HashMapHashMap<String, String> <String, String> phoneBookphoneBook = = new new HashMapHashMap<String, String> ();<String, String> ();
Using Maps
phoneBookphoneBook.put ( "Rick Blaine", "(531) 9392 4587");.put ( "Rick Blaine", "(531) 9392 4587");phoneBookphoneBook.put ( "Ilsa Lund", "(402) 4536 4674");.put ( "Ilsa Lund", "(402) 4536 4674");phoneBookphoneBook.put ("Victor Laszlo", "(998) 5488 0123");.put ("Victor Laszlo", "(998) 5488 0123");
String phoneNumber = String phoneNumber = phoneBookphoneBook.get ("Ricky Blaine");.get ("Ricky Blaine");if (phoneNumber == null) {...}if (phoneNumber == null) {...}else {...}else {...}
valuevaluekeykey
"Ricky Blaine""Ricky Blaine" was not in the was not in the phoneBookphoneBook … …
"Ricky Blaine""Ricky Blaine" was in the was in the phoneBookphoneBook … …
keykeyvaluevalue
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ ProjectSeen Seen
beforebefore
InputReaderInputReader ResponderResponder
SupportSystemSupportSystem
See Chapter05, tech-support projectsSee Chapter05, tech-support projectsSee Chapter05, tech-support projectsSee Chapter05, tech-support projects
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
go look this up go look this up ((java.lang.Stringjava.lang.String))
public HashSet<String> getInput ()public HashSet<String> getInput (){{
System.out.print ("> "); System.out.print ("> "); String inputLine = String inputLine = scanner.nextLine().trim().toLowerCase(); scanner.nextLine().trim().toLowerCase();
String[] wordArray = inputLine.split (" ");String[] wordArray = inputLine.split (" ");
HashSet<String> wordSet = new HashSet<String> (); HashSet<String> wordSet = new HashSet<String> (); for (String word : wordArray) { for (String word : wordArray) { wordSet.add (word); wordSet.add (word); } }
return wordSet; return wordSet;
}}
‘Eliza’ InputReaderJust Just seenseen
which eliminates repeated words
which eliminates repeated words
convert the convert the array to a setarray to a set
Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()Chapter05, tech-support-complete, Chapter05, tech-support-complete, InputReader.getInput()InputReader.getInput()
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ ProjectSeen Seen
beforebefore
InputReaderInputReader ResponderResponder
SupportSystemSupportSystem
See Chapter05, tech-support projectsSee Chapter05, tech-support projectsSee Chapter05, tech-support projectsSee Chapter05, tech-support projects
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ Main Loopboolean finished = false;boolean finished = false;
while while (!finished(!finished) {) {
HashSet<String> input = reader.getInput ();
if (if (input.contains ("bye")) {) { finished = true;finished = true; } } else { else { String response = responder.generateResponse (input); System.out.println (response); } }
}}Chapter05, tech-support-complete, Chapter05, tech-support-complete, SupportSystem.start()SupportSystem.start()Chapter05, tech-support-complete, Chapter05, tech-support-complete, SupportSystem.start()SupportSystem.start()
Just Just seenseen
This is the first time the This is the first time the response is dependant response is dependant
upon the enquiry!upon the enquiry!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
‘Eliza’ ProjectSeen Seen
beforebefore
InputReaderInputReader ResponderResponder
SupportSystemSupportSystem
See Chapter05, tech-support projectsSee Chapter05, tech-support projectsSee Chapter05, tech-support projectsSee Chapter05, tech-support projects
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Generating Random Responses
public Responder ()public Responder (){{ randomGenerator = new Random ();randomGenerator = new Random (); responses = new ArrayList<String> ();responses = new ArrayList<String> (); fillResponses ();fillResponses ();}}
private void fillResponses ()private void fillResponses (){{ ......}}
public String generateResponse ()public String generateResponse (){{ int index =int index = randomGenerator.nextInt (responses.size ()); randomGenerator.nextInt (responses.size ()); return responses.get (index); return responses.get (index);}}
Chapter05, tech-support2, Chapter05, tech-support2, ResponderResponderChapter05, tech-support2, Chapter05, tech-support2, ResponderResponder
returns a random returns a random number in the legal number in the legal range for indexing range for indexing responsesresponses
Seen Seen beforebefore
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Generating Better Responses
public Responder ()public Responder (){{ randomGenerator = new Random ();randomGenerator = new Random (); defaultResponses = new ArrayList<String> (); defaultResponses = new ArrayList<String> (); fillDefaultResponses (); fillDefaultResponses (); responseMap = new HashMap<String, String> ();responseMap = new HashMap<String, String> (); fillResponseMap ();fillResponseMap ();}}
... private void fillDefaultResponses ()... private void fillDefaultResponses ()
... private void fillResponseMap ()... private void fillResponseMap ()
private String pickDefaultResponse ()private String pickDefaultResponse (){{ int index =int index = randomGenerator.nextInt (defaultResponses.size randomGenerator.nextInt (defaultResponses.size ());()); return responses.get (index); return responses.get (index);}}
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
NewNew
Same as Same as tech-support2tech-support2 generateResponsegenerateResponse
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
private void fillDefaultResponses ()private void fillDefaultResponses (){{ defaultResponses.add ("That sounds odd. Tell me more?");defaultResponses.add ("That sounds odd. Tell me more?"); defaultResponses.add ("No one else complained!"); defaultResponses.add ("No one else complained!"); defaultResponses.add ("Interesting. Tell me more?");defaultResponses.add ("Interesting. Tell me more?"); defaultResponses.add ("Do you have a dll conflict?");defaultResponses.add ("Do you have a dll conflict?"); defaultResponses.add ("Read the ******* manual!");defaultResponses.add ("Read the ******* manual!"); defaultResponses.add ("That's not a bug - it's a feature!");defaultResponses.add ("That's not a bug - it's a feature!"); ... etc.... etc.}}
Generating Random Responses
Same as Same as tech-support2tech-support2 fillResponsesfillResponses
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Generating Better Responses
public Responder ()public Responder (){{ randomGenerator = new Random ();randomGenerator = new Random (); defaultResponses = new ArrayList<String> (); defaultResponses = new ArrayList<String> (); fillDefaultResponses (); fillDefaultResponses (); responseMap = new HashMap<String, String> ();responseMap = new HashMap<String, String> (); fillResponseMap ();fillResponseMap ();}}
private String pickDefaultResponse ()private String pickDefaultResponse (){{ int index =int index = randomGenerator.nextInt (defaultResponses.size randomGenerator.nextInt (defaultResponses.size ());()); return responses.get (index); return responses.get (index);}}
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
Same as Same as tech-support2tech-support2 generateResponsegenerateResponse
Just Just seenseen
... private void fillDefaultResponses ()... private void fillDefaultResponses ()
... private void fillResponseMap ()... private void fillResponseMap ()
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Generating Relevant Responses
private void fillResponseMap ()private void fillResponseMap (){{ responseMap.put ("crash",responseMap.put ("crash", "Well,"Well, it never crashes here!\n" + "Tell me about your configuration?"); responseMap.put ("slow",responseMap.put ("slow", ""Upgrade your processor then!\n" + "That should solve your problems."); responseMap.put ("windows",responseMap.put ("windows", "This is a known bug"This is a known bug in Windows!\n” + "Please report it to Microsoft"); ... etc.}}
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
NewNew
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public String generateResponse (public String generateResponse (HashSet<String> words)){{ Iterator<String> it = Iterator<String> it = wordswords.iterator ();.iterator (); while (it.hasNext ()() { while (it.hasNext ()() { String String wordword = it.next (); = it.next (); String String responseresponse = = responseMap.get (word)responseMap.get (word);; if ( if (responseresponse != null) { != null) { return return responseresponse;; } } } } return return pickDefaultResponse ();pickDefaultResponse ();}}
Generating Better Responses
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
NewNew
supply the supply the keykey
If the If the keykey is in the is in the MapMap, this returns the , this returns the matching matching valuevalue – otherwise returns – otherwise returns nullnull..
If the If the keykey is in the is in the MapMap, this returns the , this returns the matching matching valuevalue – otherwise returns – otherwise returns nullnull..
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Generating Better Responses
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
Chapter05, tech-support-complete, Chapter05, tech-support-complete, ResponderResponder
Or …Or …
public String generateResponse (public String generateResponse (HashSet<String> words)){{ for (String for (String wordword : : wordswords) {) { String String responseresponse = = responseMap.get (word)responseMap.get (word);; if ( if (responseresponse != null) { != null) { return return responseresponse;; } } } } return return pickDefaultResponse ();pickDefaultResponse ();}}
supply the supply the keykey
If the If the keykey is in the is in the MapMap, this returns the , this returns the matching matching valuevalue – otherwise returns – otherwise returns nullnull..
If the If the keykey is in the is in the MapMap, this returns the , this returns the matching matching valuevalue – otherwise returns – otherwise returns nullnull..
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Revision
Make sure you Make sure you understand understand every every statementstatement on the on the
next slide …next slide …
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Revision• A A classclass is a template from which is a template from which objectsobjects can be can be
constructed.constructed.
• A A classclass defines the defines the data fieldsdata fields held by its objects, together held by its objects, together with logic for with logic for constructorsconstructors of its objects and of its objects and methodsmethods for for accessing and operating on their data. accessing and operating on their data.
• Methods (and constructors) may declare and use their own Methods (and constructors) may declare and use their own local variableslocal variables – these exist only for the duration of their – these exist only for the duration of their method (or constructor). On the other hand, method (or constructor). On the other hand, data fieldsdata fields last last for the duration of their object.for the duration of their object.
• Methods and constructors may be passed Methods and constructors may be passed parametersparameters – – these exist only for the duration of the method or these exist only for the duration of the method or constructor.constructor.
• Data fields, parameters and local variables may have Data fields, parameters and local variables may have classclass types (i.e. they are references to other objects) or types (i.e. they are references to other objects) or primitiveprimitive types (e.g. types (e.g. intint, , floatfloat, , booleanboolean, , charchar, …)., …).
• Data fields, constructors and methods may be declared Data fields, constructors and methods may be declared publicpublic or or privateprivate..
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Revision
If you don’t,If you don’t,you must find outyou must find out … … e.g. read thee.g. read the
book!book!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
• PublicPublic attributes attributes (fields, constructors, (fields, constructors, methods)methods) are accessible to other are accessible to other classes.classes.
• Fields should not (usually) be public.Fields should not (usually) be public.
• PrivatePrivate attributes are accessible only attributes are accessible only within the same class.within the same class.
• Only methods and constructors that Only methods and constructors that are intended for use by other classes are intended for use by other classes should be should be publicpublic..
Information hiding
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Information hiding• Data belonging to one object Data belonging to one object should should
be hiddenbe hidden from other objects. from other objects.
• Know Know whatwhat an object can do, not an object can do, not howhow it does it.it does it.
• Information hiding increases the level Information hiding increases the level of of independenceindependence..
• Independence of modules Independence of modules ((“low “low coupling”)coupling”) is important for building is important for building and maintaining large systems.and maintaining large systems.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Class Fields
NewNew
Chapter05, ballsChapter05, ballsChapter05, ballsChapter05, balls
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
• A A classclass defines the defines the data fieldsdata fields held by its objects, held by its objects, together with logic for together with logic for constructorsconstructors of its objects and of its objects and methodsmethods for accessing and operating on their data. for accessing and operating on their data.
• A A classclass may also define may also define class fieldsclass fields, which are shared , which are shared by all its objects.by all its objects.
• The class itself holds a single instance of each of these The class itself holds a single instance of each of these fields fields – its objects all work with the same instances– its objects all work with the same instances..
• Compare this with Compare this with data fieldsdata fields – objects all work with – objects all work with their own (different) instancestheir own (different) instances. .
• Class fieldsClass fields are declared with the keyword: are declared with the keyword: staticstatic..
• In the In the BouncingBallBouncingBall class, class, gravitygravity is a is a class fieldclass field whose common value is shared by all its instances – whose common value is shared by all its instances – the the data fieldsdata fields xPositionxPosition and and yPositionyPosition have values have values that are specific for each ball.that are specific for each ball.
Class Fields
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
A Class Constant
privateprivate staticstatic finalfinal int gravity = 3; int gravity = 3;
private private : : specifies thespecifies the visibiltyvisibilty of the declaration. of the declaration.
static static :: specifies that all specifies that all objectsobjects of this class of this class share this field – it belongs to the share this field – it belongs to the classclass..
finalfinal :: specifies that the value given cannot bespecifies that the value given cannot be changed – it is a changed – it is a constantconstant..
Note:Note: finalfinal can be applied to can be applied to anyany field (class or field (class or data), method local variable or parameter.data), method local variable or parameter.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Writing class documentation
• Your own classesYour own classes should be documented in should be documented in the same way and to the same standard as the same way and to the same standard as the the built-in library classesbuilt-in library classes..
• Other people should be able to use your Other people should be able to use your classes without reading their classes without reading their implementation.implementation.
• Make your class a library class …Make your class a library class …
• Java libraries are called Java libraries are called packagespackages … …
Investigate !!!
Investigate !!!
Investigate !!!
Investigate !!!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Elements of documentation
• Documentation for a class should include:– the class name– a description of the overall purpose and
characteristics of the class– a version number– author names– documentation explaining each
constructor and each method
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Elements of documentation
• Documentation for each constructor and method should include:– the name of the method– the return type (if any)– the parameter names and types– a description of the purpose and function
of each method– a description of each parameter– a description of the value returned (if
any)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
/**/** * The Responder class represents a response * The Responder class represents a response * generator object. It is used to generate * generator object. It is used to generate * an automatic response. * an automatic response. * * * @author Michael Kölling and David J. Barnes * @author Michael Kölling and David J. Barnes * @version 1.0 (30.Mar.2006) * @version 1.0 (30.Mar.2006) */ */class Responderclass Responder{{ ... ...}}
javadoc - Class comments
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
/**/** * Change the colour of this shape. The new colour * Change the colour of this shape. The new colour * becomes visible immediately. Legal colour strings * becomes visible immediately. Legal colour strings * are "White", "Orange", "Blonde", "Pink", "Blue" * are "White", "Orange", "Blonde", "Pink", "Blue" * and "Brown". * and "Brown". * * * @param colour The name of the new colour. * @param colour The name of the new colour. * @return true, if the colour was successfully * @return true, if the colour was successfully changed; changed; * false, if the colour name is invalid. * false, if the colour name is invalid. */ */public boolean changeColour (String colour) public boolean changeColour (String colour) {{ ... ...}}
javadoc - Method comments
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Review• Java has an extensive class library Java has an extensive class library
(packages)(packages)..
• A good programmer must know how to find A good programmer must know how to find things in the library and become familiar things in the library and become familiar with those regularly used.with those regularly used.
• The documentation tells us what we need to The documentation tells us what we need to know to use a class know to use a class (interface)(interface)..
• The implementation is hidden The implementation is hidden (information (information hiding)hiding)..
• We document our classes so that the We document our classes so that the interface can be read on its own interface can be read on its own (class (class comment, method comments)comment, method comments)..