Download presentation
Presentation is loading. Please wait.
Published byNathaniel Webster Modified over 11 years ago
1
Chapter 5 Implementing a simple class
2
This chapter discusses n Implementing class definitions. n How to store data in an object and how to write method bodies. n Basics of statements and expressions.
3
Component Variables n Objects store information in variables. n variable: a portion of memory reserved for storing a value. n 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.
4
Component Variables (cont.) n Syntax: private variableType variableName; n Information should not be directly available to clients; clients should access information only through queries and commands.
5
Back to the Counter class n Remember that the class needed to Know: u 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.
7
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
9
Constructors n Every constructor should ensure that all of a newly created objects component variables are initialized appropriately.
10
Named constants n Sometimes data types provided by Java do not adequately represent something you wish to model. n Example: Card suit--spade, heart, diamond, club. n Solution: Represent a suit with integers. spade=4 heart=3 diamond=2 club=1
11
Named constants (cont.) n You can attach names to these values, and then refer to them by name. n 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
12
Named constants (cont.) n Now you can refer to the values by their names. if (discard.suit() == Card.SPADE)… n named constant: a value that has an identifier (name) associated with it; the associated identifier can be used to refer to the value. n magic number: a literal without an associated (descriptive) name; avoid magic numbers! n By convention, we use upper-case identifiers for named constants.
13
Implementing functionality n statement: a language construct that describes an action for the processor to perform. n The method body consists of a sequence of one or more statements.
14
Implementing functionality (cont.) n Queries perform one action which is to give the value of a component variable. n Example: public int count () { return tally; } n Every query ends with the execution of a return statement. Syntax: return expression
15
Implementing functionality (cont.) n Explorer Queries: public String name () { return playerName; } public rooms.Room location () { return room; } public int strength () { return strengthPoints; } public int stamina () { return staminaPoints; }
16
Arithmetic expressions n 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.
17
Operators n unary (monadic) operators: involves manipulation of one value. n 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
18
Operators (cont.) n binary (dyadic) operators: combine 2 expressions (operands). Operators include +, -, *, /, %. n The not-so-obvious operators: * - multiplication / - division % - modular division (remainder).
19
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
20
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)
21
Casting n Occasionally we must convert a value to a different type to perform certain operations. Syntax: (type) expression
22
Casting (cont.) n 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 n Cast operators have higher precedence than arithmetic operators.
23
Assignment statement n 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; }
24
Implementing the Constructor n The constructor is invoked when creating a new instance of an object. n It initializes the component variables of the object. public counter () { tally = 0; }
27
Using parameters n Parameters that are passed in are used in making some calculations. public void takeHit (int hitStrength){ staminaPoints = staminaPoints - hitStrength; } n automatic variable: a variable that is created when a method is invoked, and destroyed when the processor finishes executing the method. Example: hitStrength
29
Explorer class public void changeName(String newName) { playerName = newName; } public void move(rooms.Room newRoom) { location = newRoom; }
30
The Explorer constructor public Explorer (String name, rooms.Room location, int hitStrength, int stamina) { playerName = name; room = location; strengthPoints = hitStrength; staminaPoints = stamina; }
31
Invoking a method: acting as a client Consider the command strike. public void strike (denizens.Denizen monster) {…}
33
Invoking a method: acting as a client (cont.) We now want to change the state of the monsters stamina. We use the takehit command to do this. Recall how to invoke a method: object.command (arguments) n Therefore: public void strike (denizens.Denizen monster) { monster.takeHit (strengthPoints); }
34
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.
38
More on methods n Arguments provided in a method are in general expressions. n 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);
39
More on methods (cont.) n A command invocation is a form of a statement. A query is a form of expression, since it produces a value. n Examples: i = c.count(); i = c.count() + 10;
40
Local variables n Local variables are automatic variables created as part of a method execution, used to hold intermediate results needed while the method is active. n They are not initialized by the client. They must be initialized in the method. Syntax: type identifier; type identifier = expression;
41
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.
43
Weve covered n How to write a simple class implementation. n Component variables, named constants, automatic variables, and local variables. n Method bodies. The return statement and the assignment ( = ) statement. n Command and query invocation. object.commandOrQuery(arguments)
44
Glossary
45
Glossary (cont.)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.