CS115 lecture notes, Spring 1999 Week 10, Wednesday Review of constructor syntax: public class Complex { double real, imag; public Complex () { this.real = 0.0; this.imag = 0.0; } public Complex (double real, double imag) { this.real = real; this.imag = imag; } } First things to write are 1) instance variables 2) constructor(s) 3) something that prints the object public static void printComplex (Complex c) { System.out.println (c.real + " + " + c.imag + "i"); } Now, what other kinds of methods might we want to write? 1) pure functions 2) modifiers 3) fill-in methods Pure function: return value depends only on the arguments (not on any other "state"), and the method does not modify any values (except local variables). Also, no side-effects, like printing something or writing a file, etc. Return value may be a primitive or object type. Examples: findCenter, distance // abs is a function that returns a primitive public static double abs (Complex c) { return Math.sqrt (c.real * c.real + c.imag * c.imag); } // add is a function that returns a new Complex object public static Complex add (Complex a, Complex b) { return new Complex (a.real + b.real, a.imag + b.imag); } Return value may be the same type as the operands, in which case there is sometimes confusion with constructors. How can you tell the difference? Modifier: Changes one or more fields in one or more of the objects that are passed. Usually a void method, although sometimes the return value is an error code. // conjugate is a modifier public static void conjugate (Complex c) { c.imag = -c.imag; } Fill-in method: really a special case of the modifier. One of the arguments is an "empty" object. The method puts values into it. Testing ------- In each case we need to write some test code: public static void main(String args[]) { // use the first constructor Complex x = new Complex (); x.real = 1.0; x.imag = 2.0; // use the second constructor Complex y = new Complex (3.0, 4.0); System.out.println (abs (y)); conjugate (x); printComplex (x); printComplex (y); Complex s = add (x, y); printComplex (s); } } EXAM REVIEW: Emphasis on 5-8, although material is naturally cumulative. No Chapter 9 (creating your own classes) Some state diagramming: including all kinds: object (box and arrow) iteration tables, stack diagrams Some algorithm design: use abstract building blocks and pseudocode to describe algorithms at the high level without getting bogged down in details Some programming: bring lots of code samples so you can copy code fragments and avoid syntax errors. Some vocabulary: review class notes as well as glossaries Some debugging: Sharpen those red pencil eyes.