+ 1
I am not clear with tostring method can someone please explain it for me
Core java
6 ответов
+ 10
▪toString() Methods
Print methods are common in some languages, but most Java programs operate differently. You can use System.out.println() to print any object. However for good results your class should have a toString() method that formats the object's data in a sensible way and returns a string. Otherwise all that's printed is the name of the class which is normally not what you want.
For example, a good toString() method for the Car class might be:
public String toString() {
return (this.licensePlate
+" is moving at "+
this.speed
+"km/h and has a maximum speed of "+
this.maxSpeed
+"km/h." );
}
+ 10
Rules for toString() Methods
• toString() methods should return a single line of text that does not contain any carriage returns or linefeeds.
• toString() methods are primarily for debugging.
• toString() should not do a lot of fancy processing. toString() methods should be quick.
The string returned by toString() should contain the name of the class, and names and values of the fields that represent the state of the object, unless there are an excessive number of such fields, in which case only the most important should be returned.
A better Car toString() method would be:
public String toString() {
return "[Car: plate = "+ this.licensePlate
+" speed = "+ this.speed
+"; MaxSpeed = "+ this.maxSpeed
+"]";
}
⟹ These rules are conventions, not requirements of the language.
akshay patel
https://code.sololearn.com/cmy2730Qn2tY/?ref=app
+ 8
The secret is every object in java extends class Object and inherits its methods 😉
+ 6
What are you unsure about? How toString() works or how come you can use this method with any object?
+ 2
Please change your Relevant Tags to contain Java (not just 'a') it is recommended to be more specific with the question.
0
How can we use this method with any object