cs 100lecture 61 cs100j lecture 6 n previous lecture –programming concepts n programming by...

16
CS 100 Lecture 6 1 CS100J Lecture 6 CS100J Lecture 6 Previous Lecture Previous Lecture Programming Concepts Programming Concepts Programming by stepwise refinement Programming by stepwise refinement a pattern a pattern sequential refinement sequential refinement case analysis case analysis iterative refinement iterative refinement Use of comments as higher-level statements Use of comments as higher-level statements This Lecture This Lecture Computation and computational power Computation and computational power Abstraction Abstraction Classes, Objects, and Methods Classes, Objects, and Methods References and aliases References and aliases Reading: Reading: Lewis & Loftus, Chapter 4 and Section 5.1 Lewis & Loftus, Chapter 4 and Section 5.1 Savitch, Chapter 4 Savitch, Chapter 4

Upload: jennifer-crawford

Post on 18-Dec-2015

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 1

CS100J Lecture 6CS100J Lecture 6

Previous LecturePrevious Lecture– Programming ConceptsProgramming Concepts

Programming by stepwise refinementProgramming by stepwise refinement– a pattern a pattern

– sequential refinementsequential refinement

– case analysiscase analysis

– iterative refinementiterative refinement

Use of comments as higher-level statementsUse of comments as higher-level statements

This LectureThis Lecture– Computation and computational powerComputation and computational power

– AbstractionAbstraction

– Classes, Objects, and MethodsClasses, Objects, and Methods

– References and aliasesReferences and aliases

– Reading: Reading: Lewis & Loftus, Chapter 4 and Section 5.1Lewis & Loftus, Chapter 4 and Section 5.1 Savitch, Chapter 4Savitch, Chapter 4

Page 2: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 2

ComputationComputation

ProgramProgram Processor follows instructions of programProcessor follows instructions of program

– Allocate variablesAllocate variables– Input and OutputInput and Output– Store a value into a variable (assignment)Store a value into a variable (assignment)– Load a value from a variableLoad a value from a variable– Evaluate expressionsEvaluate expressions– Sequential Execution, Conditional Execution, Sequential Execution, Conditional Execution,

and Iterationand Iteration

Variables

Program

Processor

store load

input output

instructions to be followed

Page 3: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 3

Computational PowerComputational Power

If that’s all there is, where do computers If that’s all there is, where do computers

get their power from?get their power from?

– Hardware Hardware speedspeed A 500 megahertz processor is doing a half a A 500 megahertz processor is doing a half a

billion things a second!billion things a second!

– Linguistic Linguistic abstractionabstraction Programs are organized into hierarchies of Programs are organized into hierarchies of

abstractions so that lengthy computations can abstractions so that lengthy computations can

be described succinctlybe described succinctly

abstraction abstraction

– A named compound thing that can be A named compound thing that can be

manipulated as a unitmanipulated as a unit

– ExamplesExamples:: A group of A group of declarations declarations that go that go

togethertogether

A group of A group of statementsstatements that go together that go together

The subject of this lecture is how to The subject of this lecture is how to

structurestructure programsprograms, but the fundamental , but the fundamental

computational steps computational steps remain the sameremain the same..

Page 4: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 4

AggregationAggregation

Suppose a bank account is represented by Suppose a bank account is represented by

these state variables, e.g.,these state variables, e.g.,

// Bank account.// Bank account.

int balance;int balance; // current balance// current balance

int deposits;int deposits; // deposits to date// deposits to date

int withdrawals;int withdrawals; // withdrawals to date// withdrawals to date

Shortcomings:Shortcomings:

– UnderstandabilityUnderstandability: The relationship of the : The relationship of the

variables to one another is only implicit, not variables to one another is only implicit, not

explicit.explicit.

– ScalabilityScalability: If we want to represent two bank : If we want to represent two bank

accounts, we have to write twice as much:accounts, we have to write twice as much:

// Bank account 1.// Bank account 1.

int balance1;int balance1; // current balance// current balance

int deposits1;int deposits1; // deposits to date// deposits to date

int withdrawals1;int withdrawals1; // withdrawals to date// withdrawals to date

// Bank account 2.// Bank account 2.

int balance2;int balance2; // current balance// current balance

int deposits2;int deposits2; // deposits to date// deposits to date

int withdrawals2;int withdrawals2; // withdrawals to date// withdrawals to date

Page 5: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 5

Goals of AggregationGoals of Aggregation

UnderstandabilityUnderstandability: a way to group variables : a way to group variables

into a new abstraction that makes their into a new abstraction that makes their

relationship to one another explicitrelationship to one another explicit

– Such an abstraction is called a Such an abstraction is called a classclass

– Example: the class Example: the class AccountAccount

ScalabilityScalability: a way to create multiple : a way to create multiple

instances of the abstractioninstances of the abstraction

– Each instance of the abstraction is called an Each instance of the abstraction is called an

objectobject

– Example:Example: account1 account1 andand account2 account2

Page 6: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 6

Class DefinitionsClass Definitions

TemplateTemplate

classclass class-nameclass-name{{

declarationsdeclarations}}

Example:Example:

classclass Account Account{{

int balance;int balance; // current balance // current balanceint deposits;int deposits; // deposits to date // deposits to dateint withdrawals; // withdrawals to dateint withdrawals; // withdrawals to date

}}

DeclarationsDeclarations of a class define of a class define fieldsfields of the of the class that go together to make one thingclass that go together to make one thing

Each class is a type. Whereas Each class is a type. Whereas intint, , doubledouble, and, and booleanboolean are called are called primitive typesprimitive types, classes , classes are not primitive typesare not primitive types

Page 7: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 7

Variables and Values RevisitedVariables and Values Revisited

variablevariable A named place that can hold a A named place that can hold a value of a particular typevalue of a particular type

Values of primitive type are held directly in Values of primitive type are held directly in variablesvariables

Values of non-primitive type are Values of non-primitive type are references to references to objectsobjects shown graphically by arrows shown graphically by arrows

0 An int variable

valuename

count

balancedepositswithdrawals

0

0

0

An Account variableaccount1

balancedepositswithdrawals

0

0

0

Another Account variableaccount2

Page 8: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 8

Declarations RevisitedDeclarations Revisited

Declarations have the form:Declarations have the form:

typetype namename ; ;

ExampleExample::

inint count;t count;

Account account1; Account account1;

Account account2; Account account2;

The initial value of a variable depends on its The initial value of a variable depends on its

typetype

– int variables: 0int variables: 0

– non-primitive-type variables: non-primitive-type variables: nullnull

ValueValue null null signifies that no object is signifies that no object is

referenced. It can be stored in a variable of referenced. It can be stored in a variable of

any class typeany class type0 An int variablecount

An Account variableaccount1

Another Account variableaccount2

null

null

Page 9: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 9

Declarations with Initialization Declarations with Initialization ExpressionsExpressions

Declarations can have an initialization Declarations can have an initialization

expression:expression:

typetype namename = = expressionexpression ; ;

ExampleExample::

int count = 0;int count = 0;

Account account1 = Account account1 = newnew Account(); Account();

Account account2 = Account account2 = newnew Account(); Account();

An An expressionexpression of the form of the form

newnew class-nameclass-name()()

computes a reference to a newly allocated computes a reference to a newly allocated

object of the given class. object of the given class.

Page 10: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 10

Manipulating Fields of an Object Manipulating Fields of an Object

If If

– rr is an expression whose value refers to is an expression whose value refers to

an object an object oo of class of class c, c,

– ff is a field of is a field of oo

then then

– rr..ff is a variable of object is a variable of object oo

Example:Example:

// Deposit d into account1.// Deposit d into account1.

account1.balance = account1.balance + d;account1.balance = account1.balance + d;

account1.deposits = account1.deposits + d;account1.deposits = account1.deposits + d;

Page 11: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 11

References are ValuesReferences are Values

Suppose you have declared Suppose you have declared aa to be an to be an

AccountAccount variable, i.e., you have the variable, i.e., you have the

declarationdeclaration

Account a; Account a;

Then you can assign any reference to an Then you can assign any reference to an

Account object into variable Account object into variable aa..

ExampleExample::

/* If k is 1, deposit d into account1, /* If k is 1, deposit d into account1,

otherwise deposit d into account2. */otherwise deposit d into account2. */

ifif ( k == 1 ) a = account1; ( k == 1 ) a = account1;

elseelse a = account2; a = account2;

// Deposit d to Account a.// Deposit d to Account a.

a.balance = a.balance + d;a.balance = a.balance + d;

a.deposits = a.deposits + d;a.deposits = a.deposits + d;

Two or more variables that refer to the Two or more variables that refer to the same object are called same object are called aliasesaliases..

Page 12: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 12

References are Values, cont.References are Values, cont.

balancedepositswithdrawals

0

0

0

An Account variableaccount1

balancedepositswithdrawals

0

0

0

Another Account variableaccount2

An Account variablea null

2 An int variablek

Page 13: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 13

MethodsMethods

Classes have methods:Classes have methods:

classclass class-nameclass-name{{

declarationsdeclarations methodsmethods}}

A A methodmethod is a named parameterized group is a named parameterized group of of statements.statements.

return-typereturn-type method-namemethod-name( ( parameter-parameter-listlist ) )

{{ statement-liststatement-list }}

Return-typeReturn-type voidvoid signifies no return value. signifies no return value.

Page 14: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 14

Example Method DefinitionsExample Method Definitions

class class AccountAccount

{{

int balance; // current balanceint balance; // current balance

int deposits; // deposits to dateint deposits; // deposits to date

int withdrawals; // withdrawals to dateint withdrawals; // withdrawals to date

// deposit d to account// deposit d to account

voidvoid deposit(int d) deposit(int d)

{{

balance = balance + d;balance = balance + d;

deposits = deposits + d;deposits = deposits + d;

}}

// withdraw w from account// withdraw w from account

voidvoid withdraw(int w) withdraw(int w)

{{

balance = balance - w;balance = balance - w;

withdrawals = withdrawals + w;withdrawals = withdrawals + w;

}}

. . .. . .}}

Page 15: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 15

Method UseMethod Use

If If

– rr is an expression whose value refers to is an expression whose value refers to

an object an object oo of class of class cc

– mm is a method of is a method of oo

thenthen

rr..m m ( ( expression-listexpression-list ) )

invokes method invokes method mm on object on object oo

When methodWhen method m m is executed, field names is executed, field names

signify the corresponding variables of signify the corresponding variables of

object object oo

Example InvocationExample Invocation::

account1.deposit(200);account1.deposit(200);

balancedepositswithdrawals

deposit

withdraw

0

0

0

An Account variableaccount1

Page 16: CS 100Lecture 61 CS100J Lecture 6 n Previous Lecture –Programming Concepts n Programming by stepwise refinement –a pattern –sequential refinement –case

CS 100 Lecture 6 16

Example Method UseExample Method Use

// Withdraw 100 from account2.// Withdraw 100 from account2.

account2.withdraw( 100 );account2.withdraw( 100 );

/* If k is 1, deposit 200 into account1, /* If k is 1, deposit 200 into account1,

otherwise deposit 200 into account2. */otherwise deposit 200 into account2. */

ifif ( k == 1 ) a = account1; ( k == 1 ) a = account1;

elseelse a = account2; a = account2;

// Deposit 200 to Account a.// Deposit 200 to Account a.

a.deposit( 200 ); a.deposit( 200 );

// Let n be the next integer.// Let n be the next integer.

n = in.readInt();n = in.readInt();

// Output 300.// Output 300.

System.out.println(300);System.out.println(300);