1 / 67

Chapter Outline

Chapter Outline. 3.1 A First Worker Class: Class FoodItem 3.2 A Worker Class that Processes String Objects Case Study: Finding the Words in a Sentence 3.3 A Worker Class that Processes Integers Case Study: Designing a Coin Changer Machine 3.4 Review of Method Categories

krysta
Download Presentation

Chapter Outline

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter Outline • 3.1 A First Worker Class: Class FoodItem • 3.2 A Worker Class that Processes String Objects • Case Study: Finding the Words in a Sentence • 3.3 A Worker Class that Processes Integers • Case Study: Designing a Coin Changer Machine • 3.4 Review of Method Categories • 3.5 Simplifying a Solution Using Multiple Classes • Case Study: Computing the Weight of Flat Washers • 3.6 Formatting Output and Class KeyIn (Optional) • 3.7 Applets, AWT, and the Graphics Class (Optional)

  2. 3.1 Review of Class Definitions • The data fields of a class (also called instance variables) store the information associated with an object of that class. The data fields may be referenced throughout the class. The values stored in an object's data fields represent the state of that object. • The methods specify the operations that objects of the class can peform. • 1. Class header • 2. Class body • 2.1 The data field declarations for the class • 2.2 The method definitions of the class We design worker classes or support classes that support the application class or client class.

  3. Data field declarations in FoodItem • These data field declarations resemble variable declarations except they begin with the visibility modifierprivate. • A privatedata field can be accessed directly in the class in which it is defined, but not outside the class. • Other classes can manipulate data field price, for example, only through the methods of class FoodItem. public class FoodItem { // data fields private String description; private double size; private double price;

  4. Sytnax for Data field Declaration • Form: [visibility] typeName datafieldName = [value]; Example: private int pennies; private String month; • Interpretation: The data type of datafieldName is specified as typeName where typeName is a predefined Java type or a class that has been defined by Java programmers. If value is present, it must be a literal of data type typeName. The visibility may be specified as private (accessible only within the class), public (accessible anywhere), or protected (accessible only within the class and by subclasses of the class). If omitted, it has default visibility which means it can be accessed by any class in the same folder as the current class.

  5. Method Definitions public static void main(String[] args) { System.out.println("Hello world"); System.out.println("Java is fun"); } • Method definitions have the form • method header { • method body • } parameters header body

  6. Method Header • The method header gives the method name, the data type of the value returned by the method (if any), and its parameters in parentheses. Form: visibility [static] resultTypemethodName([parameterList]) Examples: public static void main(String[] args) public double getPrice() public void setPrice(double aPrice) • Interpretation: The type of result returned is resultType where void means the method does not return a result. The method parametersappear in the parameterList. This list contains individual data declarations (data type, identifier pairs) separated by commas. Empty parentheses () indicate that a method has no parameters.

  7. Method header, cont’d. • The method definition specifies visibility with modifier keywords (for example, public, private) that precede the resultType. The visibility specifies whether the method may be called from outside the class (public visibility) or just within the class (private visibility). Most methods we write have public visibility. • The keyword static indicates that a method is a class method, not an instance method. Most methods we write are instance methods.

  8. Methods for Class FoodItem • For most classes, we need to provide methods that perform tasks similar to the ones below. • a method to create a new FoodItem object with a specified description, size, and price (constructor) • methods to change the description, size, or price of an existing FoodItem object (mutators) • methods that return the description, size, or price of an existing FoodItem object (accessors) • a method that returns the object state as a string (a toString() method).

  9. Method public FoodItem(String, double, double) public void setDesc(String) public void setSize(double) Description Constructor - creates a new object whose three data fields have the values specified by its three arguments. Mutator - sets the value of data field description to the value indicated by its argument. Returns no value. Mutator - sets the value of data field size to the value indicated by its argument. Returns no value. Method Headers for Class FoodItem

  10. Method public void setPrice(double) public String getDesc() public double getSize() Description Mutator - sets the value of data field price to the value indicated by its argument. Returns no value. Accessor - returns a reference to the string referenced by data field description. Accessor - returns the value of data field size. Method Headers for Class FoodItem, cont’d.

  11. Method public double getPrice() public String toString() public double calcUnitPrice() Description Accessor - returns the value of data field price. Returns a string representing the state of this object. Returns the unit price (price / size) of this item. Method Headers for Class FoodItem, cont’d.

  12. Class FoodItem /* * FoodItem.java Author: Koffman and Wolz * Represents a food item at a market */ public class FoodItem { // data fields private String description; private double size; private double price;

  13. Class FoodItem, cont’d. // methods // postcondition: creates a new object with data // field values as specified by the arguments public FoodItem(String desc, double aSize, double aPrice) { description = desc; size = aSize; price = aPrice; } // postcondition: sets description to argument // value public void setDesc(String desc) { description = desc; }

  14. Class FoodItem, cont’d. // postcondition: sets size to argument value public void setSize(double aSize) { size = aSize; } // postcondition: sets price to argument value public void setPrice(double aPrice) { price = aPrice; } // postcondition: returns the item description public String getDesc() { return description; } // postcondition: returns the item size public double getSize() { return size; }

  15. Class FoodItem, cont’d. // postcondition: returns the item price public double getPrice() { return price; } // postcondition: returns string representing // the item state public String toString() { return description + ", size : " + size + ", price $" + price; } // postcondition: calculates & returns unit price public double calcUnitPrice() { return price / size; } }

  16. void Methods • The mutator methods are void methods. • Method setSize() sets the value of data field size to the value passed to parameter aSize. • Avoid method is executed for its effect because it does not return a value; however, it may change the state of an object or cause some information to be displayed. public void setSize(double aSize) { size = aSize; }

  17. The return Statement • Each FoodItem method that is not a void method or a constructor returns a single result. The return statementabove returns the value of data field price as the function result. • Form:returnexpression; • Example:return x + y; • Interpretation: The expression after the keyword returnis returned as the method result. Its data type must be assignment compatible with the type of the method result. public double getPrice() { return price; }

  18. toString() Method • A toString() method returns a reference to a String object that represents an object's state. The expression after returnspecifies the characters stored in the String object returned as the method result. It starts with the characters in description followed by the characters , size :followed by characters representing the value of data field size and price; e.g., "apples, Macintosh, size: 2.5, price $1.25" public String toString() { return description + ", size : " + size + ", price $" + price; }

  19. Calling methods • Because a void method does not return a value, a call to a void method is a Java statement all by itself. If myCandy is type FoodItem, an example would be • Because a non-void method returns a value, a call to a non-void method must occur in an expression: • The result returned by the call to method getPrice() (type double) is appended to the string that starts with the characters price is $ myCandy.setDescription("Snickers, large"); "price is $" + myCandy.getPrice()

  20. Call to Constructor • A constructor executes when a new object is created and initializes the object’s data fields. A call to this constructor always follows the word new and has the form: public FoodItem(String desc, double aSize, double aPrice) { description = desc; size = aSize; price = aPrice; } FoodItem myCandy = new FoodItem("Snickers", 6.5, 0.55);

  21. Argument "Snickers" 6.5 0.55 Parameter desc (references "Snickers") aSize (value is 6.5) aPrice (value is 0.55) Argument/Parameter Correspondence for FoodItem("Snickers", 6.5, 0.55) Primitive type arguments are passed by value which means the method cannot change the argument value.

  22. UML class diagram TestFoodItem main() association relationship FoodItem worker class description: String size: double price: double FoodItem() setDesc() setSize() setPrice() getDesc() getSize() getPrice() calcUnitPrice() toString() Program classes and their relationships Testing the class FoodItem UML sequence diagram classes/ objects client (application) class TestFoodItem myCandy: FoodItem new() creation of a new object mySoup: FoodItem new() toString() object lifeline time axis calculateUnitPrice() method call toString() method execution calculateUnitPrice() return from method (optional) Collaboration between objects (classes) at runtime

  23. Application or Client of FoodItem /* * TestFoodItem.java Author: Koffman and Wolz * Tests class FoodItem */ public class TestFoodItem { public static void main(String[] args) { FoodItem myCandy = new FoodItem("Snickers", 6.5, 0.55); FoodItem mySoup = new FoodItem( "Progresso Minestrone", 16.5, 2.35); System.out.println(myCandy.toString()); System.out.println(" -- unit price is $" + myCandy.calcUnitPrice()); System.out.println(mySoup.toString()); System.out.println(" -- unit price is $" + mySoup.calcUnitPrice()); } }

  24. Sample Run of Class TestFoodItem

  25. 3.2 Finding Words in a Sentence • PROBLEM: We want to write a program that gets a sentence and displays the first three words in the sentence on separate lines. To simplify the task, we assume that the sentence has at least 4 words.

  26. DESIGN of Application Class • Algorithm for main() 1. Read in a sentence. 2. Create a WordExtractor object that stores the input sentence. 3. Write the first word to the console window. 4. Create a WordExtractor object that stores the sentence starting with the second word. 5. Write the second word to the console window. 6. Create a WordExtractor object that stores the sentence starting with the third word. 7. Write the third word to the console window. 8. Write the rest of the sentence to the console window.

  27. WordExtractor App System.out JOptionPane showInputDialog() get sentence wE1: WordExtractor new() create wE1, get first word and display it getFirst() println() getRest() wE2: WordExtractor new() create wE2, get next word and display it getFirst() println() getRest() wE3: WordExtractor new() create wE3, get next word and display it getFirst() println() getRest() display rest of the sentence println() UML sequence diagram

  28. Program Style: Using Multiple Objects versus Reusing One • There is usually more than one way to solve a problem. Because class WordExtractorApp needed to extract three words, we decided to use multiple objects of type WordExtractor. When we create each object, we pass the constructor a different string to be stored. Consequently, when we apply methods getFirst() and getRest() to each object, we get a different result. • We could have used just one object. We could use method setSentence() to update its value after extracting each word Neither solution is "better"; they are just different approaches. • Question to ponder: Rewrite WordExtractorApp using just object wE1.

  29. 3.3 A Worker Class that Processes Integers PROBLEM A common problem is to determine the value of a collection of coins. Our goal is to write a class that simulates the behavior of a coin changing machine. Instead of pouring a container of coins into a hopper, the user will provide the number of each kind of coin as input data.

  30. ANALYSIS • The first step is to determine what a coin-changing machine must do. It accepts a collection of coins and computes the value of the coins in dollars and cents. For example, if a collection contains 5 quarters and 3 pennies, its value is $1.28 (one dollar and 28 cents in change). The problem inputs are the number of each kind of coin and the problem output is the value of the coins in dollars and change. • Data Requirements Problem Inputs Problem Output the number of pennies value of coins in dollars and change the number of nickels Relevant Formulas the number of dimes value of a penny is 1 cent the number of quarters value of a nickel is 5 cents value of a dime is 10 cents value of a quarter is 25 cents value of a dollar is 100 cents

  31. JOptionPane from javax.swing ChangeCoinApp application class readDouble() readInt() … main() worker class association relationships class name CoinChanger pennies: int nickels: int dimes: int quarters: int data fields or attributes class imported from javax.swing package setPennies() setNickels() setDimes() setQuarters() findCentValues() findDollars() toString() methods or operations UML class diagrams describe the program structure, i.e. the classes and their relationships. The execution of a program can be described by using UML sequence diagrams. DESIGN: UML class diagram

  32. WasherAppl JOptionPane create new object changer: CoinChanger new() notes for comments object readInt() showInputDialog() get number of pennies setPennies() readInt() focus of control (represents the method execution) showInputDialog() get number of nickels setNickels() readInt() get number of dimes showInputDialog() setDimes() object life line readInt() get number of quarters showInputDialog() setQuarters() findCentValues() compute dollars and change findDollars() findChange() findCentValues() showMessageDialog() display results UML sequence diagram method call from another object internal method call internal method execution

  33. Data fields int pennies int nickels int dimes int quarters methods void setPennies(int) void setNickels(int) void setDimes(int) void setQuarters(int) int findCentsValue(int int findDollars() int findChange() String toString() Attributes count of pennies count of nickels count of dimes count of quarters Behavior Sets the count of pennies. Sets the count of nickels. Sets the count of dimes. Sets the count of quarters. Calculates total value in cents. Calculates value in dollars. Calculates leftover change. Represents object's state. Design of Class CoinChanger

  34. Algorithms for CoinChanger methods Algorithm for setPennies() 1. Store the number of pennies. Algorithm for findCentsValue() 1. Calculate the total value in cents using the formula total cents = pennies + 5 ´ nickels +10 ´ dimes + 25 ´ quarters Algorithm for findDollars() 1. Get the integer quotient of the total value in cents divided by 100 (for example, the integer quotient of 327 divided by 100 is 3). Algorithm for findChange() 1. Get the integer remainder of the total value in cents divided by 100 (for example, the integer remainder of 327 divided by 100 is 27).. Algorithm for toString() 1. Represent the state of the object (the number of each kind of coin).

  35. Implementation of CoinChanger /* * CoinChanger.java Author: Koffman and Wolz * Represents a coin changer */ public class CoinChanger { // Data fields private int pennies; private int nickels; private int dimes; private int quarters; // Methods public void setPennies(int pen) { pennies = pen; } public void setNickels(int nick) { nickels = nick; } public void setDimes(int dim) { dimes = dim; } public void setQuarters(int quart) { quarters = quart; }

  36. Implementation of CoinChanger, cont’d. // postcondition: Returns the total value in cents. public int findCentsValue() { return pennies + 5 * nickels + 10 * dimes + 25 * quarters; } // postcondition: Returns the amount in dollars. public int findDollars() { return findCentsValue() / 100; } // postcondition: Returns the amount of leftover // change. public int findChange() { return findCentsValue() % 100; } public String toString() { return pennies + " pennies, " + nickels + " nickels, " + dimes + " dimes, " + quarters + " quarters"; } }

  37. method main Classes used CoinChanger, JOptionPane behavior Gets the number of each kind of coin, stores this information in a CoinChanger object, calculates and displays the value of coins in dollars and change. Design of ChangeCoinsApp • Algorithm for main() • 1. Create a CoinChanger object. • 2. Store the number of each kind of coin in the CoinChanger object. • 3. Display the value of the coins in dollars and change.

  38. 3.4 Review of Methods • Default initialization of new object by Constructor Data Field Type Default value intzero double zero booleanfalse char The first character in the Unicode character set (called the null character) a class type null

  39. Two constructors for CoinChanger No parameter constructor (default) public CoinChanger() { } public CoinChanger(int pen, int nick, int dim, int quar) { pennies = pen; nickels = nick; dimes = dim; quarters = quar; } If you write one or more constructors for a class, the compiler will not provide a default constructor, so you must define it yourself if you need it. When a new CoinChanger object is created, the argument list used in the constructor call determines which constructor is invoked.

  40. Calling one Instance Method from Another • Method findDollars() (new method in class CoinChanger) calls method findCentsValue() (also defined in class CoinChanger). Notice that instance method findCentsValue() is not applied to any object. The default is the current object which can be represented by the keyword this; e.g., // postcondition - returns coin value in dollars public int findDollars() { return findCentsValue() / 100; } return this.findCentsValue() / 100;

  41. Use of Prefix this with a Data Field // Mutator // Stores argument value in data field pennies. public void setPennies(int pennies) { this.pennies = pennies; } Refers to argument pennies Refers to data field pennies • Note: the local declaration of pennies as a parameter • in method setPennies()hides data field pennies • in this method. Hence, the need for keyword this to • reference the data field.

  42. 3.6 Simplifying a Solution Using Multiple Classes PROBLEM You work for a hardware company that manufactures flat washers. To estimate shipping costs, you need a program that computes the weight of a specified quantity of flat washers. As part of this process, you need to compute the weight of a single washer.

  43. ANALYSIS • A flat washer resembles a small donut. To compute its weight you need its rim area, thickness, and the density of the material used in its construction. The thickness and density of a washer are available as input data. • The rim area must be calculated from the washer's inner diameter ( ) and the washer's outer diameter ( ) which are both data items. The number of washers is an input.

  44. ANALYSIS, cont’d. Data Requirements Problem Inputs Problem Outputs inner radius weight of batch of washers outer radius thickness density quantity Relevant formulas area of circle= pxradius2 perimeter of circle = 2 xpxradius area of donut = area of outer circle - area of inner circle Need a Circle class, a Washer class, and an application class

  45. WasherAppl JOptionPane from javax.swing main() readDouble() readInt() readDouble() readInt() … association relationship (a class calls the other’s methods) Circle Washer inner: Circle outer: Circle thickness: double density: double radius: double class imported from javax.swing package setRadius() getRadius() computeArea() computeCircum() toString() computeRimArea() computeWeight() setInner() setOuter() setTickness() setDensity() toString() composition relationship (an object of class Washer contains one or more objects of class Circle) UML Class Diagram

  46. ANALYSIS, cont’d. Data Requirements Problem Inputs Problem Outputs inner radius weight of batch of washers outer radius thickness density quantity Relevant formulas area of circle= ¶ x radius2 perimeter of circle = 2 x ¶ x radius area of donut = area of outer circle - area of inner circle

  47. Circle class Data fields double radius Instance methods double computeArea() double computeCircum() Attributes the circle radius Behavior Computes the circle area. Computes the circle circumference. DESIGN of Circle class Need a Circle class, a Washer class, and an application class

  48. Circle class /* * Circle.java Author: Koffman and Wolz * A class that represents a circle */ public class Circle { private double radius; public Circle() {} public Circle(double rad) { radius = rad; } public void setRadius(double rad) { radius = rad; } public double getRadius() { return radius; }

  49. Circle class, cont’d. public double computeArea() { return Math.PI * radius * radius; } public double computeCircum() { return 2.0 * Math.PI * radius; } public String toString() { return "circle with radius: " + radius; } } ¶ ¶

  50. Data fields Circle inner Circle outer double thickness double density Instance methods double computeRimArea() double computeWeight Classes used: Circle Attributes the inner circle the outer circle the washer thickness the material density Behavior Computes the washer's rim area. Computes the washer's weight. DESIGN of Washer Class

More Related