Overriding toString()
Part of: Inheritance
The Object Class. Every class in Java ultimately extends Object , the root of the entire class hierarchy. Because of this, every object inherits a small set of methods, including toString() and equals(). This lesson focuses on toString() . What toString() Does. toString() returns a String description of an object. Java calls it automatically when you: - print an object: System.out.println(obj); - concatenate an object with a string: "value: " + obj The default Object.toString() returns something ugly like Point@1b6d3586 (class name + hash code). That is rarely useful, so you override it. Overriding It. Now System.out.println(new Point(3, 4)); prints (3, 4) instead of a memory-address-like string. The println method quietly calls your toString() behind the scenes. Why It Matters. - Makes debugging output readable. - Lets objects describe themselves consistently everywhere they are printed. - Required by the AP CSA exam's expectation that you can write a clean toString(). Rules. - Signature must be exactly public String toString(). - Use @Override to catch mistakes. - It should return a string, not print one. What usually goes wrong. What you see What caused it How to fix it --- ---
Challenge: Point toString