Notes
Outline
Chapter 5
Implementing a simple class
This chapter discusses
Implementing class definitions.
How to store data in an object and how to write method bodies.
Basics of statements and expressions.
Component Variables
Objects store information in variables.
variable: a portion of memory reserved for storing a value.
component variable: a variable that is a permanent part of an object; memory space for the variable is allocated when the object is created, and the variable exists as long as the object exists.
Component Variables (cont.)
Syntax:
private variableType variableName;
Information should not be directly available to clients; clients should access information only through queries and commands.
Back to the Counter class
Remember that the class needed to ‘Know’:
the value of count.
We will call this variable tally.
public class Counter {
…
private int tally;
…
} // end of class Counter
Every Counter object will have a component that is an int variable named tally.
Slide 6
Back to the Explorer class
public class Explorer {
…
private String playerName;
private rooms.Room room;
private int strengthPoints;
private int staminaPoints;
…
} // end of class Explorer
Slide 8
Constructors
Every constructor should ensure that all of a newly created object’s component variables are initialized appropriately.
Named constants
Sometimes data types provided by Java do not adequately represent something you wish to model.
Example: Card suit--spade, heart, diamond, club.
Solution: Represent a suit with integers.
spade=4 heart=3 diamond=2 club=1
Named constants (cont.)
You can attach names to these values, and then refer to them by name.
Example:
public final static int SPADE = 4;
public final static int HEART = 3;
public final static int DIAMOND = 2;
public final static int CLUB = 1;
Syntax: public final static type identifier = constantExpression
Named constants (cont.)
Now you can refer to the values by their names.
if (discard.suit() == Card.SPADE)…
named constant: a value that has an identifier (name) associated with it; the associated identifier can be used to refer to the value.
magic number: a literal without an associated (descriptive) name; avoid magic numbers!
By convention, we use upper-case identifiers for named constants.
Implementing functionality
statement: a language construct that describes an action for the processor to perform.
The method body consists of a sequence of one or more statements.
Implementing functionality (cont.)
Queries perform one action which is to give the value of a component variable.
Example:
public int count () {
return tally;
}
Every query ends with the execution of a return statement.
Syntax: return expression
Implementing functionality (cont.)
Explorer Queries:
public String name () {
return playerName;
}
public rooms.Room location () {
return room;
}
public int strength () {
return strengthPoints;
}
public int stamina () {
return staminaPoints;
}
Arithmetic expressions
expression: a language construct that describes how to compute a particular value.
Expressions that evaluate to type byte, short, int, long, float, and double, are collectively called arithmetic expressions.
Operators
unary (monadic) operators: involves manipulation of one value.
Affixing ‘+’ or ‘-’ can be considered a unary operator. Affixing the ‘+’ does nothing.  Affixing the ‘-’ negates the value.
Example: If a = 5 and b =-4
+a = 5, -a =-5, +b =-4, -b = 4
Operators (cont.)
binary (dyadic) operators: combine 2 expressions (operands).
Operators include ‘+’, ‘-’, ‘*’, ‘/’, ‘%’.
The not-so-obvious operators:
‘*’- multiplication
‘/’- division
‘%’- modular division (remainder).
Operators (cont.)
The “/” 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
Operator Precedence
If i1 = 10, what is the order of evaluation in i1 + 10 * 2?
Unary + and – have higher precedence than the binary operators.
*, /, % have higher precedence than the binary operators +,-.
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)
Casting
Occasionally we must convert a value to a different type to perform certain operations.
Syntax: (type) expression
Casting (cont.)
Consider these expressions:
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.
Assignment statement
assignment: a statement that instructs the processor to compute a value and to store it in a variable.
It is denoted by ‘=‘.  Note: The ‘=‘ sign does not  mean mathematical equality.
Syntax:variableName = expression
public void reset() {
tally = 0;
}
public void stepCount () {
tally = tally + 1;
}
Implementing the Constructor
The constructor is invoked when creating a new instance of an object.
It initializes the component variables of the object.
public counter () {
tally = 0;
}
Slide 25
Slide 26
Using parameters
Parameters that are passed in are used in making some calculations.
public void takeHit (int hitStrength){
staminaPoints = staminaPoints - hitStrength;
}
automatic variable: a variable that is created when a method is invoked, and destroyed when the processor finishes executing the method.
Example: hitStrength
Slide 28
Explorer class
public void changeName(String newName)
{
playerName = newName;
}
public void move(rooms.Room newRoom) {
location = newRoom;
}
The Explorer constructor
public Explorer (String name,      rooms.Room location,      int hitStrength,
     int stamina) {
playerName = name;
room = location;
strengthPoints = hitStrength;
staminaPoints = stamina;
}
Invoking a method: acting as a client
Consider the command strike.
public void strike (denizens.Denizen monster) {…}
Slide 32
Invoking a method: acting as a client (cont.)
We now want to change the state of the monster’s stamina.  We use the takehit command to do this.
Recall how to invoke a method: object.command (arguments)
Therefore:
public void strike (denizens.Denizen   monster) {
monster.takeHit (strengthPoints);
}
Invoking a method: acting as a client (cont.)
The strike command is both a server and a client.  It is the server for whatever object invokes the strike command; it is the client when invoking the takeHit command.
Slide 35
Slide 36
Slide 37
More on methods
Arguments provided in a method are in general expressions.
A method invocation must provide an argument of the appropriate type for each parameter. i.e.
public void move(int direction,       double distance)
requires an int and double
object.move(90, 2.5);
More on methods (cont.)
A command invocation is a form of a statement.  A query is a form of expression, since it produces a value.
Examples:
i = c.count();
i = c.count() + 10;
Local variables
Local variables are automatic variables created as part of a method execution, used to hold intermediate results needed while the method is active.
They are not initialized by the client.  They must be initialized in the method.
Syntax: type identifier;
       type identifier =           expression;
CashRegister class
public double netPrice
  (double grossPrice,
   double taxRate,
   double discountRate){
 double tax;
 double discount;
 tax = grossPrice * taxRate;
 discount = grossPrice * discountRate;
 return grossPrice + tax - discount;
}
tax and discount are local automatic variables.
Slide 42
We’ve covered
How to write a simple class implementation.
Component variables, named constants, automatic variables, and local variables.
Method bodies.
The return statement and the assignment (=) statement.
Command and query invocation.
object.commandOrQuery(arguments)
Glossary
Glossary (cont.)