Download presentation
Presentation is loading. Please wait.
Published byMitchell Osborne Modified over 9 years ago
1
CS61B L03 Building Objects (1)Garcia / Yelick Fall 2003 © UCB 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!] Computer Science 61B Data Structures and Advanced Programming Lecture 3 – Building Objects
2
CS61B L03 Building Objects (2)Garcia / Yelick Fall 2003 © UCB 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 »l ike object-oriented programs in Scheme or Matlab –Each class is a collection of methods and variables »again, as in Scheme or Matlab
3
CS61B L03 Building Objects (3)Garcia / Yelick Fall 2003 © UCB Designing a Class To design a class, think about what the objects in that class should do 1.Determine methods –Constructors (ala 61A) –Accessors (61A selectors) –Mutators (if any) (these change the object) 2.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 look just like the types provided by the Java library.
4
CS61B L03 Building Objects (4)Garcia / Yelick Fall 2003 © UCB Bank Account Class Design 1.Determine methods –Constructors –Accessors –Mutators 2.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
CS61B L03 Building Objects (5)Garcia / Yelick Fall 2003 © UCB Example from 61A - Definition (define-class (account balance) ;; 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
CS61B L03 Building Objects (6)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (7)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (8)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (9)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (10)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (11)Garcia / Yelick Fall 2003 © UCB 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 be available Tuesday!
12
CS61B L03 Building Objects (12)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (13)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (14)Garcia / Yelick Fall 2003 © UCB Modifying Account (in withdraw ) public void withdraw (int amt) { if ((myBalance - amt) < MIN_BALANCE) { System.err.println("Not enough funds"); } else { myBalance = myBalance - amt; } The withdraw method may now use it: Note " myBalance - amt " is repeated in this code. Is that a problem? Can anyone think of a solution? (withouut looking at their notes)
15
CS61B L03 Building Objects (15)Garcia / Yelick Fall 2003 © UCB public void withdraw (int amt) { int newBalance = myBalance - amt; if (newBalance < MIN_BALANCE) { System.err.println("Not enough funds"); } else { myBalance = newBalance; } Modifying Account (in withdraw ) The withdraw method may now use it: For better style, use a temporary variable newBalance to store the " myBalance - amt "
16
CS61B L03 Building Objects (16)Garcia / Yelick Fall 2003 © UCB 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 place C: C: No, but fixable in 2 places D: D: No, but fixable in 3 places E: E: No, but fixable in 4 places F: F: It can't be made safe
17
CS61B L03 Building Objects (17)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (18)Garcia / Yelick Fall 2003 © UCB 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
CS61B L03 Building Objects (19)Garcia / Yelick Fall 2003 © UCB 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.