Download CS61B Lecture #5: Arrays and Objects and more Slides Data Structures and Algorithms in PDF only on Docsity!
CS61B Lecture #5: Arrays and Objects
- For faster response, please send urgent problems (like “the lab files don’t compile”) as mail to cs61b, rather than using class messages.
- Homeworks are generally due by the next lab.
- For next week, please read Head First Java, chapters 5 and 6.
Arrays
- An array is structured container whose components are
- length, a fixed integer.
- a sequence of length simple containers of the same type, num- bered from 0.
- (.length field usually implicit in diagrams.)
- Arrays are anonymous, like other structured containers.
- Always referred to with pointers.
- For array pointed to by A,
- Length is A.length
- Numbered component i is A[i] (i is the index)
- Important feature: index can be any integer expression.
Example: Accumulate Values
Problem: Sum up the elements of array A.
static int sum (int[] A) {
int N;
N = 0; // New (1.5) syntax
for (int i = 0; i < A.length; i += 1) for (int x : A)
N += A[i]; N += x;
return N;
// For the hard-core: could have written
int N, i;
for (i=0, N=0; i
Example: Insert into an Array
Problem: Want a call like insert (A, 2, "gnu") to convert (destruc-
tively)
A: bear
gazelle
hartebeest
skunk
A: bear
gazelle
gnu
hartebeest
to
/** Insert X at location K in ARR, moving items
- K, K+1, ... to locations K+1, K+2, ....
- The last item in ARR is lost. */ static void insert (String[] arr, int k, String x) { for (int i = arr.length-1; i > k; i -= 1) // Why backwards? arr[i] = arr[i-1]; // Alternative to this loop: // System.arraycopy ( arr, k,︸ ︷︷ ︸ from
arr, k+1,︸ ︷︷ ︸ to
arr.length-k-1︸ ︷︷ ︸
to copy
);
arr[k] = x; }
Object-Based Programming
Basic Idea.
- Function-based programs are organized primarily around the func- tions (methods, etc.) that do things. Data structures (objects) are considered separate.
- Object-based programs are organized around the types of objects that are used to represent data; methods are grouped by type of object.
- Simple banking-system example:
account
deposit
account
account
withdraw
account
Function-based
Account deposit withdraw balance: 1420
Exported methods
Exported field
Object-based
Philosophy
- Idea (from 1970s and before): An abstract data type is
- a set of possible values (a domain), plus
- a set of operations on those values (or their containers).
- In IntList, for example, the domain was a set of pairs: (head,tail),
where head is an int and tail is a pointer to an IntList.
- The IntList operations consisted only of assigning to and accessing
the two fields (head and tail).
- In general, prefer a purely procedural interface, where the func- tions (methods) do everything—no outside access to fields.
- That way, implementor of a class and its methods has complete con- trol over behavior of instances.
- In Java, the preferred way to write the “operations of a type” is as instance methods.
The Pieces
- Class declaration defines a new type of object, i.e., new type of structured container.
- Instance variables such as balance are the simple containers within these objects ( fields or components).
- Instance methods, such as deposit and withdraw are like ordinary (static) methods that take an invisible extra parameter (called this).
- The new operator creates ( instantiates) new objects, and initializes them using constructors.
- Constructors such as the method-like declaration of Account are special methods that are used only to initialize new instances. They take their arguments from the new expression.
- Method selection picks methods to call. For example,
myAccount.deposit(100)
tells us to call the method named deposit that is defined for the
object pointed to by myAccount.
Getter Methods
- Slight problem with Java version of Account: anyone can assign to
the balance field
- This reduces the control that the implementor of Account has over possible values of the balance.
- Solution: allow public access only through methods:
public class Account {
private int balance;
public int balance () { return balance; }
- Now the balance field cannot be directly referenced outside of
Account.
- (OK to use name balance for both the field and the method. Java
can tell which is meant by syntax: A.balance vs. A.balance().)
Instance Methods
int deposit (int amount) {
balance += amount; funds += amount;
return balance;
behaves sort of like a static method with hidden argument:
static int deposit (final Account this, int amount) {
this.balance += amount; funds += amount;
return this.balance;
- NOTE: Just explanatory: Not real Java (not allowed to declare
‘this’). (final is real Java; means “can’t change once set.”)
- Likewise, the instance-method call myAccount.deposit (100) is like a call on this fictional static method:
Account.deposit (myAccount, 100);
- Inside method, as a convenient abbreviation, can leave off leading
‘this.’ on field access or method call if not ambiguous.
‘Instance’ and ‘Static’ Don’t Mix
- Since real static methods don’t have the invisible this parameter, makes no sense to refer directly to instance variables in them:
public static int badBalance (Account A) {
int x = A.balance; // This is OK (A tells us whose balance)
return balance; // WRONG! NONSENSE!
- Reference to balance here equivalent to this.balance,
- But this is meaningless ( whose balance?)
- However, it makes perfect sense to access a static (class-wide) field or method in an instance method or constructor, as happened with
funds in the deposit method.
- There’s only one of each static field, so don’t need to have a ‘this’ to get it. Can just name the class.
Summary: Java vs. CS61A OOP in Scheme
Java CS61A OOP class Foo ... (define-class (Foo args)... int x = ...; (instance-vars (x ...))
Foo( args) {...} (initialize ...)
int f(...) {...} (method (f ...) ...)
static int y = ...; (class-vars (y ...))
static void g(...) {...} (define (g...)...)
aFoo.f (...) (ask aFoo ’f ...) aFoo.x (ask aFoo ’x) new Foo (...) (instantiate Foo ...) this self