Page 1 of 1
[HD Pg 181, Sec. 8.1.2 - returning-multiple-values-from-a-method]
Posted: Mon Feb 18, 2019 7:19 pm
by OCAJO1
Expanding on the code in the book,
Code: Select all
class Name {
String firstName, lastName;
public Name listNames() {
Name n = new Name();
n.firstName = "first";
n.lastName = "last";
return n;
}
@Override
public String toString (){
return firstName+" "+lastName;
}
}
Class TestName{
public static void main(String [] args) {
System.out.println(new Name().listNames());
}
}
I was wondering how does one make use of n to print the first an last name, rather than spelling them out in the toString() method?
Thanks
Re: [HD Pg 181, Sec. 8.1.2 - returning-multiple-values-from-a-method]
Posted: Mon Feb 18, 2019 9:42 pm
by admin
Sorry, I did not understand your question.
Re: [HD Pg 181, Sec. 8.1.2 - returning-multiple-values-from-a-method]
Posted: Tue Feb 19, 2019 12:40 pm
by OCAJO1
I think I answered my own question, that the use of toString() override to return string representation of the object, has nothing to do with how a reference to that object is treated.
Which brings up another question,
public String toString()
return null; or
return " "; or
return ""; or
return firstName; or
return firstName+" "+lastName;
returns string representation of the entire object's holding.
Not withstanding the fact that the last choice have to do with whether the toString() should do the print formatting (that's not a good idea, is it?) or the formatting should be done within the printf() or print() of the calling method - which of the first four choices are preferred/good/proper/better programming return value coding in this case?
Re: [HD Pg 181, Sec. 8.1.2 - returning-multiple-values-from-a-method]
Posted: Tue Feb 19, 2019 8:45 pm
by admin
If there are instance fields in the class, then the toString method should generate and return a string that includes their values. So, return null, return "" etc (which are nothing but hardcoded values) are bad choices.
It is not a bad idea to generate a properly formatted string in toString because most of the time, it is used in log statements. Many standard Java classes such as ArrayList, return a nicely formatted string.
Re: [HD Pg 181, Sec. 8.1.2 - returning-multiple-values-from-a-method]
Posted: Wed Feb 20, 2019 12:23 pm
by OCAJO1
So the last choice would be the best way to handle the formatting in this case?
Re: [HD Pg 181, Sec. 8.1.2 - returning-multiple-values-from-a-method]
Posted: Wed Feb 20, 2019 8:03 pm
by admin
yes, that's correct.