An Introduction to Programming and Object Oriented Design

An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 3: Designing interactive classes.

Objectives ñ After studying this chapter you should understand the following: ñ the role of responsibilities in the design of an object; ñ the categorization of an object’s responsibilities as knowing responsibilities or doing responsibilities; ñ the difference between local variables and instance variables; ñ the structure of a complete program in Java; ñ the structure of a test system; ñ the purpose of named constants. May 2004 NH-Chapter 3 1

Objectives ñ Also, you should be able to: ñ analyze the role a simple object plays in a given problem and list its responsibilities; ñ use Java to specify the features of an object based on its responsibilities; ñ use Java to implement a simple class that has been specified; ñ implement a complete Java program using a simple textbased interface for an object; ñ implement a simple tester for testing a class implementation; ñ define named constants. May 2004 NH-Chapter 3 2

Designing with objects ñ Two questions when we design an OO system : ñwhat are the objects? ñwhat features should these objects have? ñ Our Initial goal: learn to design and implement simple objects. ñ We will ssume objects are there for the picking. May 2004 NH-Chapter 3 3

Designing with objects ñ Objects are designed to support system functionality. ñ System specification are distributed as responsibilities to objects identified. May 2004 NH-Chapter 3 4

Object responsibilities ñ Think in terms of ñ what object must know. ñ what object must do. May 2004 NH-Chapter 3 5

Object responsibilities ñ Knowing responsibilities include: ñ knowing properties of the entity object is modeling; ñ knowing about other objects with which it needs to cooperate. May 2004 NH-Chapter 3 6

Object responsibilities ñ Doing responsibilities include: ñ computing particular values; ñ performing actions that modify its state; ñ creating and initializing other objects; ñ controlling and coordinating the activities of other objects. May 2004 NH-Chapter 3 7

From responsibilities to class features ñ “Knowing responsibilities” ñ translate into data the object must maintain or ñ Translate into queries. ñ “Doing responsibilities” ñ translate into commands or ñ Translate into queries. May 2004 NH-Chapter 3 8

Designing a class ñ To design a class: ñ determine an object’s responsibilities, ñ classify them as knowing or doing responsibilities. May 2004 NH-Chapter 3 9

Example: Design of Nim game ñ Game: Players take turns removing sticks from a pile. Each player in turn removes one, two, or three sticks. The player who removes the last stick loses. May 2004 NH-Chapter 3 10

Design of Nim game ñ Two objects for the picking: ñ Player ñ Pile of sticks ñ Pile and Player are part of the model of problem. ñ Model aspects of game independently of how is presented to a user or how a user interacts with it. May 2004 NH-Chapter 3 11

Designing Pile ñ Pile a very simple object: ñ keeps track of how many sticks remain. ñ Pile responsibilities: ñ know: ínumber of sticks remaining ñ do: íreduce number of sticks (remove sticks) May 2004 NH-Chapter 3 12

Designing Player ñ Player takes a turn in the game to remove sticks from Pile. ñ Player responsibilities: ñ know: íthis Player’s name. íhow many sticks this Player removed on his/her most recent turn. ñ do: ítake a turn by removing sticks from the Pile May 2004 NH-Chapter 3 13

From knowing responsibilities to queries ñ Class: Pile ñ queries: sticks the number of sticks remaining in this Pile, a non-negative integer May 2004 NH-Chapter 3 14

From knowing responsibilities to queries ñ Class: Player ñ queries: ñ name : this Player’s name, a String ñ sticks. Taken : number of sticks this Player removed on his/her most recent turn ( 1, 2, or 3). May 2004 NH-Chapter 3 15

From doing responsibilities to commands ñ Class: Pile ñ commands: remove : reduce number of sticks by specified amount (number) May 2004 NH-Chapter 3 16

From doing responsibilities to commands ñ Class: Player ñ commands: take. Turn remove 1, 2, or 3 sticks from the specified Pile (pile) May 2004 NH-Chapter 3 17

Interaction diagram: Player takes turn May 2004 NH-Chapter 3 18

Pile, and Player constructors ñ How are the Player’s name and the initial number of sticks in the Pile determined? ñ Set these values Constructors. when objects are created: ñ Constructors can have parameters: ñ Player’s name parameter in Player’s constructor. ñ Initial number of sticks parameter in Pile constructor. May 2004 NH-Chapter 3 19

Pile specifications ñ nim. Game ñ Class Pile public class Pile A pile of sticks for playing simple nim. ñ Constructors public Pile (int sticks) Create a new Pile, with the specified number of sticks must be non-negative. May 2004 NH-Chapter 3 20

Pile specifications ñ Queries public int sticks () Number of sticks remaining in this Pile. ñ Commands public void remove (int number) Reduce the number of sticks by the specified amount. number must be non-negative and not greater than the number of sticks remaining. May 2004 NH-Chapter 3 21

Player specifications ñ nim. Game ñ Class Player public class Player A player in the game simple nim. ñ Constructors public Player (String name) Create a new Player with the specified name. May 2004 NH-Chapter 3 22

Player specifications ñ Queries public String name () The name of this Player. public int sticks. Taken () The number of sticks this Player removed on this Player’s most recent turn: 1, 2, or 3. May 2004 NH-Chapter 3 23

Player specifications ñ Commands public void take. Turn (Pile pile) Remove 1, 2, or 3 sticks from the specified Pile. May 2004 NH-Chapter 3 24

Implementing the class Pile ñData maintained by Pile is number remaining sticks. private int sticks. Left; // sticks left in the Pile ñ Instance variable sticks. Left is initialized in constructor and value returned by query sticks: public Pile (int sticks) { sticks. Left = sticks; } public int sticks () { return sticks. Left; } May 2004 NH-Chapter 3 25

Implementing the class Pile ñCommand remove is specified with an int parameter number, indicating sticks to be removed: public void remove (int number) { … ñ Executing command reduces instance variable sticks. Left by value client supplies in number. public void remove (int number) sticks. Left = sticks. Left - number; } May 2004 NH-Chapter 3 26

Implementing the class Player ñPlayer needs to know name and number of sticks taken on most recent turn. private String name; // this Player’s name private int sticks. Taken; // sticks taken on this Player’s ñ Variables should be initialized in the constructor. public Player (String name) { this. name = name; this. sticks. Taken = 0; } May 2004 NH-Chapter 3 27

Implementing the class Player ñ Queries simply return the values of the instance variables: public String name () { return name; } public int sticks. Taken () { return sticks. Taken; } May 2004 NH-Chapter 3 28

Invoking a method: acting as client ñGeneral form for invoking a query: object. Reference . query. Name(arguments) ñ General form for invoking a command is object. Reference May 2004 . command. Name(arguments); NH-Chapter 3 29

Implementing Player’s take. Turn /** * Remove 1, 2, or 3 sticks from the specified Pi * The Pile must not be empty. */ public void take. Turn (Pile pile) { … ñ take. Turn method must: Zdetermine how many sticks to take; Give Player the move strategy to take 1 stick. Zremove them from the Pile; pile. remove(1); Zstore the number removed in sticks. Taken instance variable. sticks. Taken = 1; May 2004 NH-Chapter 3 30

Implementing Player’s take. Turn /** * Remove 1, 2, or 3 sticks from the specified Pile. * The Pile must not be empty. */ public void take. Turn (Pile pile) { pile. remove(1); sticks. Taken = 1; } May 2004 NH-Chapter 3 31

Interaction diagram: Player commands a Pile May 2004 NH-Chapter 3 32

Parameters v. s. arguments ñ Arguments are provided in a method invocation by expressions. Thus we could write something like pile. remove(sticks. Taken + 1); or even pile. remove(2*sticks. Taken+2); May 2004 NH-Chapter 3 33

Parameters v. s. arguments ñArguments must match in number, type and order: public void move (int direction, double dist … } ñ An invocation of move must provide two arguments, an int and a double in that order. object. move(90, 2. 5); May 2004 NH-Chapter 3 34

Commands and queries ñ A command invocation is a form of statement. ñ A query, which produces a value, is an expression. ñ If my. Counter is a Counter object and i an int, i = my. Counter. current. Count(); i = my. Counter. current. Count()+10; May 2004 NH-Chapter 3 35

Example: Maze game ñ Player must find his/her way through a set of connected rooms to reach some goal. ñ there will be tricks player must figure out; ñ creatures of various kinds to be defeated along the way. May 2004 NH-Chapter 3 36

Example: Maze game ñ Objects for the picking: ñ player, ñ maze denizens, ñ rooms. May 2004 NH-Chapter 3 37

Designing Explorer ñ Explorer responsibilities: ñ know: Zhis/her name Zlocation in the maze Zamount of annoyance done when poking an opponent Zamount of annoyance he/she can endure before being defeated. May 2004 NH-Chapter 3 38

Designing Explorer ñ Responsibilities into properties ñ name of the Explorer ñ location room in which Explorer is in ñ strength measure of Explorer’s offensive ability ñ tolerance measure of what it takes to defeat Explorer May 2004 NH-Chapter 3 39

Designing Explorer ñ Type of value for each Explorer’s property: ñ Name: ñ Location: ñ Strength: ñ Tolerance: String Room int Explorer String name Room location May 2004 int strength 10 int tolerance 100 Room NH-Chapter 3 40

Designing Explorer ñ Explorer responsibilities: ñ do: Zchange location in the maze (move from room to room) Zfight a maze Denizen ñ commands to to perform these actions. ñ move ñ poke May 2004 change location poke a Denizen NH-Chapter 3 41

Designing Explorer ñ Both commands will have parameters: ñ move change location (new location) ñ poke a Denizen (denizen to poke) May 2004 NH-Chapter 3 42

Interaction diagram May 2004 NH-Chapter 3 43

A constructor for the class Explorer ñ Need constructor for creating Explorer instances. ñ During creation properties must be initialized. ñ Require values for name, location, strength, and tolerance be provided as argument. ñ Constructor for Explorer has four parameters: create new Explorer (name, location, strength, tolerance) May 2004 NH-Chapter 3 44

Explorer specification maze. Game Class Explorer public class Explorer A maze game player. Constructors public Explorer (String name, Room location, int str Create a new Explorer with specified name, initial location, strength, and tolerance. Annoyance (hit points) required to defeat this Explorer. May 2004 NH-Chapter 3 45

Explorer specification Queries public String name () Name of this Explorer. public Room location () Room in which this Explorer is currently located. public int strength () Annoyance (hit points) this Explorer causes when poking an opponent. public int tolerance () Annoyance (hit points) required to defeat this Explorer. May 2004 NH-Chapter 3 46

Explorer specification Commands public void move (Room new. Room) Move to the specified Room. public void take. That (int hit. Strength) Receive a poke of the specified number of hit points. public void poke (Denizen opponent) Poke the specified Denizen. May 2004 NH-Chapter 3 47

Implementing class Explorer ñ Explorer objects have four name, location, strength, and tolerance. properties: ñ Use instance variables to store these values: private String name; Room location; int strength; int tolerance; // // name current location current strength (hi current tolerance (h ñThese variables are initialized in the constructor. May 2004 NH-Chapter 3 48

Implementing class Explorer ñ Queries return current values of instance variables. ñ Example: query location returns value stored in location. public Room location () { return location; } May 2004 NH-Chapter 3 49

Implementing class Explorer ñImplementing method move, argument value is stored in instance variable location: public void move (Room new. Room) { location = new. Room; } May 2004 NH-Chapter 3 50

Implementing class Explorer ñMethod take. That is similar to Pile method remove. Argument value, hit. Strength, is subtracted from insta variable tolerance and stored in tolerance: public void take. That (int hit. Strength) { tolerance = tolerance - hit. Strength; } May 2004 NH-Chapter 3 51

Implementing class Explorer ñ Method poke invokes Denizen’s method take. That: public void poke (Denizen opponent) { opponent. take. That(strength); } May 2004 NH-Chapter 3 52

Local variables in methods ñ local variable: method variable created as part of method execution; used to hold intermediate results needed during computation. May 2004 NH-Chapter 3 53

Local variables in methods ñAssume that Retail. Item includes instance variables, with the obvious meanings: private double base. Price; private double discount. Rate; private double tax. Rate; ñ Want to implement Retail. Item method net. Price: public double net. Price () The cost of this Retail. Item after discount, and including tax. May 2004 NH-Chapter 3 54

Local variables in methods public double net. Price () { double discount; double subtotal; Local variables double tax; discount = base. Price * discount. Rate; subtotal = base. Price - discount; tax = subtotal * tax. Rate; return subtotal + tax; } May 2004 NH-Chapter 3 55

Local variables Instance variables • Defined inside a method. • Defined outside any method. • Exists while method executes. • Exists as long as the object exists. • Must be initialized before used. otherwise, compiler error. • Initialized in a constructor. • Accessed only from the method. • Has meaningful value during life of object, whether or not object is actively doing something. • Meaningful only during method execution. • Contains some intermediate value needed only during execution of method; value is not part of object’s state. May 2004 • Accessed from any class method. • Represents an object’s property; its value is part of object’s state. NH-Chapter 3 56

Putting together a complete system ñ A complete system includes ñ model ñ user interface. ñ Example: ñ model Rectangle instance displayed on a computer screen; use int to measure dimensions. ñ User interface object: instance of class Rectangle. Viewer, with one command, display. Rectangle. May 2004 NH-Chapter 3 57

Putting together a complete system ñ display. Rectangle: writes Rectangle’s length, width, area, and perimeter to the screen. ñ Rectangle. Viewer queries Rectangle for display data. May 2004 NH-Chapter 3 58

Designing Rectangle ñ Rectangle know ñ Width ñ Length ñ Rectangle do ñ Compute area ñ Compute perimeter May 2004 NH-Chapter 3 59

Rectangle specifications figures Class Rectangle public class Rectangle Constructors public Rectangle (int length, int width) Create a new Rectangle with the specified length and width. Queries public int length () The length of this Rectangle. public int width () The width of this Rectangle. public int area () The area of this Rectangle. public int perimeter () The perimeter of this Rectangle. May 2004 NH-Chapter 3 60

Specifying Rectangle. Viewer public void display. Rectangle (Rectangle rectangle) ñ Write the length, width, area, and perimeter of the specified Rectangle to standard output. May 2004 NH-Chapter 3 61

System. out. println ñSimple way to write output to the display. ñObject System. out has a method public void println (String s) Write a line containing the specified String to standard output. ñ Executing the method results in its argument being written to the screen. May 2004 NH-Chapter 3 62

Implementing display. Rectangle public void display. Rectangle rectangle) { (Rectangle int output. Value; output. Value = rectangle. length(); System. out. println("length: " + output. Value); output. Value = rectangle. width(); System. out. println("width: " + output. Value); output. Value = rectangle. area(); System. out. println("area: " + output. Value); May 2004 output. Value = rectangle. perimeter(); NH-Chapter 3 63

main Method ñ Need a public class, containing a method main. ñ main method: top-level method that initiates execution of a system. ñ Method main is specified as: public static void main (String[] argv) May 2004 NH-Chapter 3 64

main Method ñmain used to ñCreate Rectangle and Rectangle. Viewer, ñCommand Rectangle. Viewer to display Rectangle. May 2004 NH-Chapter 3 65

Main class /** * A simple system to display a Rectangle’s properties. */ public class Rectangle. Display { // Run the program. public static void main (String[] argv) { Rectangle the. Model; Rectangle. Viewer the. User. Interface; the. Model = new Rectangle(100, 50); the. User. Interface = new Rectangle. Viewer(); May 2004 the. User. Interface. display. Rectangle(the NH-Chapter 3 Model); 66

The method to. String ñ Useful to include in model classes a query to return a String representation of an object’s state. ñ In Java, this method is specified by convention as: public String to. String () A String representation of the object. May 2004 NH-Chapter 3 67

The method to. String ñ For example, define the method in the class Rectangle : /** * A String representation of this object. */ public String to. String () { return "Rectangle: length = " + length + " width = " + width; } May 2004 NH-Chapter 3 68

Testing ñ Unit testing: test class being implemented to make sure it behaves as expected. ñ Functional testing: test entire system to ensure that it meets customer’s specifications. May 2004 NH-Chapter 3 69

Test driven implementation ñ Incremental test-driven implementation: most effective means of reducing time required to track down and correct bugs. ñ Test-driven aspects ñ The process is to code a little, test a little. ñ Implementation is “test-driven. ”: write test for a feature before implementing the feature. May 2004 NH-Chapter 3 70

Test driven implementation example ñ Stubbed implementation of Traffic. Signal public class Traffic. Signal { public static final int private int light; public Traffic. Signal () } public int light () { return 0; } public void change () { GREEN = 0; YELLOW = 1; RED = 2; { Left blank Dummy return value Left blank } } May 2004 NH-Chapter 3 71

Traffic. Signal. Test class ñ Traffic. Signal. Test ñ Client of Traffic. Signal ñ Creates instance of Traffic. Signal ñ Queries and commands Traffic. Signal instance ñ User interface object, reporting test results to user. May 2004 NH-Chapter 3 72

Traffic. Signal. Test class ñ The only property of a Traffic. Signal. Test properties ñ Traffic. Signal to be tested. ñ Traffic. Signal. Test function is to test the Traffic. Signal. ñ Specify a single command for the class: public void run. Test () Test a Traffic. Signal. May 2004 NH-Chapter 3 73

Traffic. Signal. Test class ñ How does the Traffic. Signal. Test get a Traffic. Signal to test? ñ Traffic. Signal could be an argument, either to Traffic. Signal. Test constructor or to method run. Test; ñ Traffic. Signal could be created by Traffic. Signal. Test, either in its constructor or in the method run. Test May 2004 NH-Chapter 3 74

Traffic. Signal. Test class Traffic. Signal. Test { private Traffic. Signal signal; the object to test // //Create a Traffic. Signal. Test public Traffic. Signal. Test () { signal = new Traffic. Signal(); } // Run the test. public void run. Test () { } } May 2004 NH-Chapter 3 75

The initializing class /** * A simple test system for the class Traffic. Signal. */ public class Test { /** * Run a Traffic. Signal test. */ public static void main (String[] argv) { Traffic. Signal. Test test; test = new Traffic. Signal. Test(); test. run. Test(); } May 2004 } NH-Chapter 3 76

Writing tests ñ Use private methods testing each feature of Traffic. Signal. ñ Place invocations of these methods in run. Test() May 2004 NH-Chapter 3 77

test. Initial. State private void test. Initial. State () { System. out. println("test. Initial. State: "); System. out. println( "Initial light: " + signal. light()); } public void run. Test () { test. Initial. State(); } ñ May run test, getting misleading correct results; class Traffic. Signal has only been stubbed. May 2004 NH-Chapter 3 78

Traffic. Signal constructor and query ñFor class Traffic. Signal need to implement ñTraffic. Signal constructor ñQuery light: test. Initial. State invokes it. public Traffic. Signal () { light = Traffic. Signal. GREEN; } //initial state public int light () { return light; } ñ Run the test, getting correct result because we have correctly implemented the constructor and query. May 2004 NH-Chapter 3 79

Testing command change ñ Need to build a test for the command change. ñ give the command at least three times and see light cycle from green back to green. ñ Put this test in its own method and invoke it from run. Test: public void run. Test () { test. Initial. State(); test. Change(); } May 2004 NH-Chapter 3 80

Testing command change private void test. Change () { System. out. println("test. Change: "); System. out. println("Starting light: " + signal. light()); signal. change(); System. out. println("After 1 change: " + signal. light()); signal. change(); System. out. println("After 2 changes: " + signal. light()); signal. change(); System. out. println("After 3 changes: " + signal. light()); } May 2004 NH-Chapter 3 81

Testing command change ñRecompiling and running Traffic. Signal. Test produces: test. Initial. State: Initial light: 0 test. Change: Starting light: 0 After 1 change: 0 After 2 changes: 0 After 3 changes: 0 ñ Recall, change() is stubbed as a do-nothing method. May 2004 NH-Chapter 3 82

Implementing command change public void change () { light = (light + 1) % 3; } ñ Recompiling and running produces successful test. May 2004 NH-Chapter 3 83

Traffic. Signal and Traffic. Signal. Test ñ Have simple test system for the class Traffic. Signal: ñ Can modify existing implementation, ñ Can add new tests to system, ñ Existing tests will help ensure that additions or modifications don’t break implementation. May 2004 NH-Chapter 3 84

Static methods ñ Methods not dependent on the state of an object. ñ Defined as static, ñ Associated with the class rather with a class instance. May 2004 NH-Chapter 3 85

Static methods ñ Predefined class Math methods are all static. ñ Math includes a square root function specified as: public static double sqrt (double a) The positive square root of the specified value. May 2004 NH-Chapter 3 86

Static method invocation ñ A static function is invoked by prefixing the name of the class rather than the name of a class instance. ñ Diagonal method for Rectangle is written as: public double diagonal () { double a = (double)(length*length + wi return Math. sqrt(a); } May 2004 NH-Chapter 3 87

Final features ñClass named constants are defined as static final: public static final int GREEN = 0; ñ Specification static implies that feature is associated with the class not with an instance of the class. ñ Keyword final means that value to which identifier is bound cannot be changed. ñ Use class name when referring to feature: light = Traffic. Signal. GREEN; May 2004 NH-Chapter 3 88

Summary ñ designing with objects. ñ ask what should the object know and what should the object do. ñ enumerate the “knowing responsibilities” and the “doing responsibilities” of the object. May 2004 NH-Chapter 3 89

Summary ñ Object responsibilities are determined by the object’s role in supporting the functionality of the system. ñ System functionality is distributed to the comprising objects by assigning a set of responsibilities to each object. May 2004 NH-Chapter 3 90

Summary ñ “Knowing responsibilities” translate to queries when the object is defined. ñ “Doing responsibilities” translate into queries or commands. ñ Itemizing an object’s responsibilities determines the object’s features and its relationship to other objects that comprise the system. May 2004 NH-Chapter 3 91

Summary ñ We developed several examples in which one object acts as client to another. ñ Client object was provided with a reference to a server as a method argument. ñ Client was then able to use server by invoking its methods. May 2004 NH-Chapter 3 92

Summary ñA command invocation is a form of statement. ñThe format for invoking a command is object. command (arguments); ñ Processor executes method body associated with command, which generally results in the object changing state. May 2004 NH-Chapter 3 93

Summary ñA query invocation is a form of expression, since it computes and returns value. ñThe format is similar to a command invocation: object. query (arguments) May 2004 NH-Chapter 3 94

Summary ñA constructor invocation creates a new object, and returns a reference to the newly created object. ñThe format is new class (arguments) May 2004 NH-Chapter 3 95

Summary ñ When a method with formal parameters is invoked, ñ method variable is allocated for each formal parameter ñ Method initialized with the argument provided by the client. ñ A local variable is another kind of method variable. ñ Local variables are created when a method is invoked ñ used to hold intermediate results needed during the computation. May 2004 NH-Chapter 3 96

Summary ñ Method variables are different from instance variables. ñ Instance variables ñ contain data that is part of the object’s state. ñ They are created when the object is created, ñ should always contain a meaningful value. ñ Method variables ñ created when a method is invoked, ñ contain values that are used only for a specific computation. May 2004 NH-Chapter 3 97

Summary ñ Developed a simple but complete system containing ñ a model object ñ user interface object. ñ To complete program, introduced a class with a single method named main. May 2004 NH-Chapter 3 98

Summary ñ main is the method that is executed when the program is run. ñ Its only function is to create the initial objects and get the system started. May 2004 NH-Chapter 3 99

Summary ñ In example, ñ main creates a model object , ñ main creates user interface object, ñ main “starts” user interface, passing it model as argument. May 2004 NH-Chapter 3 100

Summary ñ We concluded with a brief introduction to unit testing. ñ To reduce time spent debugging and improve programmer efficiency, we adopt a test-driven implementation strategy. ñ Idea: develop a test for each feature or bit of functionality before implementing the feature or adding the functionality. May 2004 NH-Chapter 3 101

Summary ñ We construct a class to be used to test another existing class. ñ An instance of testing class invokes commands and queries of object under test, and displays information about its state. ñ By comparing actual results with expected results we can determine if the object under test behaves correctly. May 2004 NH-Chapter 3 102
- Slides: 103