Re: question about the toString Method



Art Cummings wrote:

I've included the bare minimum, that I think is necessary to understand the question i'm asking. I omitted the Textbook and Instructor classes. What's confusing me is why there seems to be nothing in the calling statement to direct the flow of the program to the toString method in the Course class.

You pass a reference to an object, it calls toString() on that reference.

public static void myPrintln( Object obj ) {
String s = obj.toString();
System.out.println( s ); // would actually use a different
// call here...
}

Get it?


The confusing one is how does the compiler know to call toString() when concatenating strings:

String s = "This is a: " + obj;

Answer: the compiler is specially crowbarred to call toString() in that instance.
.