Presentation is loading. Please wait.

Presentation is loading. Please wait.

Implementing a simple class

Similar presentations


Presentation on theme: "Implementing a simple class"— Presentation transcript:

1 Implementing a simple class
Chapter 5 Implementing a simple class

2 This chapter discusses
Implementing class definitions. How to store data in an object and how to write method bodies. Basics of statements and expressions.

3 Instance Variables Objects store information in variables.
variable: a portion of memory reserved for storing a value. instance variable: a variable that is a permanent part of an object; memory space for the variable is allocated when the object is created; variable exists as long as the object exists.

4 Instance Variables (cont.)
Instance variable declaration: private variableType variableName; Should be “outside” any method Principle of “information hiding” -- information should not be directly available to clients; clients should access information only through queries and/or commands.

5 Back to the Counter class
Remember that the class needed to ‘Know’: the value of count. To “implement” this responsibility, we declare an instance variable called tally public class Counter { private int tally; } // end of class Counter

6 Back to the Counter class
the value of tally is not directly accessible to clients clients will have to “access” this through queries and/or commands

7 Back to the Explorer class
‘Knowing’ responsibilities translate to the declaration of the following instance variables: public class Explorer { private String playerName; private rooms.Room room; private int strengthPoints; private int staminaPoints; } // end of class Explorer

8 Back to the Explorer class
Note the use of identifier names to “self-document” the component variables Note the way room is illustrated; its value is a reference to an object of class Room

9 Constructors Every constructor should insure that all of a newly created object’s instance variables are initialized appropriately. Might involve creating objects and assigning references to these objects (for instance variables that do not have primitive types)

10 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: “Encode” the suits using int values spade=4 heart=3 diamond=2 club=1

11 Named constants (cont.)
You can attach names to these values, and then refer to them by name. public final static int SPADE = 4; public final static int HEART = 3; public final static int DIAMOND = 2; public final static int CLUB = 1;

12 Named constants (cont.)
Syntax: public final static type identifier = constantExpression ; public static final int MAX_SCORE = 100 ; public static final double INTEREST_RATE = 0.05 ; public static final String COURSE_NAME = “CS_6001” ;

13 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.

14 Named constants (cont.)
magic number: a literal without an associated (descriptive) name; avoid magic numbers! By convention, we use upper-case identifiers for named constants. public static final double PI = ; public static final int MIN_VOLUME = 1;

15 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. public void reset() { statement1; statement2; } //end of reset

16 Implementing functionality (cont.)
One “flavor” of queries (the “natural” queries) perform one action, which is to give the value of a instance variable, e.g., public int count () { return tally; }

17 Implementing functionality (cont.)
Every query ends with the execution of a return statement. Syntax: return expression ; return tally; return name; return Math.sqrt( 2.0 );

18 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;

19 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.

20 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. e.g., Suppose a==5 and b==(-4) +a == 5, -a == (-5), +b == (-4), -b == 4

21 Operators (cont.) binary (dyadic) operators: combine 2 expressions (operands). Operators include ‘+’, ‘-’, ‘*’, ‘/’, ‘%’. The not-so-obvious operators: ‘*’- multiplication ‘/’- division ‘%’- modular division (remainder).

22 Operators (cont.) The “/” denotes division when applied to two double operands, but integer quotient when applied to two int operands. 2.0/4.0 == 0.5 2/4 == 0 5.0/4.0 == 1.25 5/4 == 1

23 Operator Precedence If i1==10, what is the order of evaluation of i * 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)

24 Casting (type) expression (int) Math.PI
Occasionally we must convert a value to a different type to perform certain operations. Syntax: (type) expression Example: (int) Math.PI

25 Casting (cont.) 10/40 == 0 Consider these expressions:
(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.

26 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;

27 Implementing the constructor
The constructor is invoked when creating a new instance of an object. Initializes the component variables of the object. public Counter () { tally = 0; }

28 Class Counter implemented

29 Using parameters & automatic variables
Parameters “receive” values (actual arguments) that are used in performing computations. 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 (e.g., hitStrength)

30 Using parameters & automatic variables (cont.)

31 Back to the Explorer class
public void changeName( String newName ) { playerName = newName; } public void move( rooms.Room newRoom ) { location = newRoom;

32 The Explorer constructor
public Explorer ( String name, rooms.Room location, int hitStrength, int stamina ) { playerName = name; room = location; strengthPoints = hitStrength; staminaPoints = stamina; }

33 Invoking a method: acting as a client
Consider the command strike public void strike (denizens.Denizen monster) { … }

34 Invoking a method: acting as a client (cont.)

35 Invoking a method: acting as a client (cont.)
To change the state of the monster’s stamina, invoke the takehit command Recall how to invoke a method: object.command( arguments ) Example: public void strike( Denizen monster ){ monster.takeHit( strengthPoints ); }

36 Invoking a method: acting as a client (cont.)
The strike command has both a server and a client dimension: It is a server-side resource for whichever object invokes the strike command of the Explorer class. It invokes a resource ( the takeHit command) as a client of a Denizen object.

37 Class Explorer implemented

38 Class Explorer implemented

39 More on methods Arguments used in a method invocation are, in general, expressions. A method invocation must provide an argument of the appropriate type for each parameter, e.g., public void move( int direction, double distance ) requires an int and double arguments object.move(90, 2.5);

40 More on methods (cont.) A command invocation is a form of a statement.
A query is a form of expression, since it represents a value. Examples: i = c.count(); i = c.count() + 10; c.reset(); c.stepCount();

41 Local variables local variables: automatic variables created as part of a method execution, used to hold intermediate results needed while the method is active. Not initialized by the client; must be initialized within the method itself: Syntax: type identifier; type identifier = expression;

42 Cash register class tax and discount are local automatic variables
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 Local vs Instance Variables

44 We 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)


Download ppt "Implementing a simple class"

Similar presentations


Ads by Google