BlueJ Chapter 5 More sophisticated behavior: Library classes and documentation.

Slides:



Advertisements
Similar presentations
More Sophisticated Behaviour 1 Using library classes to implement more advanced functionality.
Advertisements

More sophisticated behaviour Using library classes to implement some more advanced functionality.
Copyright by Scott GrissomCh 5 Sophisticated Behavior Slide 1 Java Class Library a very large collection of classes for you to use as needed the challenge.
16-Jun-15 javadoc. 2 Javadoc placement javadoc comments begin with /** and end with */ In a javadoc comment, a * at the beginning of the line is not part.
More sophisticated behavior Using library classes to implement some more advanced functionality 4.0.
More Sophisticated Behaviour 2 Using library classes to implement more advanced functionality. Also … class ( static ) fields.
More sophisticated behavior Using library classes to implement some more advanced functionality 3.0.
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
More sophisticated behavior Using library classes to implement some more advanced functionality.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Java Packages and Libraries M Taimoor Khan
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Week1 Using the Library (the Java API) Classes are grouped together in packages –To use a class you have to know which package it is in –Every package.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Grouping objects Arrays, Collections and Iterators 1.0.
CIT 590 Intro to Programming First lecture on Java.
23-Oct-15 Abstract Data Types. 2 Data types A data type is characterized by: a set of values a data representation, which is common to all these values,
More sophisticated behavior Using library classes to implement some more advanced functionality 5.0.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
10-Nov-15 Java Object Oriented Programming What is it?
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 1.0.
More sophisticated behavior Using library classes to implement some more advanced functionality 5.0.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
1 COS 260 DAY 10 Tony Gauvin. 2 Agenda Questions? 4 th Mini quiz Today –Chapter 4 Assignment 2 Due Capstone Discussion Proposals Due Oct 15 No class on.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
1 COS 260 DAY 9 Tony Gauvin. 2 Agenda Questions? 3 rd Mini quiz –Good results ->All A’s –Threw out question on name overloading 4 th Mini quiz next class.
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Arrays Chapter 7.
More-Sophisticated Behavior
Using the Java Collection Libraries COMP 103 # T2
Objects First with Java CITS1001 week 4
More Sophisticated Behavior
Libraries CITS1001.
JAVA COLLECTIONS LIBRARY
JAVA COLLECTIONS LIBRARY
Java Collections Overview
More sophisticated behavior
Object Based Programming
COS 260 DAY 11 Tony Gauvin.
Object Oriented Programming
Dynamic Data Structures and Generics
Defining Classes and Methods
Objects First with Java A Practical Introduction using BlueJ
Collections and iterators
Java objects: a first view
Objects First with Java A Practical Introduction using BlueJ
Creating and Modifying Text part 3
Collections and iterators
Presentation transcript:

BlueJ Chapter 5 More sophisticated behavior: Library classes and documentation

Java constructs to be discussed in this chapter: StringArrayListRandomHashMapHashSetIterator String Tokenizer Staticfinal

1. Review Arraylist Arraylist Useful class from the Java library Useful class from the Java library store an arbitrary number of objects store an arbitrary number of objects Knowing how to use the libraries is essential to becoming an advanced Java programmer Knowing how to use the libraries is essential to becoming an advanced Java programmer Too big to memorize, thousands of classes Too big to memorize, thousands of classes Learn how to read the API Learn how to read the API HOW it’s implemented doesn’t matter HOW it’s implemented doesn’t matter ALL is well documented so others can use it ALL is well documented so others can use it

This chapter’s project A technical support system A technical support system DodgySoft software company DodgySoft software company Decided to get rid of people answering phones for tech support and replace them with an online support system. Decided to get rid of people answering phones for tech support and replace them with an online support system. The program holds a dialog with the user, responding to questions. The program holds a dialog with the user, responding to questions.

Prototype tech-support1 (the simplified version) Support System Input Reader Responder

Developing the system The prototype support system starts out very dumb. The prototype support system starts out very dumb. Always gives the same response Always gives the same response First understand how it works, then improve upon it. First understand how it works, then improve upon it.

2. Refer to the API One method used in the start method of the SupportSystem class is startsWith One method used in the start method of the SupportSystem class is startsWith Find documentation for the String class for a description of how the method works Find documentation for the String class for a description of how the method works (Appendix F of the BlueJ book tells how to set up BlueJ to access a local copy of the API to run faster, can we do this? (Appendix F of the BlueJ book tells how to set up BlueJ to access a local copy of the API to run faster, can we do this?

3. Interface vs. Implementation Interface = describes what a class does and how it can be used Interface = describes what a class does and how it can be used Please note: the word interface is also used a number of different ways in Java, like the I in GUI, or the interface type of class definition. Please note: the word interface is also used a number of different ways in Java, like the I in GUI, or the interface type of class definition. Implementation = complete source code to define a class Implementation = complete source code to define a class If an interface is well written you don’t need to see the implementation. If an interface is well written you don’t need to see the implementation.

4. String equality Remember, if Word is a String Remember, if Word is a String (Word = = “bye”) is true if the String Word and the String “bye” occupy the same memory location (Word = = “bye”) is true if the String Word and the String “bye” occupy the same memory location Word.equals(“bye”) is true if the 2 strings have the same content. Word.equals(“bye”) is true if the 2 strings have the same content.

Improving the system First improvement: First improvement: Vary the responses Vary the responses Start with random responses unrelated to user input Start with random responses unrelated to user input Create an ArrayList of possible string responses Create an ArrayList of possible string responses

5. Random numbers import java.util.random; import java.util.random; // create an instance of the Random class // create an instance of the Random class Random randGen; Random randGen; randGen = new Random(); randGen = new Random(); int index –=randGen.nextInt(); int index –=randGen.nextInt(); System.out.println(index); System.out.println(index); Note: Only create one instance of Random and store it within a class definition. Don’t create a new Random instance every time you want a new number or it won’t be very random! Note: Only create one instance of Random and store it within a class definition. Don’t create a new Random instance every time you want a new number or it won’t be very random!

Range of random numbers Random numbers generated are >= -2,147,483,648 and = -2,147,483,648 and <= 2,147,483,647 nextInt(n) generates a number from 0 (inclusive) to n (exclusive) nextInt(n) generates a number from 0 (inclusive) to n (exclusive)

Add random to Responder class Import java.util.Random Import java.util.Random Declare a field of type Random Declare a field of type Random Declare a field of type ArrayList Declare a field of type ArrayList Create the Random and ArrayList objects Create the Random and ArrayList objects Fill the ArrayList with some responses Fill the ArrayList with some responses Select and return a random phrase when generateResponse is called. Select and return a random phrase when generateResponse is called.

6. Review: ArrayLists // import the package to use // import the package to use import java.util.ArrayList; import java.util.ArrayList; // create a list // create a list ArrayList myList = new ArrayList (); ArrayList myList = new ArrayList (); // the size method returns the number of elements in the list // the size method returns the number of elements in the list int size = myList.size(); int size = myList.size(); // the get method returns an element at an index // the get method returns an element at an index // you must cast to the type of result you want // you must cast to the type of result you want String nthAnswer = myList.get(n); // no need to cast String nthAnswer = myList.get(n); // no need to cast

Which is easier to read? int index = randomGenerator.nextInt(responses.size()); int index = randomGenerator.nextInt(responses.size()); return responses.get(index); return responses.get(index); int listSize = responses.size(); int listSize = responses.size(); int index = randomGenerator.nextInt(listSize); int index = randomGenerator.nextInt(listSize); return responses.get(index); return responses.get(index);

7. importing packages we could just import java.util.*; we could just import java.util.*; better to specify which classes are used better to specify which classes are used import java.util.Random; import java.util.Random; import java.util.ArrayList: import java.util.ArrayList: all classes in java.lang are automatically imported. all classes in java.lang are automatically imported. these are the most used classes like String and System these are the most used classes like String and System

stop here You’ve finished the notes for part 1 You’ve finished the notes for part 1 Do the part 1 exercises. Do the part 1 exercises.

8. Maps A collection that stores key/value pairs. A collection that stores key/value pairs. Values can be looked up using the key. Values can be looked up using the key. Example: phonebook Example: phonebook key = name key = name value = phone number value = phone number look up a name to get a phone number look up a name to get a phone number does not use an index (position of the entry in the book) to find info, uses alphabetical order of keys does not use an index (position of the entry in the book) to find info, uses alphabetical order of keys

9. HashMap a special kind of map. a special kind of map. put inserts an entry into the map put inserts an entry into the map get retrieves a value for a given key get retrieves a value for a given key HashMap phoneBook = new HashMap(); HashMap phoneBook = new HashMap(); // add numbers to book // add numbers to book phoneBook.put(“Li Wei”, “(410) ”); phoneBook.put(“Li Wei”, “(410) ”); phoneBook.put(“Ann Day”, “(301) ”); phoneBook.put(“Ann Day”, “(301) ”); // look up a number // look up a number String s = (String) phoneBook.get(“Li Wei”); String s = (String) phoneBook.get(“Li Wei”);

Improving tech support map responses to key words map responses to key words If they say: Respond: slow Upgrading your hardware should solve performance problems bug Our software engineers are working on the problem right now. expensive Our cost is very competitive, Have you really noticed our features? Anything else Otherwise, generate a random response to start with, just use single key words

Goal for tech-support User enters complete sentences User enters complete sentences input will not be stored as a single string, but a set of strings containing each word in the question input will not be stored as a single string, but a set of strings containing each word in the question Matching responses are selected if any keywords are recognized in the question. Matching responses are selected if any keywords are recognized in the question. the set of strings (words in the question) is sent to the responder to check every word and generate a response. the set of strings (words in the question) is sent to the responder to check every word and generate a response.

10. Set a collection that stores each individual element a collection that stores each individual element no specific order no specific order no repetition of elements no repetition of elements must be able to: must be able to: add elements add elements retrieve elements retrieve elements

11. Java collections General collection type Construct used List Keeps things in order ArrayList Map Key to value connection HashMap Set Unique elements in no order HashSet

12. Iterator an object that allows you to iterate (travel) over all elements of a collection an object that allows you to iterate (travel) over all elements of a collection import java.util.Iterator; import java.util.Iterator; hasNext method returns true/false hasNext method returns true/false next method gets the next object next method gets the next object good for accessing collections that don’t have an index good for accessing collections that don’t have an index it keeps track and visits every element. it keeps track and visits every element.

example of an iterator always starts at the beginning and moves to the end always starts at the beginning and moves to the end in an ArrayList: in an ArrayList: ArrayList myList = new ArrayList(); ArrayList myList = new ArrayList(); Iterator it = myList.iterator(); Iterator it = myList.iterator(); while(it.hasNext()){ while(it.hasNext()){ System.out.println(it.next()); System.out.println(it.next()); }

13.Using sets import java.util.HashSet; import java.util.HashSet; import java.util.Iterator; import java.util.Iterator; add words from the input into the set add words from the input into the set HashSet myset = new HashSet(); HashSet myset = new HashSet(); mySet.add(word1); mySet.add(word1); mySet.add(word2); // how to get the words? mySet.add(word2); // how to get the words?

14. Tokenizing strings StringTokenizer class StringTokenizer class like an iterator like an iterator String input = readInputLine(); String input = readInputLine(); HashSet words = new HashSet(); HashSet words = new HashSet(); StringTokenizer tk = new StringTokenizer(input); StringTokenizer tk = new StringTokenizer(input); while (tk.hasMoreTokens()) while (tk.hasMoreTokens()) words.add(tk.nextToken()); words.add(tk.nextToken());

Finishing tech support When changing the input to produce a set of words instead of a single string: When changing the input to produce a set of words instead of a single string: must also adjust SupportSystem and Responder classes must also adjust SupportSystem and Responder classes the result of the getInput method is now a HashSet the result of the getInput method is now a HashSet the parameter into generateResponse is now a HashSet the parameter into generateResponse is now a HashSet if no words in the set are recognized, generate a random response. if no words in the set are recognized, generate a random response.

Documentation A serious problem in real-world projects A serious problem in real-world projects A commercial application may have hundreds of thousands of lines of code in thousands of classes A commercial application may have hundreds of thousands of lines of code in thousands of classes Nobody should have to read your actual code to understand how it works. Nobody should have to read your actual code to understand how it works. The documentation should explain everything. The documentation should explain everything.

15. javadoc in BlueJ Generate documentation function in main menu Generate documentation function in main menu Interface view option in editor shows a preview of the documentation for a single class. Interface view option in editor shows a preview of the documentation for a single class.

class documentation should include should include class name class name overall purpose overall purpose version number version number author’s name author’s name documentation for each constructor and method documentation for each constructor and method

documentation for each constructor and method should include: should include: name of method name of method return type return type parameter names and types parameter names and types description of purpose of method description of purpose of method description of each parameter description of each parameter description of value returned. description of value returned. Additionally a Read Me file is usually included in each project. Additionally a Read Me file is usually included in each project.

16. javadoc comments /** /** this is a javadoc comment this is a javadoc comment */ */ key symbols starting are recognized key symbols starting are recognized

17. Good programming practices To ensure better modularization of an application, internal detail of a class’s implementation should be hidden from other classes. This is information hiding. To ensure better modularization of an application, internal detail of a class’s implementation should be hidden from other classes. This is information hiding. If changes in one part of a program do not make it necessary to also make changes in another part of the program it is weak coupling or loose coupling. If changes in one part of a program do not make it necessary to also make changes in another part of the program it is weak coupling or loose coupling. This is good because it makes programs easier to maintain and upgrade. This is good because it makes programs easier to maintain and upgrade.

18. Public vs. private Access modifiers Access modifiers define the visibility of a field, constructor or method. define the visibility of a field, constructor or method. things marked private are within the implementation and don’t need documentation externally. (like javadoc) things marked private are within the implementation and don’t need documentation externally. (like javadoc)

stop here you’ve finished the notes for part 2 you’ve finished the notes for part 2 do the exercises before continuing to the ball project at the end of the chapter do the exercises before continuing to the ball project at the end of the chapter

Ball project Ball Demo 2 ways to produce graphical output on canvas Bouncing Ball behavior of a bouncing ball Canvas Provides a window to draw on

Altering the Ball Demo Good practice to study these concepts Good practice to study these concepts The Canvas class should not need any modification The Canvas class should not need any modification A canvas can be used by creating an instance and making it visible using the setVisible method. A canvas can be used by creating an instance and making it visible using the setVisible method.

19. Class variables and constants static variables exist one per CLASS. not one for each instance of the class. static variables exist one per CLASS. not one for each instance of the class. // in bouncingBall // in bouncingBall private static final int gravity = 3; private static final int gravity = 3; private int xPosition; private int xPosition; private int YPosition; private int YPosition; If 3 instances of Bouncing Balls are created If 3 instances of Bouncing Balls are created there will be one gravity variable there will be one gravity variable 3 xPositions and 3 yPositions 3 xPositions and 3 yPositions each ball has an individual x and y position, but all have the same gravity. each ball has an individual x and y position, but all have the same gravity.

Constants private final int size = 10; private final int size = 10; must be initialized when declared. must be initialized when declared. are usually class variables are usually class variables private static final int size = 10; private static final int size = 10;

Summary You should be able to read and write class library descriptions You should be able to read and write class library descriptions Know essential classes from the library Know essential classes from the library Use javadoc for standardized documentation Use javadoc for standardized documentation

20. Vocabulary interface interface implementation implementation map map set set javadoc javadoc access modifier access modifier information hiding information hiding coupling coupling class variable class variable static static constant constant final final