760 likes | 770 Views
Learn about writing Worker and Support classes for reusable applications, including structure, data fields, methods, and more.
E N D
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
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.
Review of class definitions • A Header declaration • The class body • The data field declarations of the class • The method definitions of the class
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.
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;
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.
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];
Visibility • 4 types of visibility exist: • private (only class) • public (anywhere) • protected (class and subclasses) • default (package (in same folder))
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.
Method Definitions • Form: method header { method body } • The header gives the method name and parameters and return value which are both optional.
Syntax Diagram visibility [static] resultType methodName([parameterList]) public static void main(string[] args) private double getPrice() private void setPrice(double aPrice) private String toString()
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
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
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
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.
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
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.
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
Constructor method public FoodItem(String desc, double aSize, double aP) { description = desc; size = aSize; price = aP; }
Mutator (modifier) public void setDesc(String desc) { description = desc; } public void setSize(double aSize) { size = aSize; } public void setPrice(double aPrice) { price = aPrice; }
Accessor public String getDesc() { return description; } public double getSize() { return size; } public double getPrice() { return price; }
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.
toString // postcondition: returns a string representing the item state public String toString() { return description + ", size : " + size + ", price $" + price; }
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();
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.
Post Condition // postcondition: sets description to the argument value public void setDesc(String desc) { description = desc; }
Post Condition // postcondition: returns the item price public double getPrice() { return price; }
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
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()); } }
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.
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.
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
Section 3.2 Class to manipulate Strings • This section of the book create both a worker (supporting) class and an application class.
Problem • Program gets a sentence • Displays first 3 words of the sentence on different lines. • Sentence must have at least 4 words
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
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.
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
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
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
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. • ……………
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()
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.
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.
Some details String sent = JOptionPane.showInputDialog(“enter at least 4 words”); WordExtractor wE1 = new WordExtractor(sent);
Code • Look at code pages 124 – 125 • Look at running in JBuilder
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.
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
Data • Input • Number of pennies • Number of nickels • Number of dimes • Number of quarters • Output • Value if coins in dollars and change
Design • See table on page 129