1 / 19

2003-08-29  Dan Garcia (cs.berkeley/~ddgarcia)

Computer Science 61B Data Structures and Advanced Programming Lecture 3 – Building Objects. 2003-08-29  Dan Garcia (www.cs.berkeley.edu/~ddgarcia) Kathy Yelick  (www.cs.berkeley.edu/~yelick) inst.eecs.berkeley.edu/~cs61b/ www.ucwise.org 1 Handout: notes [and pick up index cards!].

iolani
Download Presentation

2003-08-29  Dan Garcia (cs.berkeley/~ddgarcia)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Computer Science 61BData Structures and Advanced ProgrammingLecture 3 – Building Objects 2003-08-29  Dan Garcia(www.cs.berkeley.edu/~ddgarcia) Kathy Yelick (www.cs.berkeley.edu/~yelick) inst.eecs.berkeley.edu/~cs61b/www.ucwise.org1 Handout:notes [and pick up index cards!]

  2. Design Problem: Financial Software • Design problem: • Want to model an investment portfolio • Real estate, bonds, cash, stocks, mutual funds, 401K… • Small version of the problem: • Design a simple no-interest savings account • Prevent from going negative • How to do this in Java? • A Java program is a collection of classes • like object-oriented programs in Scheme or Matlab • Each class is a collection of methods and variables • again, as in Scheme or Matlab

  3. Designing a Class To design a class, think about what the objects in that class should do • Determine methods • Constructors (ala 61A) • Accessors (61A selectors) • Mutators (if any) (these change the object) • Determine the set of variables • inside each object (61A instance variables) • shared by all objects in a class (61A class variables) Then fill in the blanks… You CAN define your own types in Java. They lookjust like the types provided by the Java library.

  4. Bank Account Class Design • Determine methods • Constructors • Accessors • Mutators • Determine the set of variables • inside each object • shared by all objects in a class • Questions • What currency? $? €? • Integer or floating point? Are all balances valid? • Account • balance • deposit, withdraw • myBalance • MIN_BALANCE

  5. Example from 61A - Definition (define-class (accountbalance) ;; Add money to the account (method (deposit amt) (set! balance (+ balance amt)) balance) ;; Take money from the account if enough ;; Otherwise return a can't-do-it msg (method (withdraw amt) (if (< balance amt) "Not enough funds" (begin (set! balance (- balance amt) ) balance) ) ) )

  6. Example from 61A - Use >(define my-account (instantiate account 10)) my-account >(ask my-account 'balance) 10 >(ask my-account 'deposit 2) 12 >(ask my-account 'withdraw 999) Not enough funds >(ask my-account 'withdraw 11) 1

  7. Bank Account Java Class Skeleton public class Account { // class name private int myBalance; // instance variable /** constructor */ public Account (int balance) { … } /** methods: deposit, withdraw, balance, main */ public void deposit (int amount) { … } public void withdraw (int amount) { … } public int balance ( ) { … } public static void main (String [] args) {…} }

  8. Write comments before you code! /** An Account contains the amount of money in a * simulated no-interest bank account. */ public class Account { /** Instance variable */ private int myBalance; /** Construct an account with the given balance. */ public Account (int balance) { … } /** Modify this account by adding money. */ public void deposit (int amount) { … } /** Modify this account by taking money out if enough * Otherwise print a can't-do message. */ public void withdraw (int amount) { … } /** Return the balance. */ public int balance ( ) { … } /** main method. Used to test this class. */ public static void main (String [] args) {…} } These are called method "Signatures". This is a design step!

  9. Bank Account Java Definition public class Account { // class name private int myBalance; // instance var public Account (int balance) { // constructor myBalance = balance; } public void deposit (int amt) { myBalance = myBalance + amt; } public void withdraw (int amt) { if (myBalance < amt) { System.err.println("Not enough funds"); } else { myBalance = myBalance - amt; } } public int balance ( ) { return myBalance; } public static void main (String [] args) {…} }

  10. Bank Account Use in Java • Main method may go in Account class or elsewhere public static void main (String [] args) { Account mine = new Account (10); System.out.println (mine.balance ()); mine.deposit (2); System.out.println (mine.balance ()); mine.withdraw (999); System.out.println (mine.balance ()); mine.withdraw (11); System.out.println (mine.balance ()); } Let's demonstrate!

  11. Administrivia • Reading assignments online on portal • For today: "Scheme to Java" in reader • For Wednesday ADW Chapter 4 • Discussion 113 moved! 285 Cory 241 Cory • Monday is a University holiday • Happy Labor day! PRS may beavailable Tuesday!

  12. Invariants • Account is an Abstract Data Type (ADT) • The essence of abstraction is the ability to maintain invariants. • An invariant is something that is always true • May assume it on entry to a method • Must ensure it when the method returns • (May be false for a while within the method, where no other method could see it.) • E.g., myBalance should never go below a minimum value • Add a variable for that minimum value • Good style: We don't hard-code "0" as a minimum value! • Modify the withdraw method to preserve the invariant

  13. Modifying Account (add invariant) • The variable used for minimum balance will be • Shared by all Account objects: static in Java • Never change: final in Java • Could be public or private (more on this later) public class Account { … /* Invariant: myBalance ≥ MIN_BALANCE */ private static final int MIN_BALANCE = 5; private int myBalance; }

  14. Modifying Account (in withdraw) • Note "myBalance - amt" is repeated in this code. • Is that a problem? Can anyone think of a solution? (withouut looking at their notes) • The withdraw method may now use it: public void withdraw (int amt) { if ((myBalance - amt) < MIN_BALANCE) { System.err.println("Not enough funds"); } else { myBalance = myBalance - amt; }

  15. Modifying Account (in withdraw) • For better style, use a temporary variable newBalance to store the "myBalance - amt" • The withdraw method may now use it: public void withdraw (int amt) { int newBalance = myBalance - amt; if (newBalance < MIN_BALANCE) { System.err.println("Not enough funds"); } else { myBalance = newBalance; }

  16. Peer Instruction Question • With the addition of the MIN_BALANCE variable and modification of withdraw… • Is our implementation now "safe"? I.e., will the invariant that the balance ≥ MIN_BALANCE always be preserved? A: A: Yes, it's now safe B: B: No, but fixable in 1 placeC: C: No, but fixable in 2 placesD: D: No, but fixable in 3 placesE: E: No, but fixable in 4 placesF:F: It can't be made safe

  17. Naming • Variable and method names • Prefix names of instance (object) variables with “my” • Prefix names of class variables (static) with “our”. (Except for static final variables.) • Name void functions with verbs or verb phrases. • Name typed functions with nouns. (Exception: conversion functions, e.g. toString.) • Capitalization • Class start with a capital (e.g., Account) • Methods and variables start with lower case • Use capitals to separate words (e.g., myBalance) • static final variables are in all capitals

  18. Comments • Write comments before code! • Accompany each method with comments that describe purpose, arguments, return value. • Always say if the method modifies something • Accompany the instance variables with comments about invariant relations. • Make comments count • This: int newBalance; /* Withdrawal result*/ • Not: int newBalance; /* An integer */ • More on style later (javadoc today if time)

  19. And in conclusion… • Scheme vs. Java: All programs… • in Scheme are functions. • in Java are a class (with a main method) at the top-level. • Roughly 3 kinds of methods • A constructor creates a new object of a class (same name as class) • An accessor looks at the object (usually returns other type) • A mutator that changes the object(Usually returns nothing, which is designated “void”) • Style • Comments and variable names are crucial in large programs

More Related