cs231 Lecture Notes Week 2, Wednesday Object methods -------------- Observation: lots of methods operate on a single object that is passed on a parameter. The object-oriented view of this is that you are invoking a method "on" an object, or sometimes people say you are passing a message to the object. Either way, there is the notion that one of the parameters is special. OBJECT METHODS are an alternate syntax that makes the special parameter invisible! Object methods we have seen: g.drawOval (...); string.charAt (1); When you invoke them, you invoke them "on" an object. All the methods we have written have been CLASS METHODS. You just invoke them. Possible confusion: Sometimes when you invoke a CLASS METHOD, you specify the name of the class, as in Card.printCard (...); Math.cos (...); How can we tell when we are invoking a CLASS or OBJECT method? Ok, so how do we WRITE object methods? 1) leave out the word static! 2) leave out the magic parameter In that case, how do we refer to the magic parameter? 1) using the keyword this OR 2) implicitly! Examples: printDeck and printCard plenty more examples in Chapter 13! ----- Homework 1 discussion Multiple classes -- mapping between objects and real-world concepts. Disadvantage -- additional level of indirection between you and the contents of the objects syntax is more convoluted... deck.length vs. deck.cards.length Actually, that indirectness can be an advantage: 1) object method syntax mitigates the awkwardness 2) each object can control the management of its data 3) separation of interest between objects -- promotes reusability, reliability More about this later. Homework 2 Next step toward object-orientedness -- object methods. Compare the syntaxes and see what's what. Algorithms -- how to classify card hands. Hard part -- dealing with hands with funny numbers of cards. 1) use histograms! 2) how do we compute the histograms once for use with many functions? Using instance variables to cache information Invariants / preconditions -------------------------- Invariant: something that is provably true at some point in a program Precondition: a condition that a method requires to be true when it executes, in order to work correctly Postcondition: a condition that is provably true at the end of a method (provided that the precondition is satisfied) What are the preconditions for isFlush? isPair? isStraightFlush? What should a method do about its preconditions? 1) fail 2) check 3) eliminate (minimize)