IntroductionFor today: Object-based programming, classes, con-structors, instance methods, instance variables.Readings covered today:On To Java,Chapters 8–12;Programming Into Java,Sections 4.4, 4.7, 4.8 (parts ofthese will still be obscure).Coming up:On To Java,Chapters 14–16, 19, 20.Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 1Object-Based ProgrammingBasic Idea.•Function-based programsare organized primarily aroundthe functions (methods, etc.) that do things. Datastructures (objects) are considered separate.•Object-based programsare organized around thetypes of objectsthat are used to represent data,– Methods, then, are grouped by type of object.• For example: function-based banking system:account deposit accountaccount withdraw account...•Vs. object-based banking system:Accountdepositwithdraw balance: 1420ExportedmethodsExportedfieldLast modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 2Philosophy• Idea (from 1970s and before): Anabstract datatypeis– a set of possible values (adomain), plus– a set ofoperationson those values (or their con-tainers).• In IntList, for example, the domain was aset ofpairs:(head,tail), where head is an int and tailis a pointer to an IntList.• The IntList operations consisted only of assigningto and accessing the two fields (head and tail).• In general, prefer a purelyprocedural interface,wherethe functions (methods) do everything—no outsideaccess to fields.• That way, implementor of a class and its methodshas complete control over behavior of instances.• In Java, the preferred way to write the “operationsof a type” is asinstance methods.Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 3You Saw It All in CS61A• Here’s the account class from CS61A, slightly mod-ified to make it more compatible with Java:(define-class (account balance0)(instance-vars (balance 0))(initialize(set! balance balance0))(method (deposit amount)(set! balance (+ balance amount))balance)(method (withdraw amount)(if (< balance amount)(error "Insufficient funds")(begin(set! balance (- balance amount))balance))) );; Use:(define my-account (instantiate account 1000))(ask my-account ’balance)(ask my-account ’deposit 100)(ask my-account ’withdraw 500)Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 4And Here It Is in Javapublic class Account {public int balance;public Account (int balance0) {balance = balance0;}public int deposit (int amount) {balance += amount; return balance;}public int withdraw (int amount) {if (balance < amount)throw new IllegalStateException("Insufficient funds");else {balance -= amount; return balance;}}}// Use:Account myAccount = new Account (1000);myAccount.balancemyAccount.deposit (100);myAccount.withdraw(500);Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 5The Pieces, part I• Class declaration defines anew type of object,i.e.,new type of structured container.• Instance variables such as balance are the simplecontainers within these objects (fieldsorcompo-nents).• Instance methods, such as deposit and withdraware like ordinary (static) methods that take an in-visible extra parameter (called this).• The new operator creates (instantiates) new objects,and initializes them using constructors.• Constructors such as the method-like declaration ofAccount are special methods that are used only toinitialize new instances. They take their argumentsfrom the new expression.• Method selection picks methods to call. For ex-ample,myAccount.deposit(100) tells us to call themethod nameddeposit that is defined for the ob-ject pointed to bymyAccount.Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 6Getter Methods• Slight problem with Java version of Account: anyonecan assign to thebalance field• This reduces the control that the implementor ofAccount 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 referencedoutside ofAccount.• OK to use name balance for both the field and themethod . . .• . . . Java can tell which is meant by syntax: A.balancevs. A.balance().Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 7Class Variables and Methods• Suppose we want to keep track of the bank’s totalfunds.• This number is not associated with any particularAccount, but is common to all—it isclass-wide.• In Java, “class-wide” ≡ staticpublic class Account {...private static int funds = 0;public int deposit (int amount) {balance += amount; funds += amount;return balance;}public static int funds () {return funds;}... // Also change withdraw.}•From outside, can refer to either Account.numAccounts()or myAccount.numAccounts() (same thing).Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 8Instance Methods and Variables Explained• Instance method such asint deposit (int amount) {balance += amount; funds += amount;return balance;}behaves very much like a static method with hiddenargument:static int deposit (final Account this,int amount) {this.balance += amount; funds += amount;return this.balance;}•NOTE: Just explanatory: Not real Java! However,finalisreal Java; means “can’t assign to”• Likewise, a call on an instance method, such asmyAccount.deposit (100) is like a call on this fic-tional static method:Account.deposit (myAccount, 100);•As a convenient abbreviation, can leave off the ‘this.’on field access or method call if not ambiguous.Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 9‘Instance’ and ‘Static’ Don’t Mix• Since real static methods don’t have the invisiblethis parameter, makes no sense to refer to instancevariables in them:public static int badBalance () {return balance; // WRONG! NONSENSE!}•Reference to balance here equivalent to this.balance.• This is meaningless (whosebalance?)• However, it makes perfect sense to access a static(class-wide) field or method in an instance methodor constructor, as happened withfunds in the depositmethod.Last modified: Wed Sep 19 01:48:32 2001 CS61B: Lecture #5 10Constructors• To completely control objects of some class, youmust be able to set their initial contents.• Aconstructoris a kind of special instance methodthat is called by the new operator right after it cre-ates a new object, as ifL = new IntList(1,null)=⇒tmp =pointer
View Full Document