Presentation is loading. Please wait.

Presentation is loading. Please wait.

More Sophisticated Behaviour 2 Using library classes to implement more advanced functionality. Also … class ( static ) fields.

Similar presentations


Presentation on theme: "More Sophisticated Behaviour 2 Using library classes to implement more advanced functionality. Also … class ( static ) fields."— Presentation transcript:

1 More Sophisticated Behaviour 2 Using library classes to implement more advanced functionality. Also … class ( static ) fields.

2 class Notebook { private ArrayList notes; public Notebook () { ArrayList notes = new ArrayList (); } public void addNote (String note) { notes.add (note); } } What’s Wrong with This?

3 class Notebook { private ArrayList notes; public Notebook () { ArrayList notes = new ArrayList (); } public void addNote (String note) { notes.add (note); } } What’s Wrong with This? class Notebook { private ArrayList notes; public Notebook () { ArrayList notes = new ArrayList (); } public void addNote (String note) { notes.add (note); } } Delete !!!

4 Keep going to the classes!

5 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main Concepts to be Covered More library classes More library classes – sets and maps ( HashSet and HashMap ) Information hiding Information hiding – public versus private Class fields Class fields – static and final Writing documentation Writing documentation

6 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ArrayList myList = new ArrayList (); myList.add ("one"); myList.add ("two"); myList.add ("one"); Iterator it = myList.iterator (); while (it.hasNext ()) { String s = it.next ();... do something with s } lists Using lists import java.util.ArrayList; import java.util.Iterator; Seen before

7 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling sets Using sets import java.util.HashSet; import java.util.Iterator; HashSet mySet = new HashSet (); mySet.add ("one"); mySet.add ("two"); mySet.add ("one"); Iterator it = mySet.iterator (); while (it.hasNext ()) { String s = it.next ();... do something with s } New

8 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling sets lists Using sets and lists All varieties of set and list are examples of collection classes. We can use for-each loops and Iterators on them. Of course, we can also use get (index) methods on them as well (or instead). One difference is that a set one holds one instance of objects that are equal – i.e. if a and b have both been added to a set and a.equals(b), then only one of them will be there. It is not guaranteed which one is kept. So, never search a set using ==. import java.util.HashSet; import java.util.Iterator;

9 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling sets lists Using sets and lists A second difference is that the order in which elements are kept in a set is not defined. For example, the order of elements returned by a for-each loop or Iterator is not necessarily the same order in which they were added. All varieties of set and list are examples of collection classes. We can use for-each loops and Iterators on them. Of course, we can also use get (index) methods on them as well (or instead). import java.util.HashSet; import java.util.Iterator;

10 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling sets lists Using sets and lists Go look them up in the Java API documentation !!! import java.util.HashSet; import java.util.Iterator;

11 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ Project Seen before InputReaderResponder SupportSystem See Chapter05, tech-support projects

12 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ Main Loop boolean finished = false; while (!finished) { if () { finished = true; } else { } } boolean finished = false; while (!finished) { String input = reader.getInput (); if (input.startsWith ("bye")) { finished = true; } else { String response = responder.generateResponse (); System.out.println (response); } } Chapter05, tech-support1, SupportSystem.start() Seen before This returns the line of text typed by the customer.

13 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Go look this up ( java.util.HashSet ) boolean finished = false; while (!finished) { if () { finished = true; } else { } } boolean finished = false; while (!finished) { HashSet input = reader.getInput (); if (input.contains ("bye")) { finished = true; } else { String response = responder.generateResponse (input); System.out.println (response); } } ‘Eliza’ Main Loop Chapter05, tech-support-complete, SupportSystem.start() New This returns the set of different words typed by the customer. Now, “bye” can be any word – not just the first.

14 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ Main Loop boolean finished = false; while (!finished) { if () { finished = true; } else { } } boolean finished = false; while (!finished) { HashSet input = reader.getInput (); if (input.contains ("bye")) { finished = true; } else { String response = responder.generateResponse (input); System.out.println (response); } } Chapter05, tech-support-complete, SupportSystem.start() New This is the first time the response is dependant upon the enquiry!

15 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Note: in the project code, scanner is (confusingly) called reader … This is a String ‘Eliza’ InputReader public String getInput () { System.out.print ("> "); String inputLine = scanner.nextLine(); return inputLine; } Chapter05, tech-support1, InputReader.getInput() New private Scanner scanner; import java.util.Scanner; go look this up ( java.util.Scanner )

16 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Note: in the project code, scanner is (confusingly) called reader … ‘Eliza’ InputReader public HashSet getInput () { System.out.print ("> ") ; String inputLine = scanner.nextLine().trim().toLowerCase();... more stuff } Chapter05, tech-support-complete, InputReader.getInput() New private Scanner scanner; import java.util.Scanner;

17 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ InputReader public HashSet getInput () { System.out.print ("> ") ; String inputLine = scanner.nextLine().trim().toLowerCase();... more stuff } New Chapter05, tech-support-complete, InputReader.getInput() This is a String private Scanner scanner; import java.util.Scanner;

18 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ InputReader public HashSet getInput () { System.out.print ("> ") ; String inputLine = scanner.nextLine().trim().toLowerCase();... more stuff } New Chapter05, tech-support-complete, InputReader.getInput() So is this … private Scanner scanner; import java.util.Scanner;

19 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private Scanner scanner; import java.util.Scanner; ‘Eliza’ InputReader public HashSet getInput () { System.out.print ("> ") ; String inputLine = scanner.nextLine().trim().toLowerCase();... more stuff } New go look these up ( java.lang.String ) Chapter05, tech-support-complete, InputReader.getInput() So is this … go look this up ( java.util.Scanner )

20 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling go look this up ( java.lang.String ) public HashSet getInput () { System.out.print ("> "); String inputLine = scanner.nextLine().trim().toLowerCase(); String[] wordArray = inputLine.split (" "); HashSet wordSet = new HashSet (); for (String word : wordArray) { wordSet.add (word); } return wordSet; } ‘Eliza’ InputReader New which eliminates repeated words converts the array to a set Chapter05, tech-support-complete, InputReader.getInput()

21 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Maps Maps are collections that contain pairs of values. Maps are collections that contain pairs of values. A pair consists of a key and a value. A pair consists of a key and a value. Lookup works by supplying a key, and retrieving the corresponding value. Lookup works by supplying a key, and retrieving the corresponding value. An example: a telephone book. An example: a telephone book.

22 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using Maps A map with Strings both as keys and values: A map with Strings both as keys and values: phoneBook:HashMap "Rick Blaine""(531) 9392 4587" "Ilsa Lund""(402) 4536 4674" "Victor Laszlo""(998) 5488 0123"

23 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling HashMap phoneBook = new HashMap (); Using Maps phoneBook.put ( "Rick Blaine", "(531) 9392 4587"); phoneBook.put ( "Ilsa Lund", "(402) 4536 4674"); phoneBook.put ("Victor Laszlo", "(998) 5488 0123"); String phoneNumber = phoneBook.get ("Rick Blaine");... System.out.println (phoneNumber); value key keyvalue

24 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling HashMap phoneBook = new HashMap (); Using Maps phoneBook.put ( "Rick Blaine", "(531) 9392 4587"); phoneBook.put ( "Ilsa Lund", "(402) 4536 4674"); phoneBook.put ("Victor Laszlo", "(998) 5488 0123"); String phoneNumber = phoneBook.get ("Ricky Blaine");... value key Important: invoking get with a key that does not exist in the HashMap object returns null. This can be useful! keyvalue

25 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling HashMap phoneBook = new HashMap (); Using Maps phoneBook.put ( "Rick Blaine", "(531) 9392 4587"); phoneBook.put ( "Ilsa Lund", "(402) 4536 4674"); phoneBook.put ("Victor Laszlo", "(998) 5488 0123"); String phoneNumber = phoneBook.get ("Ricky Blaine"); if (phoneNumber == null) {...} else {...} value key Important: invoking get with a key that does not exist in the HashMap object returns null. This can be useful! keyvalue

26 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling HashMap phoneBook = new HashMap (); Using Maps phoneBook.put ( "Rick Blaine", "(531) 9392 4587"); phoneBook.put ( "Ilsa Lund", "(402) 4536 4674"); phoneBook.put ("Victor Laszlo", "(998) 5488 0123"); String phoneNumber = phoneBook.get ("Ricky Blaine"); if (phoneNumber == null) {...} else {...} value key "Ricky Blaine" was not in the phoneBook … "Ricky Blaine" was in the phoneBook … keyvalue

27 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ Project Seen before InputReaderResponder SupportSystem See Chapter05, tech-support projects

28 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling go look this up ( java.lang.String ) public HashSet getInput () { System.out.print ("> "); String inputLine = scanner.nextLine().trim().toLowerCase(); String[] wordArray = inputLine.split (" "); HashSet wordSet = new HashSet (); for (String word : wordArray) { wordSet.add (word); } return wordSet; } ‘Eliza’ InputReader Just seen which eliminates repeated words convert the array to a set Chapter05, tech-support-complete, InputReader.getInput()

29 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ Project Seen before InputReaderResponder SupportSystem See Chapter05, tech-support projects

30 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ Main Loop boolean finished = false; while (!finished) { if () { finished = true; } else { } } boolean finished = false; while (!finished) { HashSet input = reader.getInput (); if (input.contains ("bye")) { finished = true; } else { String response = responder.generateResponse (input); System.out.println (response); } } Chapter05, tech-support-complete, SupportSystem.start() Just seen This is the first time the response is dependant upon the enquiry!

31 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling ‘Eliza’ Project Seen before InputReaderResponder SupportSystem See Chapter05, tech-support projects

32 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Generating Random Responses public Responder () { randomGenerator = new Random (); randomGenerator = new Random (); responses = new ArrayList (); responses = new ArrayList (); fillResponses (); fillResponses ();} private void fillResponses () {......} public String generateResponse () { int index = randomGenerator.nextInt (responses.size ()); return responses.get (index); int index = randomGenerator.nextInt (responses.size ()); return responses.get (index);} Chapter05, tech-support2, Responder returns a random number in the legal range for indexing responses Seen before

33 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Generating Better Responses public Responder () { randomGenerator = new Random (); randomGenerator = new Random (); defaultResponses = new ArrayList (); fillDefaultResponses (); responseMap = new HashMap (); defaultResponses = new ArrayList (); fillDefaultResponses (); responseMap = new HashMap (); fillResponseMap (); fillResponseMap ();}... private void fillDefaultResponses ()... private void fillResponseMap () private String pickDefaultResponse () { int index = randomGenerator.nextInt (defaultResponses.size ()); return responses.get (index); int index = randomGenerator.nextInt (defaultResponses.size ()); return responses.get (index);} Chapter05, tech-support-complete, Responder New Same as tech-support2 generateResponse

34 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Chapter05, tech-support-complete, Responder private void fillDefaultResponses () { defaultResponses.add ("That sounds odd. Tell me more?"); defaultResponses.add ("No one else complained!"); defaultResponses.add ("That sounds odd. Tell me more?"); 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 tech-support2 fillResponses

35 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Generating Better Responses public Responder () { randomGenerator = new Random (); randomGenerator = new Random (); defaultResponses = new ArrayList (); fillDefaultResponses (); responseMap = new HashMap (); defaultResponses = new ArrayList (); fillDefaultResponses (); responseMap = new HashMap (); fillResponseMap (); fillResponseMap ();} private String pickDefaultResponse () { int index = randomGenerator.nextInt (defaultResponses.size ()); return responses.get (index); int index = randomGenerator.nextInt (defaultResponses.size ()); return responses.get (index);} Chapter05, tech-support-complete, Responder Same as tech-support2 generateResponse Just seen... private void fillDefaultResponses ()... private void fillResponseMap ()

36 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Generating Relevant Responses 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, Responder New

37 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public String generateResponse () public String generateResponse (HashSet words){ Iterator it = words.iterator (); while (it.hasNext ()() { String word = it.next (); String response = responseMap.get (word); if (response != null) { return response; } } return pickDefaultResponse (); Iterator it = words.iterator (); while (it.hasNext ()() { String word = it.next (); String response = responseMap.get (word); if (response != null) { return response; } } return pickDefaultResponse ();} Generating Better Responses Chapter05, tech-support-complete, Responder New supply the key If the key is in the Map, this returns the matching value – otherwise returns null.

38 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Generating Better Responses Chapter05, tech-support-complete, Responder Or … public String generateResponse () public String generateResponse (HashSet words) { for (String word : words) { String response = responseMap.get (word); if (response != null) { return response; } } return pickDefaultResponse (); } supply the key If the key is in the Map, this returns the matching value – otherwise returns null.

39 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Revision Make sure you understand every statement on the next slide …

40 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Revision A class is a template from which objects can be constructed. A class is a template from which objects can be constructed. A class defines the data fields held by its objects, together with logic for constructors of its objects and methods for accessing and operating on their data. A class defines the data fields held by its objects, together with logic for constructors of its objects and methods for accessing and operating on their data. Methods (and constructors) may declare and use their own local variables – these exist only for the duration of their method (or constructor). On the other hand, data fields last for the duration of their object. Methods (and constructors) may declare and use their own local variables – these exist only for the duration of their method (or constructor). On the other hand, data fields last for the duration of their object. Methods and constructors may be passed parameters – these exist only for the duration of the method or constructor. Methods and constructors may be passed parameters – these exist only for the duration of the method or constructor. Data fields, parameters and local variables may have class types (i.e. they are references to other objects) or primitive types (e.g. int, float, boolean, char, …). Data fields, parameters and local variables may have class types (i.e. they are references to other objects) or primitive types (e.g. int, float, boolean, char, …). Data fields, constructors and methods may be declared public or private. Data fields, constructors and methods may be declared public or private.

41 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Revision If you don’t, you must find out … e.g. read the book!

42 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Public attributes (fields, constructors, methods) are accessible to other classes. Public attributes (fields, constructors, methods) are accessible to other classes. Fields should not (usually) be public. Fields should not (usually) be public. Private attributes are accessible only within the same class. Private attributes are accessible only within the same class. Only methods and constructors that are intended for use by other classes should be public. Only methods and constructors that are intended for use by other classes should be public. Information hiding

43 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Information hiding Data belonging to one object should be hidden from other objects. Data belonging to one object should be hidden from other objects. Know what an object can do, not how it does it. Know what an object can do, not how it does it. Information hiding increases the level of independence. Information hiding increases the level of independence. Independence of modules (“low coupling”) is important for building and maintaining large systems. Independence of modules (“low coupling”) is important for building and maintaining large systems.

44 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Class Fields New Chapter05, balls

45 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling A class defines the data fields held by its objects, together with logic for constructors of its objects and methods for accessing and operating on their data. A class defines the data fields held by its objects, together with logic for constructors of its objects and methods for accessing and operating on their data. A class may also define class fields, which are shared by all its objects. A class may also define class fields, which are shared by all its objects. The class itself holds a single instance of each of these fields – its objects all work with the same instances. The class itself holds a single instance of each of these fields – its objects all work with the same instances. Compare this with data fields – objects all work with their own (different) instances. Compare this with data fields – objects all work with their own (different) instances. Class fields are declared with the keyword: static. Class fields are declared with the keyword: static. In the BouncingBall class, gravity is a class field whose common value is shared by all its instances – the data fields xPosition and yPosition have values that are specific for each ball. In the BouncingBall class, gravity is a class field whose common value is shared by all its instances – the data fields xPosition and yPosition have values that are specific for each ball. Class Fields

46 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling A Class Constant private static final int gravity = 3; private : specifies the visibilty of the declaration. static : specifies that all objects of this class share this field – it belongs to the class. final : specifies that the value given cannot be changed – it is a constant. Note: final can be applied to any field (class or data), method local variable or parameter.

47 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Writing class documentation Your own classes should be documented in the same way and to the same standard as the built- in library classes. Your own classes should be documented in the same way and to the same standard as the built- in library classes. Other people should be able to use your classes without reading their implementation. Other people should be able to use your classes without reading their implementation. Make your class a library class … Make your class a library class … Java libraries are called packages … Java libraries are called packages … Investigate !!!

48 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

49 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)

50 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling /** * 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 (30.Mar.2006) */ class Responder {... } javadoc - Class comments

51 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling /** * Change the colour of this shape. The new colour * becomes visible immediately. Legal colour strings * are "White", "Orange", "Blonde", "Pink", "Blue" * and "Brown". * * @param colour The name of the new colour. * @return true, if the colour was successfully changed; * false, if the colour name is invalid. */ public boolean changeColour (String colour) {... } javadoc - Method comments

52 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review Java has an extensive class library (packages). Java has an extensive class library (packages). A good programmer must know how to find things in the library and become familiar with those regularly used. A good programmer must know how to find things in the library and become familiar with those regularly used. The documentation tells us what we need to know to use a class (interface). The documentation tells us what we need to know to use a class (interface). The implementation is hidden (information hiding). The implementation is hidden (information hiding). We document our classes so that the interface can be read on its own (class comment, method comments). We document our classes so that the interface can be read on its own (class comment, method comments).


Download ppt "More Sophisticated Behaviour 2 Using library classes to implement more advanced functionality. Also … class ( static ) fields."

Similar presentations


Ads by Google