Point has two private fields, and nothing else. Printing it calls a built in to string method. Run it. Point, an at sign, and a strange code. Not very helpful.
Main.javajava
public class Main { public static void main(String[] args) { Point p = new Point(3, 4); System.out.println(p); }}
Output
Point@251a69d7
Also uses Point.java
public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; }}
We add our own to string method. It returns a nice, readable string. At override tells Java we're replacing the built in version. We'll learn more about override, in the next module.
Main.javajava
public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Point(" + x + ", " + y + ")"; }}
Now, println uses our to string. Joining an object into a string uses it too. Run it. Point three, four, in both lines.
Main.javajava
public class Main { public static void main(String[] args) { Point p = new Point(3, 4); System.out.println(p); System.out.println("Start at " + p); }}
Output
Point(3, 4)
Start at Point(3, 4)
Also uses Point.java
public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Point(" + x + ", " + y + ")"; }}
Override to string, to control how your objects print. Println, and joining with plus, both use it. That's the end of module eight. Next module, object oriented programming.