CSC 297.Java 2003F, Static vs. Object Methods Admin: * Demos of factoring programs * Assignment: Design a RationalNumber class and suggest what methods should be object methods and what methods class methods Topics: * Object model, reviewed * Object fields, revisited * Object methods, revisited * Static methods, revisited * Static fields * Choosing a method type Notes on Alex's code * Comment procedures and classes (and equally big things) with a block comment of the form /** * Yadda yadda yadda. */ * Break up your code with succinct one-line comments that explain each chunk. These comments should be prefaced by // * Use indentation to show the logical structure of your code. * Think about efficiency. * Close braces belong on lines by themselves or they are easily lost. * Careful in how you comment close braces. * Using boolean "sentinels" for loops is often a good idea. Object model, reviewed * Object gather data and functions together * In Java, classes describe the general form of some objects Object fields, revisited * The "regular" fields in a class are places in which to store the data for corresponding objects double x_coord; double y_coord; Object methods, revisited * The "regular" methods in a class are things that use or change these values. public double distanceFromOrigin() { countOfDFOcalls = countOfDFOcalls + 1; return Math.sqrt(x_coord*x_coord + y_coord*y_coord); } Static methods, revisited * Sometimes you want to write methods that are not associated with any particular object but with the class as a whole. * E.g., convertAStringToaPoint * These are called "static" methods * Declared with PROTECTION static RETURN_TYPE NAME(PARAMS) { } * Static methods cannot reference object fields * How many times have I called distanceFromOrigin on *any* point? * Probably needs an accompanying "static" field (associated with the class as a whole). * PROTECTION static TYPE FIELD_NAME = INITIALIZATION; * E.g. private static int countOfDFOcalls = 0; public static int howManyTimesWasDFOCalled { return countOfDFOcalls; } Choosing a method type