Implementing a simple class

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 6 Conditions. This chapter discusses n Conditions and conditional statements. n Preconditions, postconditions, and class invariants. n Boolean.
Chapter 4 Specification of a simple class. This chapter discusses How to write the specifications for a class.  The precise description of features common.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Data types, declarations, and expressions in Java.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
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.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Lecture 4 Types & Expressions COMP1681 / SE15 Introduction to Programming.
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.
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.
 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,
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
PROCESSING Numeric Types. Objectives Be able to … Explain the difference between a literal, a variable and a constant Declare numeric variables and constants.
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.
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.
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
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.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
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.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Java Primer 1: Types, Classes and Operators
Lecture 2: Data Types, Variables, Operators, and Expressions
Object Oriented Programming
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Lecture Set 4 Data Types and Variables
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Type Conversion, Constants, and the String Object
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 6 Methods: A Deeper Look
Chapter 2: Basic Elements of Java
Building Java Programs
Chapter 6 Conditions.
Building Java Programs Chapter 2
Expressions and Assignment
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.
Chapter 2 Programming Basics.
Building Java Programs
Object Oriented Programming in java
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Primitive Types and Expressions
Classes, Objects and Methods
Building Java Programs Chapter 2
Names of variables, functions, classes
Presentation transcript:

Implementing a simple class 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.

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.

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.

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

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

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

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

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)

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

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;

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

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.

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 = 3.1416; public static final int MIN_VOLUME = 1;

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

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

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

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. e.g., Suppose 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 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

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

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.

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. Initializes the component variables of the object. public Counter () { tally = 0; }

Class Counter implemented

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)

Using parameters & automatic variables (cont.)

Back to the 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.)

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

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.

Class Explorer implemented

Class Explorer implemented

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

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

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;

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

Local vs Instance Variables

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)