If you have a class and you override the toString() method, it will return such a string method when the instance/object of the class is printed.
Why? when you create an object of a class and you print it to the console. It only returns the address of that object in the system memory.
For example, if we create an object of class A as shown below.
A a =new A();
Print(a);
Above code will print the address of the “a” object in the memory as adadads:A or Instance of A
So note that the toString()
method in a class will only override the return of address location when the instance/object of the class is printed to the console.
Example:
// Create a class
class Name {
String name = "justice";
int age = 23;
// override the toString method and return some String when the object/instance of this class is printed
@override
String toString() {
// am returning the above class properties
return this.name + " " + this.age.toString();
}
}
void main() {
// create object/instance of the above class
Name name = new Name();
/*
If you print an object/instance of a class and that class override the toString method,
it will invoke the toString method implicitly instead of returning the instance address of the class.
*/
print(name);
// So because the below "Name" class override the toString methods the result will be: justice 23
// if the "Name" class didn't override the toString method, then the result will be: Instance of 'Name' or Locatio address
}