CSC152 2004F, Class 16: Standard Methods Admin: * Labs good? * Comments on eboards? * Exam distributed Friday * Homework grading for Friday (I hope) * New term: "Mold class" (replaces "Template class") * Main class: Provides main method. * Mold class: Provides guidelines for building objects. Contains fields and constructors. * Interface: Provides a list of methods, but nothing more. * Template class (official): Class that accepts other classes as parameters. * Problem with switch statements + Moral: If you use a return in a case, you don't need the break. Overview: * Why have standard methods? * The toString method * The equals method * The compareTo method * The clone method * The hashCode method /Standard Methods/ * Methods you are likely to put in almost every class that's not a main class. * Five standards: + toString: Represents the object as a string + equals: Compare the object to another + compareTo: Compare the object to another + clone: Make a copy + hashCode: Represent the object as an integer * Why have these standard methods? * Why have toString? * Gets called as default. * Useful to be able to print objects. * If everyone uses the same name, it's easier to write code that uses this method. (Sounds like an interface issue.) * Standard methods mean that others can write general methods that use our objects, even if they don't know about our objects in advance. /Equals: Compare for Equality/ * Note: Your first task is to determine what "naturally equal" means. * E.g., both Polar(2.0, Math.PI/2) and Point(0.0, 2.0) are Vec2Ds * No: They are different types * Yes: Both represent the point (0,2) * E.g., are Point(0.0,2.0) and Point(0.00000001,1.99999998) equal? * No: Different values (however, pretty darn close) * Yes: If you don't need that many decimal places * Yes: Java tends to approximate. * The signature (form) of the equals method public boolean equals(Object other) * Problem: General Objects don't provide the methods you want * Solution: Cast those objects to the appropriate type NewType newname = (NewType) oldobject * Problem: If you cast inappropriately, your program crashes * Solution: Check if you can cast if (object instanceof ClassName) /CompareTo/ * public int compareTo(Object other) * Return negative number for "I'm less than other" * Return 0 for "I'm equal to other" * Return postiive number for "I'm greater than other" * Probably have to cast as in equals * If it's not castable, crash and burn /Clone/ * public Object clone() * Make a copy. * Useful for mutable objects. /HashCode/ public int hashCode() * Return some integer. * Equal objects should return the same integer. * Unequal objects should be unlikely to return the same integer. /Homework/ * Implement all of these, except hashCode, for DateV1. Convo tomorrow in Bucksbaum. See a Frank Sinatra movie and learn about "whiteness"