Custom toString() in java

java

Solution

Your method `public String toString(Point3D p)` is not overriding `Object.toString()`, which is the standard way to obtain a `String` representation of an `Object`.

The point of overriding it is to allow any subclass of `Object` to provide an appropriate representation of the object as a `String`. The Java API uses this method in a number of circumstances, mainly when needing to transform an `Object` into a `String` (for instance when doing `System.out.println(object)`, or performing String concatenation:

`String s = "The point is " + pointObject;`

Implement it as ay89 suggested:

@Override
public String toString() { 
    String result = getX() + "," + getY() + "," + getZ(); 
    return result;
} 

Please note the usage of the `@Override` annotation. If you used it on your method, the compiler would have warned you that something was wrong with its definition.

Problem

I'm studying to do my java OCA test, using the book "Java SE7 Programming Essentials" by Michael Ernest. This is my code for one of the answers to a question below: ``` public class Point3D { int x, y, z; public void setX(int x) { this.x = x; } public int getX() { return this.x; } public void setY(int y) { this.y = y; } public int getY() { return this.y; } public void setZ(int z) { this.z = z; } public int getZ() { return this.z; } public String toString(Point3D p) { String result = p.getX() + "," + p.getY() + "," + p.getZ(); return result; } public static void main(String args[]) { Point3D point = new Point3D(); point.setX(5); point.setY(12); point.setZ(13); System.out.println(point.toString(point)); } } ``` My code works, but in the last line, I think I've made my code in a weird way, shouldn't there be a way to make just `point.toString()` and not `point.toString(point)` return the String representation of the point? Can anyone explain to me how to fix it? I'm sure it's a simple answer, just trying to understand it because I suspect it points to a hole in my java knowledge.

Original source

Related problems