Chapter 5 Implementing a simple class. This chapter discusses n Implementing class definitions. n How to store data in an object and how to write method.

Slides:



Advertisements
Similar presentations
Chapter 6 Conditions. This chapter discusses n Conditions and conditional statements. n Preconditions, postconditions, and class invariants. n Boolean.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Chapter 4 Specification of a simple class. This chapter discusses How to write the specifications for a class.  The precise description of features common.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
JavaScript, Third Edition
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
LESSON 6 – Arithmetic Operators
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Arithmetic Operations. Review function statement input/output comment #include data type variable identifier constant declaration.
Integer numerical data types. The integer data types The integer data types use the binary number system as encoding method There are a number of different.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
CHAPTER 2 COMPONENTS OF A PROGRAMMING LANGUAGE I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Executable Statements 1. Def. Executable statements are instructions to the computer to perform specific tasks. 2. Two examples: method calls and assignment.
Chapter 4 Specification of a simple class. This chapter discusses n How to write the specifications for a class. u The precise description of features.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Doing math In java.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Chapter 7 Programming by contract: preconditions and postconditions.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 Section 3.2b Arithmetic Operators Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 4 Assignment Statement
Operators and Expressions
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE
Java Primer 1: Types, Classes and Operators
Lecture 2: Data Types, Variables, Operators, and Expressions
Object Oriented Programming
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Chapter 3 Assignment Statement
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 4 : Conditionals
Lecture 3 Expressions Richard Gesick.
Chapter 2: Basic Elements of Java
Chapter 6 Conditions.
Expressions and Assignment
Implementing a simple class
Data Types and Expressions
Chapter 2 Programming Basics.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Primitive Types and Expressions
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

Chapter 5 Implementing a simple class

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.

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.

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.

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.

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

Constructors n Every constructor should ensure that all of a newly created objects component variables are initialized appropriately.

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

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

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.

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.

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

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

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.

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

Operators (cont.) n binary (dyadic) operators: combine 2 expressions (operands). Operators include +, -, *, /, %. n 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 -> /4 -> 1

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

Casting n Occasionally we must convert a value to a different type to perform certain operations. Syntax: (type) expression

Casting (cont.) n Consider these expressions: 10/40 = 0 (double)10/(double)40 = /40.0 = 0.25 (int)10.0/(int)40.0 = 0 n Cast operators have higher precedence than arithmetic operators.

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

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

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

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) {…}

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); }

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.

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

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;

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;

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.

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)

Glossary

Glossary (cont.)