1 / 76

Chapter 3

Chapter 3. Object Oriented Design and Writing Worker Classes. Structure of classes . We will begin to write 2 classes for each project Worker or Support class Application or client class The intent is to create classes that are reusable Reuse is an important aspect of OOP.

jbarker
Télécharger la présentation

Chapter 3

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 3 Object Oriented Design and Writing Worker Classes

  2. Structure of classes • We will begin to write 2 classes for each project • Worker or Support class • Application or client class • The intent is to create classes that are reusable • Reuse is an important aspect of OOP

  3. Section 3.1 First Worker Class • We will carefully study a class that represents Food Items in a grocery store. • Worker classes are meant to represent real world objects. • They model a real world entity. Keep this in mind as we analyze this class.

  4. Review of class definitions • A Header declaration • The class body • The data field declarations of the class • The method definitions of the class

  5. Class Data fields • The data fields of a class are also called instance variables. • These are chosen very carefully! • Only the data that represents the object is part of the class data fields. • Do not put all necessary variables here. Other variables will be used in you methods later.

  6. Class Data Field • The values in these fields represent the “state” of the object. • The FoodItem fields are: public class FoodItem { // data fields private String description; private double size; private double price;

  7. Class Data Fields • Class data fields always have visibility of private. • This means they can be accessed from anywhere in the class, but can not be accessed from outside the class. • This is a form of encapsulation that we will discuss further later.

  8. Class Data Fields • Because we make our class data fields private they can only be accessed via the class methods. • Syntax Diagram: [visibility] typeName datafieldName = [value];

  9. Visibility • 4 types of visibility exist: • private (only class) • public (anywhere) • protected (class and subclasses) • default (package (in same folder))

  10. Initial values • You can optionally include initial values for your data fields. private double price = 1.0; • Later we will learn to use this in very powerful ways.

  11. Method Definitions • Form: method header { method body } • The header gives the method name and parameters and return value which are both optional.

  12. Syntax Diagram visibility [static] resultType methodName([parameterList]) public static void main(string[] args) private double getPrice() private void setPrice(double aPrice) private String toString()

  13. Methods Methods • We will always provide the following 4 “types” of methods with our worker classes: 1. constructor 2. mutator (modifier) 3. accessor 4. method that returns object state as a string

  14. Methods • Those are the 4 types of Standard method we will provide. They always work with the class data fields. • We will additionally then provide the specialized methods needed to perform our individual tasks: • A method that calculates the unit price of an item

  15. Constructor • Always has same name as the class. • Gets called automatically when you instantiate a class. • If you do not provide one, one is automatically provided for you. • Allows user of worker class to set initial values in the data fields

  16. Mutators (modifiers) • Allow the user to change the “state” of the object. • Which means they can change the values in the data fields. • Typically have 1 for each class data field and start with the word “set”. • They are void, don’t return a value. • Are passed a value (parameter) to store in data field.

  17. Accessors • Allow the user of you class to see or return the state (class data fields). • Again typically have 1 for each data field. • Typically begin with the word get. • They always return a value (not void) • Do not receive parameters

  18. String • toString() converts the state of a class to a string. • We will see some real neat outcomes of always providing this toString() method. • Always returns a value of type string.

  19. Methods headers • The order that the methods are programmed does not matter. • By convention we typically list constructors, mutators, accessors, toString, then our class specific methods. • See table of headers on page 109

  20. Constructor method public FoodItem(String desc, double aSize, double aP) { description = desc; size = aSize; price = aP; }

  21. Mutator (modifier) public void setDesc(String desc) { description = desc; } public void setSize(double aSize) { size = aSize; } public void setPrice(double aPrice) { price = aPrice; }

  22. Accessor public String getDesc() { return description; } public double getSize() { return size; } public double getPrice() { return price; }

  23. Return • This is used to return a value to a calling program. • Must use if not void. • Tells compiler that the expression that follows is returned as the method result. • Compiler assures that it is not possible to exit without returning a value. If possible get a syntax error.

  24. toString // postcondition: returns a string representing the item state public String toString() { return description + ", size : " + size + ", price $" + price; }

  25. Calling Methods • Void methods are statements by themselves myCandy.setDescription(“Snickers”); • non-void you must use value being returned “Price is $” + myCandy.getPrice(); double price = myCandy.getPrice();

  26. Post conditions • Each method should begin with a post condition comment. • This is what must be true after the method executes. • Is a part of the documentation.

  27. Post Condition // postcondition: sets description to the argument value public void setDesc(String desc) { description = desc; }

  28. Post Condition // postcondition: returns the item price public double getPrice() { return price; }

  29. Parameters • You can only access parameters within the body of the method they are passed to. • This is the “scope” of the method. • Parameters are passed “respectively” • They must match in type. • See examples pg 114-115

  30. Test Class 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); System.out.println(" -- unit price is $" + mySoup.calcUnitPrice()); } }

  31. Arguments Passed by value • Primitive types are passed by value. • If you change in method is not changed in calling program • See example 3.4 page 117 • Objects are passed by reference.

  32. Transfer of control • When method is called control is passed to that method from the main method. • When reaches end of method returns to main method. • See example Figure 3.5 on page 118.

  33. Encapsulation • Mutator methods change the state of the data fields. • But to make those changes the client (user) program must come through your methods. • To retrieve a data fields must come through accessor. • Your data is protected by encapsulation. • See diagram pg 119

  34. Section 3.2 Class to manipulate Strings • This section of the book create both a worker (supporting) class and an application class.

  35. Problem • Program gets a sentence • Displays first 3 words of the sentence on different lines. • Sentence must have at least 4 words

  36. Analysis • Get first word of sentence • Get rest of sentence also • Then can get first word of “rest of sentence” • and so on • See table 3.3 top of page 121

  37. Analysis • Input • A sentence (at least 4 words) • Output • first three words of the sentence • Need 2 classes • Worker class WordExtractor must store sentence and get 1st word and “rest” • WordExtractorApp uses WordExtractor to solve the problem.

  38. Design • Class WordExtractor • Methods • getFirst() to get first word • getRest() to get rest of sentence • Your methods represent the actions you identify in analysis • See figure 3.7 page 121

  39. Analysis • Algorithm for getFirst() • find position of the first blank in sentence • return characters up to the first blank • Algorithm for getRest() • find position of the first blank in sentence • return characters after the first blank

  40. Analysis • Application class (WordExtractor) always contains main method where program execution begins. • Can solve this by creating 3 word extractor objects. • 1st one original sentence • 2nd “rest” and so on

  41. Algorithm for main() • Read in Sentence. • Create WordExtractor object that stores input sentence. • Write first word in console window. • Create new WordExtractor object that stores sentence starting with second word. • ……………

  42. Implementation • Each class gets defined in it’s own file. • Is it’s own project in JBuilder. • Class WordExtractor has a single field • sentence whose first word is being retrieved • Use String class • indexOf() • substring()

  43. Some details • int posBlank = sentence.indexOf(“ “); • posBlank is a variable but is not a class data field. • posBlank is a local variable to the method it is declared in. • Can only be accessed in this method. • This is known as variable scope.

  44. Some details • return sentence.substring(0, posBlank); • returns String object containing characters of first word. • return sentence.substring(posBlank + 1); • return String object containing rest of sentence.

  45. Some details String sent = JOptionPane.showInputDialog(“enter at least 4 words”); WordExtractor wE1 = new WordExtractor(sent);

  46. Code • Look at code pages 124 – 125 • Look at running in JBuilder

  47. Program style • Program choose to use multiple objects versus 1 object solution. • Will be easier to design 1 object solution once we know about looping. • Notice worker class did not have appropriate constructor, mutator, and accessor methods.

  48. Section 3.3 Worker class for integers • Problem • Program takes number of coins and converts it into total amount. • Analysis • Computes the value in dollars and cents

  49. Data • Input • Number of pennies • Number of nickels • Number of dimes • Number of quarters • Output • Value if coins in dollars and change

  50. Design • See table on page 129

More Related