Why should I override the toString method instead of creating another method?

Is there anything special in toString that makes it unique and more useful to override compared to just turning off the toString method and creating a separate method.

For example, the following codes. What is the advantage / disadvantage of the Override toString method? Both methods return the same result.

@Override
public String toString(){ 
    return String.format("%s is a %s", "Apple", "fruit.");
}

public String newMethod(){
    return String.format("%s is a %s", "Apple", "fruit.");
}
+3
source share
12 answers

If you implement a method toString(), you can do things like:

MyType myobject = new MyType();
System.out.println(myobject);

This will automatically call the method toString().

If you were to implement your own method and call it newMethod(), you would need to do this:

MyType myobject = new MyType();
System.out.println(myobject.newMethod());

toString() .

+6

( ):

  • . , , . , , , , toString. .

  • Framework . , System.out.println(myObj) toString myObj.

+10

, Java toString(), Object.

System.out.println(yourObject);

@Override
public String toString(){ 
    return String.format("%s is a %s", "Apple", "fruit.");
}

.

+5

, , , System.out.print(object), toString(). , , .

+3

toString() Object, Java .

, , System.out.println(someObject).

- , , toString(), , :

@Override
public String toString(){ 
    return String.format("%s is a %s", "Apple", "fruit.");
}

public String newMethod(){
    return toString();
}
+2

Java toString() - . , , , Reflection.

, , toString(). , , , - String, , toString() ( toString() ), , newMethod().

toString(), Object, . -.

+2

toString , , , - System.out.println(something) ( java) Console.WriteLine(something) ( #). , toString .

+1

, JVM Object toString(), .

newMethod(), , : sysout(objOfYourClass.newMethod());
toString(), : sysout(objOfYourClass);

+1

ToString() - , . , , , ToString(). , ToString(), Console.WriteLine (#) System.out.println (Java)

+1

: System.out.println(yourclassobject) toString().

+1

JVM , toString() , System.out.println(obj);, toString()

0

toString, .

For example, System.out.printlnrelies on this to print an object string representation in stdout.

0
source

All Articles