I've seen both approaches used but have never heard that one way is preferred over the other for any particular reason.
public String toString() {
return this.field1 + " " + this.field2;
}
versus
public String toString() {
return getField1() + " " + getField2();
}
I used String concatenation in my example to keep the code brief.
Using getters in toString is an overkill. And you should not be using toString for non debug purposes. Save this answer.
In general, they should be public. If they are private they can only be called from within your class and, since you already have access to the private variables within your class, are redundant. The point of them is to allow access to these variables to other, outside, objects. Save this answer.
When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.
There will not be enough information about state or properties of object. So, whenever you use or print a reference variable of type in which toString() method is not overrided, you will get an output like above. You will not get what the object actually has in it.
Use getters, if you have them!
Maybe, one day you change the code so that a getter will not only return the fields value but do something more or create the result in a different way. Then you'll be more then happy that you used getters consistently.
But as usual, there are excemptions from my advice - what do you expect from the toString() method if you allow overriding of the getter methods, do you want it use the classes fields or the result of the - maybe override - getter method.
So, as usual, it depends, but I'd use getters unless I have a good reason to access the fields directly.
Using accessor methods might be preferred if they provide any additional logic on top of just returning the field's value (like uppercasing a string, or something like that). If your class is designed to be extended, I would tend towards accessors because they may be overridden.
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