In the following model class, what purpose does overriding the toString()
method achieve?
class User {
final int id;
String name, email, token;
User(this.id, this.name, this.email, this.token);
User.fromJson(dynamic json) : this.id = json['id'] {
this.name = json['name'];
this.email = json['email'];
this.token = json['token'];
}
dynamic toJson() => {'id': id, 'name': name, 'email': email, 'token': token};
@override
String toString() {
return toJson().toString();
}
}
By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.
Overriding toString() Method in Java out. print. It is because this method was getting automatically called when the print statement is written. So this method is overridden in order to return the values of the object which is showcased below via examples.
String toString () override. Returns the shortest string that correctly represent the input number. All doubles in the range 10^-6 (inclusive) to 10^21 (exclusive) are converted to their decimal representation with at least one digit after the decimal point.
String toString() Returns a string representation of this integer. The returned string is parsable by parse. For any int i , it is guaranteed that i == int.
The purpose of the toString() method is to provide a literal representation of whatever object it is called on, or to convert an object to a string (example converting primitive types to strings). For a user defined class, it can vary depending on your use case. You might want to print out the object to a console. A simple print command on the object won't give you any useful information. However, you can use the toString() method and convert it to a more understandable version. Example
@override
String toString() {
return "($someProperty,$someOtherProperty)";
}
This will return whatever the properties of that object were set at that time. Another (although not good) purpose could be to compare two objects of the same class. Similar to the above example, you can say that two objects of the class would be equal if the output of the toString() method of both objects is the same. Again, it totally depends on your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With