1 / 72

Chapter 2: Defining a Simple Class

Chapter 2: Defining a Simple Class. Object Interaction: Clients and Servers. Objectives: After studying this chapter you should understand the following: the client-server relationship; the purpose of a class specification; the purpose of a class implementation;

candra
Télécharger la présentation

Chapter 2: Defining a Simple Class

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 2: Defining a Simple Class

  2. Object Interaction: Clients and Servers • Objectives: After studying this chapter you should understand the following: • the client-server relationship; • the purpose of a class specification; • the purpose of a class implementation; • the function of statements in a program; • the function of arithmetic expressions in a program; • the meaning and use of an assignment statement; • the role of parameters in the specification of a method; • the role of comments in programs. NH-Chapter 2

  3. Object Interaction: Clients and Servers • Also, you should be able to: • write the specification of a simple class; • implement a simple class; • invoke an object’s methods; • construct a simple static diagram; • construct a simple interaction diagram describing the interaction of two objects. • write and evaluate arithmetic expressions; • write legal return statements; • write legal assignment statements; • develop a javadoc document for the client. NH-Chapter 2

  4. Clients and Servers • Recall: • an object has features: queries and commands. • objects cooperate to produce a problem solution. NH-Chapter 2

  5. server before executing command server after executing command Client and Server relationship query Piece Player currentSquare color white color white rank queen userControlled yes d1 square d1 … … client response server command Piece Player color white moveTo(c2) color white rank queen userControlled yes square d1 … … client Piece color white rank queen square c2 … NH-Chapter 2

  6. Clients and Servers • Object A uses object B • object A is termed the client, and object B is the server. • A client queries and commands a server. NH-Chapter 2

  7. Clients and Servers • Example: chess playing program. • Client Player, Server Piece • Player object queries Piece object to determine its location, • Player object commands Piece to move to new location on board. NH-Chapter 2

  8. Server specification and Implementation • Client need only know server’s features and use. • Object specification (interface): definition of object’s features, as seen by its clients. • The implementation provides the “internals” that actually make up the features. NH-Chapter 2

  9. Example of Client specification for Counter • Start listing its responsibilities: • Class: Counter • queries: • currentCount the current value of count, a non-negative integer • commands: • reset set the value of count to 0 • incrementCount increment the value of count by 1 NH-Chapter 2

  10. Defining class Counter in Java • package counters; • /** • * A simple integer counter. • */ • public class Counter { • } Definitions of features goes here. NH-Chapter 2

  11. Specifying a Method for a query • /** • * The number of items counted. • */ • publicint currentCount () { • } Name of method. Type of value returned by query. Method implementation goes here. NH-Chapter 2

  12. Specifying a Method for a command • /** • * The number of items counted. • */ • publicvoid incrementCount () { • } Name of method. Type of value returned by command. Method implementation goes here. NH-Chapter 2

  13. Class constructor • constructor: a class’ method used to create and initialize an object. Name of method. • /** • * Create a new Counter, with the count initialized to 0 • */ • public Counter () { • } Method implementation goes here. • Note: name of class constructor is the same as the name of the class. NH-Chapter 2

  14. Static diagram of the class Counter Counter + int currentCount() + void incrementCount() + void reset() NH-Chapter 2

  15. 3. the result of myCounter executing the method is that the value of the current count is delivered to the client. Invoking queries • client’s reference object to Counter:myCounter • To query myCounter for current value of count: myCounter.currentCount() server client Counter myCounter 4 int count myCounter.currentCount() public int currentCount () { . . 4 } 2. object myCounter performs actions as 1. client invokes the method prescribed by the method definition. currentCount of the object myCounter. NH-Chapter 2

  16. Server’s state Before command client Counter myCounter 4 int count 2. myCounter performs actions as prescribed by method myCounter.reset(); public void reset { . . } 1. client invokes the method Server’s state after command reset of the object myCounter. Counter myCounter 0 int count . public void reset { . . } . } Invoking commands • client’s reference object to Counter:myCounter • To command myCounter to reset, myCounter.reset(); NH-Chapter 2

  17. Client Counter Interaction diagrams • client object interacting with a Counter. object queries Counter for current count, and then give Counter command reset. currentCount() the object is active executing the method currentCount count time reset() NH-Chapter 2

  18. Implementing class data • Counter needs current value of count. • Define only one instance variable: syntax to use privatevariableTypevariableName; • Variable definition is included in class: public class Counter { private int count; // current count … } NH-Chapter 2

  19. Counter object showing instance variable Counter Value of variable at some time 10 Type of variable int count Name of variable Instance variable Counter - int count + int currentCount() + void incrementCount() + void reset() Static diagram of class Counter, showing instance variable NH-Chapter 2

  20. Implementing functionality • For each method provide algorithm • set of instructions for processor to carrys out. • Algorithm is described via Java statements: • statement: a language construct that describes an action for the processor to execute. NH-Chapter 2

  21. Implementing query currentCount • Method must deliver value stored in variable count. • Use return statement: return count; /** * The number of items counted. */ publicint currentCount () { return count; } NH-Chapter 2

  22. Return statement and expressions • The general form of a return statement is • Expression : language construct that describes how to compute a particular value. • Processor evaluates expression to produce a value. return expression; NH-Chapter 2

  23. variableName = expression; LHS RHS Implementing simple commands:Assignment statement • A command modifies state of the object. • Use an assignment statement: • instructs processor to compute a value and store it in a variable. • Processor executes assignment in two steps: • computes the value by the expression on RHS; • stores value in variable on LHS, replacing previous value. NH-Chapter 2

  24. Implementing command reset • want to store 0 in the variable count. /** * Reset the count to 0. */ publicvoid reset () { count = 0; } NH-Chapter 2

  25. Implementing the command incrementCount • want to update count to current value in count plus one. • Use count on LHS, and • Use the expression : count + 1 on RHS /** * Increment the count by 1. */ publicvoid incrementCount () { count = count + 1; } NH-Chapter 2

  26. Implementing constructor • instance variable count must be set to 0 in the instance creation. /** * Create a new Counter, with the count initialized to 0. */ public Counter () { count = 0; } NH-Chapter 2

  27. Arithmetic expressions • Expressions that evaluate to integer and floating point values. • Can be built by combining literals and variable names with arithmetic operators • + addition • - subtraction • * multiplication • / division • % remainder NH-Chapter 2

  28. Unary operators: “+” and “-” • assume that i1, is anint variables containing 10 +3  3 -3 -3 + i1 10 - i1 -10 NH-Chapter 2

  29. Division operator • “/” denotes division when applied to two floating point operands, but integer quotient when applied to two integer operands. 2.0/4.0  0.5 2/4  0 5.0/4.0  1.25 5/4  1 NH-Chapter 2

  30. Remainder operator % • Primarily used with integer operands 10 % 5  0 10 % 3  1 10 % 6  4 10 % 11  10 NH-Chapter 2

  31. Mixed type expressionsNumeric promotion • Mixed Operands: • what happens if one operand is int and the other double, • int operand is converted (promoted) to a double representing same value 7 / 2.0  7.0 / 2.0  3.5 i1 * 0.5  10 * 0.5  10.0 * 0.5  5.0 NH-Chapter 2

  32. Operator precedence • What is the order of evaluation in • Unary + and – have higher precedence than binary operators. • *, /, %have higher precedence than operators +,- 5 + 10 * 2 NH-Chapter 2

  33. Operator precedence • If two operators have equal precedence, operations are performed left to right. i.e. 10 / 5 * 3 = 6 • Parentheses are used to override precedence. i.e. 10 / ( 5 * 3) NH-Chapter 2

  34. Casting • Occasionally must convert a value to a different type to perform certain operations. • Syntax: (type) expression 10/40 = 0 (double)10/(double)40 = 0.25 10.0/40.0 = 0.25 (int)10.0/(int)40.0 = 0 • Cast operators have higher precedence than arithmetic operators. NH-Chapter 2

  35. A simple green-yellow-red Traffic signal • Features: public TrafficSignal () Create a new TrafficSignal, initially green. publicint light () The light currently on. publicvoid change () Change to the next light. NH-Chapter 2

  36. Traffic signal implementation • Instance variable: int light • represent possible lights with integers: • 0 for green, 1 for yellow, 2 for red. • To isolate client from choice of values for light, use named class constants NH-Chapter 2

  37. Named class constants • publicclass TrafficSignal { • /** • * The green signal light. • */ • publicstaticfinalint GREEN = 0; • /** • * The yellow signal light. • */ • publicstaticfinalint YELLOW = 1; • /** • * The red signal light. • */ • publicstaticfinalint RED = 2; • … • } NH-Chapter 2

  38. Implementing constructor • /** • * Create a new TrafficSignal, initially green. • */ • public TrafficSignal () { • light = TrafficSignal.GREEN; • } NH-Chapter 2

  39. Implementing command change • /** • * Change to the next light. • */ • publicvoid change () { • light = (light + 1) % 3; • } • Note: remainder by 3 will yield values 0, 1, or 2 NH-Chapter 2

  40. Methods with parameters • Often client must provide additional data when invoking a constructor or method. • Additional data provided are parameters. NH-Chapter 2

  41. Methods with parameters • Example: model a Playing card. • The constructor needs two parameters: • suit • Rank • As the client must specify which card to create. NH-Chapter 2

  42. parameters Constructor with parameters • public PlayingCard (int suit , int rank) { Parameter type Parameter name NH-Chapter 2

  43. Invoking constructor with parameters • Client invokes constructor providing two int values • One for suit • Another for rank • This invocation will create a PlayingCard with • suit: spades • rank (value of card) : 3 new PlayingCard(4, 3) NH-Chapter 2

  44. Executing constructor with parameters Method variables • When client invokes constructor, • Two int method variables are created: • named suit and rank • initialized with 4, and 3 respectively. • lifetime of method variables: constructor execution . • destroyed at completion of execution of constructor. • Lifetime of object’s instance variables : object lifetime . new PlayingCard(4, 3) NH-Chapter 2

  45. Implementing PlayingCard constructor • PlayingCard has two instance variables: private int suit; private int rank; • Initialize them in constructor, using client’s values. • Client’s values are in method variables: suit, rank NH-Chapter 2

  46. Implementing PlayingCard constructor • The following implementation will not work: • public PlayingCard (int suit, int rank) { • suit = suit; • rank = rank; • } • In body of method, names suit and rank refer to method variables only. NH-Chapter 2

  47. Implementing PlayingCard constructor • The keyword this refers to object being constructed. • this.suit refers to its instance variable suit • this.rank refers to its instance variable rank. public PlayingCard (int suit, int rank) { this.suit = suit; this.rank = rank; } NH-Chapter 2

  48. Java in detail: arithmethic expressions Simple expressions • Literals 0 7 23 0.5 2.0 3.14159 2.4e-23 • Variable names • It denotes value currently stored in variable. • int i1 = 10; int i2 = -20; int i3 = 30; • double d1 = 2.5; double d2 = 0.5; • //evaluating them produces their values: • i1  10 i2  -20 i3  30 • d1  2.5 d2  0.5 NH-Chapter 2

  49. Java in detail: arithmethic expressions Operators • Expressions can be combined with operators to form more complicated expressions. i1 / -3  -3 -7 / 2  -3 i1 % -3  1 -7 % 2  -1 NH-Chapter 2

  50. Java in detail: arithmethic expressions Numeric promotion • Operands for binary and unary operators are automatically converted to similar values of a different type when necessary. 7 / 2.0  7.0 / 2.0  3.5 i1 * 0.5  10 * 0.5  10.0 * 0.5  5.0 NH-Chapter 2

More Related