1 / 22

2003-09-03 Dan Garcia (cs.berkeley/~ddgarcia) Kathy Yelick (cs.berkeley/~yelick)

Computer Science 61B Data Structures and Advanced Programming Lecture 4 – Designing Classes. 2003-09-03 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. What is a Class?.

aida
Télécharger la présentation

2003-09-03 Dan Garcia (cs.berkeley/~ddgarcia) Kathy Yelick (cs.berkeley/~yelick)

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 4 – Designing Classes 2003-09-03 Dan Garcia(www.cs.berkeley.edu/~ddgarcia) Kathy Yelick(www.cs.berkeley.edu/~yelick) inst.eecs.berkeley.edu/~cs61b/www.ucwise.org1 Handout:notes

  2. What is a Class? • A class defines a new type • Can be used in declarations, e.g. • A class defines a set of objects • What variables does each object contain? • A class defines a way of constructing objects • How the variables are initialized • A class defines a set of operations (methods) • These can modify or “mutate” the object • These can access or “observe” the objects

  3. Design Problem: Fractions • Java has built-in type for representing “real” numbers (approximately) • Rational numbers are not directly supported • Extend our programming environment by adding a “Fraction” type • Inside the Fraction class are two things: public class Fraction { } • By convention, the variables go at the end • Methods • Variables • Constructors: all named Fraction • Others: named something else • May have built-in or user-defined type

  4. Fraction f1; f1 1) A Class Defines a New Type • Knowing only the name of the class, what can we do? public class Fraction { … } • Declare a variable. • Set it to null. • Null is like nil in Scheme: a reference that doesn’t point anywhere. • If you don’t set this variable to null, Java does it

  5. myNumer • black boxes are objects • green boxes are variables myDenom 2) A Class Defines a Set of Objects • The variables (fields) tell us what they look like inside: public class Fraction { … /* private fields within a Fraction. */ private int myNumer; // numerator private int myDenom; // denominator }

  6. f1 myNumer 3 myDenom 4 3) A Class Defines Construction • Fraction class has 3 constructors public Fraction (int n, int d) { myNumer = n; myDenom = d; } What “new” does Fraction f1 = new Fraction(3,4); public Fraction (int n) { this(n, 1); } public Fraction ( ) { myNumer = 0; myDenom = 1; }

  7. Notes on Constructors • The constructors are overloaded • They have the same name, which is the class name • They must have different #s or types of arguments • Fraction (String s) {…} would be OK • Fraction (int d) {…} is not OK • Constructors have no return type • When you say “new” two things happen: • The object is allocated • A constructor is executed • Java lets you • Omit the constructor • Omit initialization of fields (provides defaults) … But don’t do either of these

  8. Designing a Class • How will objects be built: constructors • Should the object of the class be mutable? • If so, what methods will allow for mutation • Fractions are like other number types – immutable • Can objects be created from others in the class? • E.g., sum operation on fractions • Ways to observe/access objects: • Conversions, like toString and toDouble • Predicates like isZero, isInteger (not in current class) • Helping functions to simplify programming

  9. Public vs. Private • Methods and fields may be public or private • Public things (methods or fields) can be accessed anywhere • Variables can be read and assigned • Methods can be called • Private things can only be accessed by methods defined within the same class • This is not the same as saying “in the same object” • Most common pattern: • Methods are public, except helping methods • Fields are private

  10. What Should be Private? • Why are both variables in Fraction “private?” • Hides unnecessary details • Keeps users from relying on them • Allows for future changes in the code • To keep invariants true, e.g., • myDenom should never be zero • Fractions should always be stored reduced • It’s a kind of redundancy in the program • “Users don’t need to know this…” • Does one ever want public variables in a class?

  11. 4) A Class Defines Operations /** Calculates and returns the double floating * point value of a fraction. @return a double * floating point value for this Fraction. */ public double toDouble ( ) { double n = myNumer; double d = myDenom; return (n / d); } • this refers the object on which the method was invoked • Floating point numbers approximate reals • Two Java types: float (less memory) and double • Why not return myNumer/myDenom? this. this.

  12. Another Accessor Method /** Converts this fraction to a string * "numerator/denominator” in reduced form. * @return a String form of this Fraction. */ public String toString ( ) { int thisGcd = gcd (myNumer, myDenom); return (myNumerator/thisGcd + "/" + myDenominator/thisGcd); } • Note the use of + for string concatenation • Now we can print fractions using: System.out.println("f1 = " + f1);

  13. Accessor May Return a Fraction /** Add f2 to this fraction. * @param f2 is the fraction to be added. * @return the sum of f2 and this Fraction. */ public Fraction sum (Fraction f2) { Fraction total = new Fraction((myNumer * f2.myDenom) + (f2.myNumer * myDenom), (myDenom * f2.myDenom)); return total; } • Note access to f2’s internal (private) state

  14. Parameters to Methods • Each parameter is a variable—either a primitive type or a reference (non-primitive). • A method invocation does the following: • Create a new environment with • A box for each parameter • And one for this, the object on which the method is called • copies the arguments from the call • Copying a primitive value is straightforward • For a reference, make another arrow to the same object • executes the statements of the method. • No copying back into the caller’s arguments is done.

  15. f2 total this threeQ twoT answer myNumer myNumer myNumer 3 2 17 myDenom myDenom myDenom 3 12 4 Fraction total = new Fraction((myNumer * f2.myDenom) + (f2.myNumer * myDenom), (myDenom * f2.myDenom)); return total; Example Fraction threeQ = new Fraction(3,4); public Fraction sum (Fraction f2) { ... } Fraction twoT = new Fraction(2,3); Fraction answer = threeQ.sum(twoT);

  16. threeQ twoT answer myNumer myNumer myNumer 2 3 17 myDenom myDenom myDenom 3 4 12 Example Fraction threeQ = new Fraction(3,4); Fraction twoT = new Fraction(2,3); Fraction answer = threeQ.sum(twoT);

  17. Another Possible Fraction Method // inside Fraction public void swap(Fraction a, Fraction b) { Fraction temp; temp = a; a = b; b = temp; } //inside main method Fraction f1, f2; f1 = new Fraction (3,4); f2 = new Fraction (6,7); swap (f1, f2); • What are the values of f1 and f2 now? A: A: f1 will be 6/7 and f2 will be 3/4 B: B:f1 will be 3/4 and f2 will be 6/7 because Fractions are immutableC: C: f1 will be 3/4 and f2 will be 6/7 because of Java’s parameter passing D: D: This program is illegal

  18. A Helping Function in Fraction /** Computes the greatest common divisor. * @param x is assumed positive * @param y is assumed non-negative * @return the gcd of x and y */ static private int gcd (int x, int y) { if (y == 0) { return x; } else { return gcd (y, x % y); } } • Static means there is no “this” object. • Need not be (should not be) invoked as obj.gcd(…). % means “modulo” i.e., “remainder”

  19. Understanding Public/Private • Consider writing a main method. Which of the following would be legal inside it? • Two cases: main defined inside Fraction and main defined somewhere else, say “Tester.” f1 = new Fraction (2,3); double d = f1.toDouble(); int n1 = f1.myNumerator; n1 = gcd(12,16)

  20. 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 (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…

  21. 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

  22. Computer Science 61B:Designing and Implementing Classes Administrative stuff Lab protocol: labs must be checked off during class. No checkoffs after 2 hours (check off parts early) Arrive on time – some labs are longer than others No checkoffs in a different section TAs have updated class lists as of Monday Looking for more lab assistants Most important information is online Office hours are posted Reading assignments online Midterms and other future due dates Correction: HW2 due at 10AM, not 10PM on Feb. 5th, not Jan. 31st

More Related