Download session5

Document related concepts
no text concepts found
Transcript
Gentle
Introduction to
Programming
Session 5: Memory Model,
Object Oriented Programming
1
Review
• Recursive vs. Iterative
• Arrays
• Arrays in memory
• Initialization and usage
• foreach, filter
• Arrays as functions arguments
• Multi-dimensional arrays
• References to array
• Sorting, searching and time-complexity analysis
• Binary search
• Bubble sort, Merge sort
2
Today
• Home work review
• Scala memory model
• Guest lecture by Prof. Ronitt Rubinfeld 11:10
• Object-oriented programming (OOP)
• Classes and Objects
• Functional Objects (Rational Numbers example)
• Home work
3
Exercise 1
Write a program that gets 10 numbers from the user.
It then accepts another number and checks to see if
that number was one of the previous ones.
Example 1:
Please enter 10 numbers:
1 2 3 4 5 6 7 8 9 10
Please enter a number to search for: 8
Found it!
Example 2:
Please enter 10 numbers:
1 2 3 4 5 6 7 8 9 10
Please enter a number to search for: 30
Sorry, it’s not there
4
Solution
FindNumber.scala
5
Exercise 2
• Implement a function that accepts two integer
arrays and returns true if they are equal, false
otherwise. The arrays are of the same size
• Write a program that accepts two arrays of
integers from the user and checks for equality
6
Solution
CompareArrays.scala
7
Solution (main)
CompareArrays.scala
8
Exercise 3
• Read, understand and implement
selection/insertion sort algorithm
• http://en.wikipedia.org/wiki/Selection_sort
• http://en.wikipedia.org/wiki/Insertion_sort
9
Selection Sort
10
Solution
11
Today
• Home work review
• Scala memory model
• Guest lecture by Prof. Ronitt Rubinfeld
• Object-oriented programming (OOP)
• Classes and Objects
• Functional Objects (Rational Numbers example)
• Home work
12
Passing Arguments to Functions
• When a function is called, arguments’ values
are attached to function’s formal parameters by
order, and an assignment occurs before
execution
• Values are copied to formal parameters
• “Call by value”
• Function’s parameters are defined as vals
13
Passing Arguments to Functions
•
•
•
•
A reference is also passed by value
Example: arrays
Objects (?)
This explains why we can change an array’s
content within a function
a
4
5
6
7
8
9
14
Local Names
• Arguments names do not matter!
• Local variable name hides in-scope variables
with the same name
Different x!
15
Everything is an Object (in Scala)
•
•
•
•
In Java: primitives vs. objects
In Scala everything is an Object
But: special treatment for primitives
Why do we care?
val x = 5
var y = x
y = 6
?
val ar1 = Array(1,2,3)
val ar2 = ar1
ar2(0) = 4
16
?
val x = 5
var y = x
y = 6
val ar1 = Array(1,2,3)
val ar2 = ar1
ar2(0) = 4
17
Memory Image 1
val x = 5
var y = x
y = 6
x
5
y
5
6
18
Memory Image 2
val ar1 = Array(1,2,3)
val ar2 = ar1
ar2(0) = 4
ar1
1 2 3
4
ar2
19
Scala Memory Model
• Based on Java…
• Stack: local variables and arguments, every
function uses a certain part of the stack
• Stack variables “disappear” when scope ends
• Heap: global variables and object, scope
independent
• Garbage Collector
• Partial description
20
How to Change a Variable via
Functions?
• The arguments are passed as vals thus can not
be changed
• So how can a method change an outer
variable?
• By its return value
• By accessing heap-based memory (e.g., arrays)
21
Today
• Home work review
• Scala memory model
• Guest lecture by Prof. Ronitt Rubinfeld
• Object-oriented programming (OOP)
• Classes and Objects
• Functional Objects (Rational Numbers example)
• Home work
22
Programming in Scala
Chapter 4: Classes and Objects
Chapter 6: Functional Objects
23
Singletone Objects
• All programs written so far in this course are
Signletone objects
• File start with the reserved word object
• Contain functions that can be used elsewhere
• Application: singeltone object with a main
function
• (Actually singeltone objects are more then that)
• (Java programmers: think of it as a holder of static
methods)
24
A Car
• How would you represent a car?
• Parts / features: 4 wheels, steering wheel, horn,
color,…
• Functionality: drive, turn left, honk, repaint,…
• In Scala???
25
Object-Oriented Programming
(OOP)
• Represent problem-domain entities using a
computer language
• When building a software in a specific domain,
describe the different components of the domain
as types and variables
• Thus we can take another step up in abstraction
26
Class as a Blueprint
A class is a blueprint of objects
27
Class as a Blueprint
A class is a blueprint of objects
28
Classes as Data Types
• Classes define types that are a composition of
other types and have unique functionality
• An instance of a class is named an object
• Every instance may contain:
• Data members / fields
• Methods
• Constructors
• Instances are accessed only through reference
29
Examples
• String
• Members: all private
• Methods: length, replace, startsWith, substring,…
• Constructors: String(), String(String),…
• http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
• Array
• Members: all private
• Methods: length, filter, update,…
• Constructors: initiate with 1-9 dimensions
• http://www.scala-lang.org/docu/files/api/scala/Array.html
30
Car Example
• Members: 4 wheels, steering wheel, horn, color,…
• Every car instance has its own
• Methods: drive, turn left, honk, repaint,…
• Constructors: Car(String color),
Car(Array[Wheels], Engine,…), …
31
Today
• Home work review
• Scala memory model
• Guest lecture by Prof. Ronitt Rubinfeld
• Object-oriented programming (OOP)
• Classes and Objects
• Functional Objects (Rational Numbers example)
• Home work
32
Rational Numbers
• A ration number is a number that can be
expressed as a ration n/d (n,d integers, d not 0)
• Examples: 1/2, 2/3, 112/239, 2/1
• Not an approximation
33
Specification
• Add, subtract, multiply, divide
• println should work smoothly
• Immutable (result of an operation is a new rational number)
• It should feel like native language support
34
Constructing a Rational
• How client programmer will create a new
Rational object?
Class parameters
35
Constructing a Rational
• The Scala compiler will compile any code placed in
the class body, which isn’t part of a field or a method
definition, into the primary constructor
?
36
Reimplementing toString
• toString method
• A more useful implementation of toString would
print out the values of the Rational’s numerator and
denominator
• override the default implementation
37
Usage
• Now we can remove the debug println…
38
Checking Preconditions
• Ensure the data is valid when the object is
constructed
• Use require
39
Define “add” Method
• Immutable
• Define add:
40
Add Fields
• n, d are in scope in the add method
• Access then only on the object on which add
was invoked 
41
Test Add, Access Fields
42
Self Reference (this)
• Define method lessThan:
• Define method max:
43
Auxiliary Constructors
• Constructors other then the primary
• Example: a rational number with a denominator
of 1 (e.g., 5/1  5)
• We would like to do: new Rational(5)
• Auxiliary constructor first action: invoke
another constructor of the same class
• The primary constructor is thus the single point
of entry of a class
44
Revised Rational
45
Private Fields and Methods
• 66/42 = 11/7
• To normalize divide the numerator and denominator
by their greatest common divisor (gcd)
• gcd(66,42) = 6  (66/6)/(42/6) = 11/7
• No need for Rational clients to be aware of this
• Encapsulation
46
Off Topic: Calculate gcd
• gcd(a,b) = g
•
•
•
•
a = n * g
b = m * g
gcd(n,m)=1(otherwise g is not the gcd)
a = t * b + r = t * m * g + r  g is a
divisor of r
• gcd(a,b) = gcd(b,a%b)
• The Euclidean algorithm: repeat iteratively:
if (b == 0) return a
else repeat using a  b, b  a%b
• http://en.wikipedia.org/wiki/Euclidean_algorithm
47
Correctness
• Example:
gcd(40,24)  gcd(24,16)  gcd(16,8) 
gcd(8,0)  8
• Prove: g
= gcd(a,b) = gcd(b,a%b)= g1
• g1 is a divisor of a ( g1 ≤ g)
• There is no larger divisor of a (
g1 ≥ g)
• ≤ : a = t * b + r  a = t * h * g1 + v * g1
 g1 is a divisor of a
• ≥ : assume g > g1  a = t * b + r  g is a
divisor of b and r  contradiction
48
Implementation
49
Revised Rational
50
Defining Operators
•
•
•
•
Why not use natural arithmetic operators?
Replace add by the usual mathematical symbol
Operator precedence will be kept
All operations are method calls
51
Revised Rational
52
Usage
53
Method Overloading
• Now we can add and multiply rational numbers!
• What about mixed arithmetic?
• r * 2 won’t work 
• r * new Rational(2) is not nice 
• Add new methods for mixed addition and
multiplication
• Method overloading
• The compiler picks the correct overloaded
method
54
Usage
• The * method invoked is determined in each
case by the type of the right operand
55
Revised Rational
56
Implicit Conversions
• 2 * r  2.*(r)  method call on 2 (Int) 
Int class contains no multiplication method
that takes a Rational argument 
• Create an implicit conversion that
automatically converts integers to rational
numbers when needed
57
Companion Object
58
Revised Rational
• Define implicit conversion in Rational.scala,
after defining object Rational
59
In Eclipse
• In Rational.scala:
• Companion object
(object Rational)
• Rational class (class
Rational)
• Place the main method
in another file
60
Summary
• Customize classes so that they are natural
to use
• fields, methods, primary constructor
• Method overriding
• Self reference (this)
• Define several constructors
• Encapsulation
• Define operators as method
• Method overloading
• Implicit conversions, companion object
61
Today
• Home work review
• Scala memory model
• Guest lecture by Prof. Ronitt Rubinfeld
• Object-oriented programming (OOP)
• Classes and Objects
• Functional Objects (Rational Numbers example)
• Home work
62
Exercise 1
• Implement class Complex so it is natural to use
complex numbers
• Examples:
63