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 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; ñ 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. May 2004 NH-Chapter 2 1
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. May 2004 NH-Chapter 2 2
Clients and Servers ñ Recall: ñ an object has features: queries and commands. ñ objects cooperate to produce a problem solution. May 2004 NH-Chapter 2 3
Client and Server relationship query Piece Player color user. Controlled white current. Square yes d 1 color white rank queen square … d 1 … client response server command Piece Player color user. Controlled white move. To(c 2) yes white rank queen square … client color d 1 … server before executing command server after executing command Piece color white rank queen square c 2 … May 2004 NH-Chapter 2 4
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. May 2004 NH-Chapter 2 5
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. May 2004 NH-Chapter 2 6
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. May 2004 NH-Chapter 2 7
Example of Client specification for Counter ñ Start listing its responsibilities: ñ Class: Counter ñ queries: ñ current. Count the current value of count, a non-negative integer ñ commands: ñ reset the value of count to 0 ñ increment. Count increment the value of count by 1 May 2004 NH-Chapter 2 8
Defining class Counter in Java package counters; /** * A simple integer counter. */ public class Counter { Definitions of features goes here. } May 2004 NH-Chapter 2 9
Specifying a Method for a query Name of method. Type of value returned by query. /** * The number of items counted. */ public int current. Count () { Method implementation goes here. } May 2004 NH-Chapter 2 10
Specifying a Method for a command Name of method. Type of value returned by command. /** * The number of items counted. */ public void increment. Count () { Method implementation goes here. } May 2004 NH-Chapter 2 11
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. May 2004 NH-Chapter 2 12
Static diagram of the class Counter +int current. Count() +void increment. Count() +void reset() May 2004 NH-Chapter 2 13
Invoking queries ñ client’s reference object to Counter: my. Counter ñ To query my. Counter for current value of count: my. Counter. current. Count() server client Counter int count my. Counter. current. Count() public 4 current. Count () { . . 4 1. client invokes the method current. Count of the object my. Counter. int my. Counter } 2. object my. Counter performs actions as prescribed by the method definition. 3. the result of my. Counter executing the method is that the value of the current count is delivered to the client. May 2004 NH-Chapter 2 14
Invoking commands ñ client’s reference object to Counter: my. Counter ñ To command my. Counter to reset, my. Counter. reset(); Counter Server’s state Before command void reset { 2. my. Counter performs actions as prescribed by method my. Counter. reset(); Counter 1. client invokes the method reset of the object my. Counter. May 2004 4 int count public. . } client my. Counter Server’s state after command NH-Chapter 2 my. Counter int count. public. . }. } 0 void reset { 15
Interaction diagrams ñ client object interacting with a Counter. object queries Counter for current count, and then give Counter command reset. Client Counter current. Count() the object is active executing the method time count current. Count reset() May 2004 NH-Chapter 2 16
Implementing class data ñ Counter needs current value of count. ñ Define only one instance variable: syntax to use private variable. Type variable. Name; ñ Variable definition is included in class: public class Counter { private int count; // current count … } May 2004 NH-Chapter 2 17
Counter int Type of variable count 10 Value of variable at some time Name of variable Instance variable Counter object showing instance variable Counter -int count +int current. Count() +void increment. Count() +void reset() Static diagram of class Counter, showing instance variable May 2004 NH-Chapter 2 18
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. May 2004 NH-Chapter 2 19
Implementing query current. Count ñ Method must deliver value stored in variable count. ñ Use return statement: return count; /** * The number of items counted. */ public int current. Count () { return count; } May 2004 NH-Chapter 2 20
Return statement and expressions ñThe general form of a return statement is return expression; ñ Expression : language construct that describes how to compute a particular value. ñ Processor evaluates expression to produce a value. May 2004 NH-Chapter 2 21
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. LHS variable. Name = expression; RHS ñ Processor executes assignment in two steps: 1. computes the value by the expression on RHS; 2. stores value in variable on LHS, replacing previous value. May 2004 NH-Chapter 2 22
Implementing command reset ñ want to store 0 in the variable count. /** * Reset the count to 0. */ public void reset () { count = 0; } May 2004 NH-Chapter 2 23
Implementing the command increment. Count ñ 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. */ public void increment. Count () { count = count + 1; } May 2004 NH-Chapter 2 24
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; } May 2004 NH-Chapter 2 25
Arithmetic expressions ñ Expressions that evaluate to integer and floating point values. ñ Can be built by combining literals and variable names with arithmetic operators ñ+ ññ* ñ/ ñ% May 2004 addition subtraction multiplication division remainder NH-Chapter 2 26
Unary operators: “+” and “-” ñ assume that i 1, is an int variables containing 10 +3 3 -3 + i 1 10 - i 1 -10 May 2004 NH-Chapter 2 27
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 May 2004 NH-Chapter 2 28
Remainder operator % ñ Primarily used with integer operands 10 % 5 10 % 3 10 % 6 10 % 11 May 2004 0 1 4 10 NH-Chapter 2 29
Mixed type expressions Numeric 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 i 1 * 0. 5 10. 0 * 0. 5 May 2004 NH-Chapter 2 5. 0 30
Operator precedence ñWhat is the order of evaluation in 5 + 10 * 2 ñ Unary + and – have higher precedence than binary operators. ñ *, /, % have higher precedence than operators +, - May 2004 NH-Chapter 2 31
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) May 2004 NH-Chapter 2 32
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. May 2004 NH-Chapter 2 33
A simple green-yellow-red Traffic signal ñ Features: public Traffic. Signal () Create a new Traffic. Signal, initially green. public int light () The light currently on. public void change () Change to the next light. May 2004 NH-Chapter 2 34
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 May 2004 NH-Chapter 2 35
Named class constants public class Traffic. Signal { /** * The green signal light. */ public static final int GREEN = 0; /** * The yellow signal light. */ public static final int YELLOW = 1; /** * The red signal light. */ public static final int RED = 2; … } May 2004 NH-Chapter 2 36
Implementing constructor /** * Create a new Traffic. Signal, initially green. */ public Traffic. Signal () { light = Traffic. Signal. GREEN; } May 2004 NH-Chapter 2 37
Implementing command change /** * Change to the next light. */ public void change () { light = (light + 1) % 3; } ñNote: remainder by 3 will yield values 0, 1, or 2 May 2004 NH-Chapter 2 38
Methods with parameters ñ Often client must provide additional data when invoking a constructor or method. ñ Additional data provided are parameters. May 2004 NH-Chapter 2 39
Methods with parameters ñ Example: model a Playing card. ñ The constructor needs two parameters: ñ suit ñ Rank ñ As the client must specify which card to create. May 2004 NH-Chapter 2 40
Constructor with parameters public Playing. Card (int suit , Parameter type May 2004 NH-Chapter 2 int rank) { Parameter name 41
Invoking constructor with parameters ñClient invokes constructor providing two int values ñOne for suit ñAnother for rank new Playing. Card(4, 3) ñ This invocation will create a Playing. Card with ñ suit: spades ñ rank (value of card) : 3 May 2004 NH-Chapter 2 42
Executing constructor with parameters Method variables ñWhen client invokes constructor, new Playing. Card(4, 3) ñ 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. May 2004 NH-Chapter 2 43
Implementing Playing. Card constructor ñ Playing. Card 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 May 2004 NH-Chapter 2 44
Implementing Playing. Card constructor ñ The following implementation will not work: public Playing. Card (int suit, int rank) { suit = suit; rank = rank; } ñIn body of method, names suit and rank refer to method variables only. May 2004 NH-Chapter 2 45
Implementing Playing. Card 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 Playing. Card (int suit, int rank) { this. suit = suit; this. rank = rank; } May 2004 NH-Chapter 2 46
Java in detail: arithmethic expressions Simple expressions ñ Literals 0 7 23 0. 5 2. 0 3. 14159 2. 4 e-23 ñVariable names ñIt denotes value currently stored in variable. int i 1 = 10; int i 2 = -20; double d 1 = 2. 5; double d 2 = 0. 5; //evaluating them produces their values: i 1 10 i 2 -20 d 1 2. 5 d 2 0. 5 May 2004 NH-Chapter 2 int i 3 = 30; i 3 30 47
Java in detail: arithmethic expressions Operators ñ Expressions can be combined with operators to form more complicated expressions. i 1 / -3 -7 / 2 -3 i 1 % -3 May 2004 1 -7 % 2 NH-Chapter 2 -1 48
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. May 2004 7 / 2. 0 7. 0 / 2. 0 i 1 * 0. 5 10. 0 * 0. 5 NH-Chapter 2 3. 5 5. 0 49
Java in detail: arithmethic expressions Precedence ñ Operators *, /, and % have higher precedence than binary operators + and -. ñ In an un-parenthesized expression multiplication is done before addition Multiply before adding i 1 + 20 30 i 1 * 10 + 2 10 / 2 + 1 5 + 6 / 10 100 + 2 5+1 5+0 6 5 102 (-5) + 10 5 i 1 + 10 * 2 - 5 + i 1 May 2004 NH-Chapter 2 50
Java in detail: arithmethic expressions Associativity ñ Binary operators are left associative: when expression contains two operators with equal precedence, operations are performed left to right. Left operator before right i 1 / 5 * 2 May 2004 2*2 10 - 4 - 3 6 -3 i 1/20 * 2 10/20 * 2 2*i 1/20 2*10/20 20 / i 1*2 20/20 20 / 10*2 NH-Chapter 2 4 3 0*2 1 2*2 0 4 51
Java in detail: Concatenation ñ For operands Strings: binary operator “+” denotes string concatenation. string 1 + string 2 ñ Evaluates to a String containing characters of string 1 with characters of string 2 appended. "abc" + "def" May 2004 NH-Chapter 2 "abcdef" 52
Java in detail: Concatenation ñ If one operands of “+” is a String and the other isn’t, the non. String operand will be converted to a String, and concatenation performed. int i = 23; May 2004 "abc" + i "abc 23“ i+"" "2*i=" + 2*i 2+i+"!" "!"+2+i "23 " "2*i=46" "25!" ( “+” is left associative!) "!223" NH-Chapter 2 53
Java in detail: Casting (type)expression (double)i 1 / i 3 10. 0 / 30 (int)d 3 (int)d 4 2 -2 (double)i 1/i 3 10. 0/30 0. 333… (double)0 0. 0 (double)(i 1/i 3) May 2004 (double)10 NH-Chapter 2 0. 333… 54
Java in detail: basic organizational structure ñ package: a collection of closely related classes. ñ compilation unit: a file containing the definition of one or more classes of a package. May 2004 NH-Chapter 2 55
Java in detail: basic organizational structure package A; package B; public class A 1 { … } // end of class A 1 public class B 1 { … } // end of class B 1 class A 3 { … } // end of class A 3 class B 2 { … } // end of class B 2 A 1. java B 1. java package A; package C; public class A 2 { … } // end of class A 2 public class C 1 { … } // end of class C 1 A 2. java May 2004 C 1. java NH-Chapter 2 56
Java in detail: referring to classes in a different package, import statements ñ Via import statement, can refer to a class in another package with by name rather than with its fully qualified name. ñ Two formats for an import statement: import package. Name. class. Name; import package. Name. *; import javax. swing. border. Line. Border; import javax. swing. border. *; May 2004 NH-Chapter 2 57
Java in detail: referring to classes in a different package, import statements ñ Instead of writing : javax. swing. border. Line. Border my. Border; my. Border = new javax. swing. border. Line. Border(my. Color); ñ Write : import javax. swing. border. Line. Border; import javax. swing. border. *; Line. Border my. Border; my. Border = new Line. Border(my. Color); May 2004 NH-Chapter 2 58
Java in detail: package java. lang ñ The predefined package java. lang contains the definitions of a number of commonly used classes. ñ String is a member of java. lang. ñ Do not need to explicitely import this package. Java does it by default. May 2004 NH-Chapter 2 59
Summary ñ Saw how to specify and implement a simple class using the programming language Java. ñ Two objects are related in a fundamental way when one object uses the other: ñ one object queries and command the other. ñ This relation is : client-server relationship. ñ The client object queries and commands the server object. May 2004 NH-Chapter 2 60
Summary ñ Definition of class of which the object is an instance, consists of two parts: ñ Specification: a precise description of object’s features as seen by a client. ñ Implementation: internal mechanisms that enable an object to behave according to its specification. May 2004 NH-Chapter 2 61
Summary ñ Class specification is made up of: ñ method specifications ñ constructor specifications. May 2004 NH-Chapter 2 62
Summary ñ Methods define ñ the specifications ñ the implementation of an object’s features. ñ A method that defines a query returns a value of a given type. ñ A method that defines a command causes object to change state when it is invoked. ñ Constructors are used to create objects and initialize their states. May 2004 NH-Chapter 2 63
Summary ñ Implementing a class involves ñ writing data descriptions for data stored in class instances, and ñ writing method bodies that define the actions the processor performs when the methods are invoked. May 2004 NH-Chapter 2 64
Summary ñ An object’s data are stored in instance variables. ñ Instance variables are created when object is created. ñ Instance variables are part of the object’s implementation ñ An instance variable is created with a variable declaration: private variable. Type variable. Name; May 2004 NH-Chapter 2 65
Summary ñ A method body is made up of a sequence of statements that implement the method algorithm. ñ Statements describe actions the processor performs when executing the method. ñ When method is invoked, processor executes statements one after another, in the order in which they appear in the method body. May 2004 NH-Chapter 2 66
Summary ñ Return statement has the form: return expression; ñ Assignment statement has the form: variable = expression; May 2004 NH-Chapter 2 67
Summary ñ An expression describes how a value is to be computed. ñ Arithmetic expressions, in particular, produce numeric values when they are evaluated. ñ Both return statements and assignment statements include expressions. May 2004 NH-Chapter 2 68
Summary ñ Parameters in method or constructor: indicate that client provide information when the method or constructor is invoked. ñ Arguments: values client supplies when invoking method or constructor. May 2004 NH-Chapter 2 69
Summary ñ Method variables: variables allocated for each parameter and initialized with the argument provided by the client. ñ Method variables: created when the method is invoked, and deallocated when execution of method is complete. May 2004 NH-Chapter 2 70
Summary ñ Packages: groups of class definitions that make up a program. ñ Classes defined in same package are related to each other: instances of these classes can access each other by default. ñ If a class is to be visible throughout the entire system, it must be explicitly labeled as public. ñ Class definitions are written in source files. ñ Each file can contain definition of at most one public class. May 2004 NH-Chapter 2 71
- Slides: 72