CSC152 2006S, Class 21: Standard Object Methods Admin: * Trustees voted to split Math/CS into CS and Math/Stats. Yay! * Should [some student] be allowed to leave early? No one cares, but the general consenus is "I hope you fail". * Two readings for tomorrow (both ready already): + Interfaces + Polymorphism * Questions on the exam? * Office hours today: 2-4 p.m. Overview: * The standard methods. * Lab. /Questions/ * What is a zero-parameter constructor? One with no parameters * What's the difference between a constructor and a method? * A method can do anything. * Constructors are intended to initialize a new object in a class. * Methods are defined with public TYPE NAME(PARAMS) * Constructors are defined public CLASS(PARAMS) * What should a zero-parameter constructor do? * Initialize all the fields to reasonable values * In a piggybank, set all the counts to 0. * In a fraction, set the numerator to 0 and the denominator to 1. * How do I round a double value? (Some different strategies) * Convert it to a Double and then call intValue * Try (int) nameOfDouble * Convert it to a string, strip off the period, and then call Integer.parseInt * Use Math.round or Math.floor or something similar * E.g., this.numerator = BigInteger.valueOf(Math.round(Math.floordecimal)); this.denominator = BigInteger.ONE; * Do you care that we do lots of conversions? * If they're necessary, no. If they're just for the sake of converting, then yes. * How close is close enough when deciding if a fraction is good enough? if (larger.subtract(smaller).toDecimal < .000000001) * How do I use Math.PI? Fraction pie = new Fraction(Math.PI); pen.println(pi + " is approximately " + pie); pen.println(pie + " is approxmately " + pie.toDouble()); /Standard Methods/ * Java programmers assume that whenever you define a class, you define some methods * Always: toString() - get a pritnable version of the object equals(Object other) - compare hashCode() - compute some integer that is likely to be different for different objects and must be the same for equal objects * Usually compareTo(XXX other) clone() - Make a copy * When writing equals, the standard form is the following. Only "MyClass" and the ellipses need to be changed public boolean equals(Object other) { return (other instanceof MyClass) && this.equals((MyClass) other); } public boolean equals(MyClass other) { ... } /Questions from the Lab/ * How do I determine whether two fractions are equal when they're both not in simplified form? * Eryn says "cross product"