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)

Slides:



Advertisements
Similar presentations
DONT PANIC!! Lots of new notions coming in these slides Dont worry if not all of it makes perfect sense Well meet most of this stuff again in detail later.
Advertisements

Classes and Objects CMSC 202. Version 9/122 Programming & Abstraction All programming languages provide some form of abstraction. – Also called information.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
CHAPTER 9 DEFINING CLASSES & CREATING OBJECTS Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Road Map Introduction to object oriented programming. Classes
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
CHAPTER 2 OBJECTS AND CLASSES Goals: To understand the concepts of classes and objects To realize the difference between objects and object references.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Chapter 3 Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand.
Chapter 9 Domain Models 1CS6359 Fall 2012 John Cole.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CSC 212 – Data Structures Lecture 12: Java Review.
Introduction to Object-Oriented Programming
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Creating Simple Classes. Outline of Class Account Class Account Account # Balance Holder name phone# Overdrawn (true/false) Data Members Open Credit Debit.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Classes CS 21a: Introduction to Computing I First Semester,
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
CS61B L02 Using Objects (1)Garcia / Yelick Fall 2003 © UCB Kathy Yelick Handout for today: These lecture notes Computer Science 61B Lecture 2 – Using Objects.
CS61B L12 Arrays and Implementing Enumerations (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
CS61B L08 Vectors, Enumeration & Project 1 (1)Garcia / Yelick Fall 2003 © UCB Never forget…
Classes: Member Functions and Implementation November 22, 2002 CSE103 - Penn State University Prepared by Doug Hogan.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
Programs and Classes A program is made up from classes Classes may be grouped into packages A class has two parts static parts exist independently Non-static.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CS61B L11 Testing & Static (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
CS61B L07 Specification and Documentation (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
CS61B L06 Control Structures (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
Class Design I Class Contracts Readings: 2 nd Ed: Section 9.5, Advanced Topic nd Ed: Section 8.5, Advanced Topic 8.2 Some ideas come from: “Practical.
SEEM Java – Basic Introduction, Classes and Objects.
CS61B L10 Exceptions (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CS61B L13 Lists (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
CS 100Lecture71 CS100J Lecture 7 n Previous Lecture –Computation and computational power –Abstraction –Classes, Objects, and Methods –References and aliases.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 3: An Introduction to Classes 1 Chapter 3 An Introduction to Classes.
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
Chapter 3 Implementing Classes
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Classes and Objects Introduced
CSE 8A Lecture 17 Reading for next class: None (interm exam 4)
Introduction to Computer Science / Procedural – 67130
Software Development Java Classes and Methods
Intro To Classes Review
Java Programming with BlueJ
Java Classes and Objects 3rd Lecture
More on Classes and Objects
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
JAVA CLASSES.
Classes CS 21a: Introduction to Computing I
Introduction to Object-Oriented Programming
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

CS61B L03 Building Objects (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  ( inst.eecs.berkeley.edu/~cs61b/ 1 Handout: notes [and pick up index cards!] Computer Science 61B Data Structures and Advanced Programming Lecture 3 – Building Objects

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

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.

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

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) ) ) )

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

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) {…} }

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!

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) {…} }

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!

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!

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

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; }

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)

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 "

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

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

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)

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