Presentation is loading. Please wait.

Presentation is loading. Please wait.

More-Sophisticated Behavior

Similar presentations


Presentation on theme: "More-Sophisticated Behavior"— Presentation transcript:

1 More-Sophisticated Behavior
Objects First with Java More-Sophisticated Behavior Using library classes to implement some more advanced functionality 6.0 © David J. Barnes and Michael Kölling

2 Main concepts to be covered
Objects First with Java Main concepts to be covered Using library classes Reading documentation © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

3 Objects First with Java
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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

4 Working with the library
Objects First with Java 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

5 A Technical Support System
Objects First with Java A Technical Support System A textual, interactive dialog system. Idea based on ‘Eliza’ by Joseph Weizenbaum (MIT, 1960s). Explore tech-support-complete … … The program appears to respond intelligently to the user’s typed input. Explore tech-support1 – an incomplete version. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

6 Objects First with Java
Main loop structure boolean finished = false; while(!finished) { do something if(exit condition) { finished = true; } else { do something more A common iteration pattern. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

7 Modularization © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

8 Main loop body in SupportSystem
Objects First with Java Main loop body in SupportSystem String input = reader.getInput(); ... String response = responder.generateResponse(); System.out.println(response); NB: input is ignored by the Responder in this version © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

9 Objects First with Java
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? © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

10 Reading class documentation
Objects First with Java 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

11 API Reference © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

12 Interface vs implementation
Objects First with Java 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

13 Interface vs implementation
Objects First with Java 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

14 Documentation for 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

15 Methods from String contains endsWith indexOf substring toUpperCase
trim Beware: strings are immutable! © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

16 Objects First with Java
Using library classes Classes organized into packages. Classes from the library must be imported using an import statement; except from the java.lang package. They can then be used like classes from the current project. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

17 Objects First with Java
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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

18 Adding random behavior
Objects First with Java Adding random behavior The library class Random can be used to generate random numbers: import java.util.Random; ... Random rand = new Random(); int num = rand.nextInt(); int value = 1 + rand.nextInt(100); int index = rand.nextInt(list.size()); The code fragment creates a new instance of the Random class and stores it in the randomGenerator variable. It then calls the nextInt method to receive a random number and stores it in the index variable. If the nextInt() method called (with no arguments), it will generate a number in the range of to If the nextInt(int n) method is called (with an argument), it generates a number from 0 (inclusive) to n (exclusive) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

19 Using Random If the nextInt() method is called (with no arguments), it will generate a number in the range of -2,147,483,648 to 2,147,483,647 If the nextInt(int n) method is called (with an argument), it generates a number from 0 (inclusive) to n (exclusive) To use Random, import the Random class: import java.util.Random; Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

20 Selecting random responses
Objects First with Java Selecting random responses public Responder() { randomGenerator = new Random(); responses = new ArrayList<>(); 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); This version of the tech support system includes an ArrayList response that is filled with additional responses by calling the fillResponses method and then generates a random response to questions with a generateResponse method. The first line of code in the generateResponse method does three things: It gets the size of the response list by calling its size method. It generates a random number between 0 (inclusive) and the size (exclusive). It stores that random number in the local variable index. The second line of code in the generateResponse method does two things: It retrieves the response at position index using the get method It returns the selected string as the method result, using the return statement. Show tech-support2 and talk about it’s limitations. We now have a solution to our tech support system that generates random responses. This is better than the first version, but still not very convincing. In particular, the input of the user does not influence the response in any way. This is what needs to be improved. The plan is that we shall have a set of words that are likely to occur in typical questions and we will associate these words with particular responses. If the input from the user contains one of our known words, we can generate a related response. To do this we will use a HashMap. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

21 Parameterized classes
Objects First with Java Parameterized classes The documentation includes provision for a type parameter: ArrayList<E> These type names reappear in the parameters and return types of the methods of the class: E get(int index) boolean add(E e) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

22 Parameterized classes
The types in the documentation are placeholders for the types we use in practice: An ArrayList<Track> actually has methods: Track get(int index) boolean add(Track e) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

23 Objects First with Java
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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

24 Further library classes
Objects First with Java Further library classes Using library classes to implement some more advanced functionality © David J. Barnes and Michael Kölling

25 Main concepts to be covered
Objects First with Java Main concepts to be covered Further library classes: Set – avoiding duplicates Map – creating associations Writing documentation: javadoc © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

26 Objects First with Java
Using sets import java.util.HashSet; ... HashSet<String> mySet = new HashSet<>(); mySet.add("one"); mySet.add("two"); mySet.add("three"); for(String element : mySet) { do something with element } Compare with code for an ArrayList! © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

27 Objects First with Java
Tokenising Strings public 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; This example show how to split an input line into an array of Strings using the split method of the String class. The inputLine string will be split on spaces. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

28 Objects First with Java
Maps Maps are collections that contain pairs of objects. Parameterized with two types. Pairs consist of a key and a value. Lookup works by supplying a key, and retrieving a value. Example: a contacts list. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

29 Objects First with Java
Using maps A map with strings as keys and values :HashMap "Charles Nguyen" "(531) " "Lisa Jones" "(402) " "William H. Smith" "(998) " © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

30 Objects First with Java
Using maps HashMap <String, String> contacts = new HashMap<>(); contacts.put("Charles Nguyen", "(531) "); contacts.put("Lisa Jones", "(402) "); contacts.put("William H. Smith", "(998) "); String number = contacts.get("Lisa Jones"); System.out.println(number); HashMap is a particular implementation of Map. The most important methods of the HashMap class are put and get. The put method inserts an entry into the map, and get retrieves the value for a given key. The code fragment creates a HashMap and inserts three entries into it. Each entry is a key/value pair consisting of a name and a telephone number. Note that you pass the key (the name “Lisa Jones”) to the get method in order to receive the value (the phone number). We can apply this idea to our tech support system. Show fillResponses method from tech support complete. We can now associate the responses with a word. We still have the problem of recognizing the key words in the sentence that was entered by the user. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

31 HashMap in Responder private HashMap <String, String> responseMap; ... responseMap.put("crash", "Which version is this?"); String response = responseMap.get(word); if(response != null) { } © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

32 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

33 Collections and primitive types
Objects First with Java Collections and primitive types The generic collection classes can be used with all class types ... … but what about the primitive types: int, boolean, etc.? Suppose we want an ArrayList of int? © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

34 Objects First with Java
Wrapper classes Primitive types are not objects types. Primitive-type values must be wrapped in objects to be stored in a collection! Wrapper classes exist for all primitive types: simple type wrapper class int Integer float Float char Character Note that there is no simple mapping rule from primitive name to wrapper name! © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

35 Objects First with Java
Wrapper classes wrap the value int i = 18; Integer iwrap = new Integer(i); int value = iwrap.intValue(); unwrap it In practice, autoboxing and unboxing mean we don't often have to do this explicitly © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

36 Autoboxing and unboxing
Objects First with Java Autoboxing and unboxing private ArrayList<Integer> markList; ... public void storeMark(int mark) { markList.add(mark); } autoboxing int firstMark = markList.remove(0); unboxing © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

37 Writing class documentation
Objects First with Java 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'! © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

38 Elements of documentation
Objects First with Java 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

39 Elements of documentation
Objects First with Java 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

40 Objects First with Java
javadoc Class comment: /** * The Responder class represents a response * generator object. It is used to generate an * automatic response. * Michael Kölling and David J. Barnes ( ) */ © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

41 Objects First with Java
javadoc Method comment: /** * Read a line of text from standard input (the text * terminal), and return it as a set of words. * prompt A prompt to print to screen. A set of strings, where each String is * one of the words typed by the user */ public HashSet<String> getInput(String prompt) { ... } © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

42 Objects First with Java
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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

43 Objects First with Java
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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

44 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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

45 Code completion in BlueJ
© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

46 Objects First with Java
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). © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

47 Class variables and constants

48 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

49 Objects First with Java
Class variables © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

50 Constants A variable, once set, can have its value fixed.
Designated by the final keyword. final int SIZE = 10; Final fields must be set in their declaration or the constructor. Combing static and final is common. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

51 Objects First with Java
Class constants static: class variable final: constant private 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; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

52 Class methods A static method belongs to its class rather than the instances: public static int getDaysThisMonth() Static methods are invoked via their class name: int days = Calendar.getDaysThisMonth(); © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

53 Limitations of class methods
A static method exists independent of any instances. Therefore: They cannot access instance fields within their class. They cannot call instance methods within their class. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

54 Review Class variables belong to their class rather than its instances. Class methods belong to their class rather than its instances. Class variables are used to share data among instances. Class methods are prohibited from accessing instance variables and methods. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

55 Review The values of final variables are fixed.
They must be assigned at declaration or in the constructor (for fields). final and static are unrelated concepts, but they are often used together. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

56 Further Advanced Material
© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

57 Polymorphic collection types
Different collection classes offer similar interfaces; e.g.: ArrayList and LinkedList HashSet and TreeSet Types exist which capture those similarities: List Set © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

58 Polymorphic collection types
Polymorphism allows us to ignore the more specific type in most cases. We create objects of the specific type, but ... … declare variables of the more general type: List<Track> tracks = new LinkedList<>(); Map<String, String> responseMap = new HashMap<>(); © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

59 The Stream collect method
Used to create a new collection object at the end of a pipeline. The collect method takes a Collector parameter that accumulates elements of the stream. We often use the polymorphic collection types for the result. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

60 Collecting a filtered stream
public List<Sighting> getSightingsOf(String animal) { return sightings .stream() .filter(record -> animal.equals( record.getAnimal())) .collect(Collectors.toList()); } java.util.stream.Collectors static toList method returns a Collector object © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


Download ppt "More-Sophisticated Behavior"

Similar presentations


Ads by Google