toString and Method Decomposition
toString
Part of: Writing Classes
Giving an Object a Readable Form By default, printing an object shows something cryptic like Point@1b6d3586. Overriding toString lets you control the text Java uses whenever an object is printed or joined to a String: Now System.out.println(p) prints (3, 4). Java automatically calls toString when an object appears where a String is expected, so "P = " + p works too. The method must be public, take no parameters, and return a String. Method Decomposition Method decomposition is the practice of breaking a big task into several small, well-named methods, each doing one thing. Small methods are easier to read, test, and reuse. Compare a tangled method with a decomposed version: Each helper (subtotal, tax) is private because it is an internal detail; only total is public. The top-level method becomes a short, readable summary of the steps. Guidelines for Decomposition Good decomposition follows a few rules: - Each method should do one clear job and be named for that job. - A method that grows long or has a comment like // now compute tax is a hint to extract a helper. - Helpers used only inside the class should be private. Key points: - Override public String toString() to give an objec
Challenge: Fraction toString