System.out.println("Student 1: " + student1);
This should compile and run, but notice what it does -- nothing
very useful! When an object is printed, Java looks for a toString
method for that object. This method must have no parameters and must return
a string. If such a method exists for this object, it is
called automatically -- you don't have to write the call in your program --
and the string it returns
is printed. If no such method exists, a unique hexadecimal
identifier for the object
is printed (e.g., Student@3a56d7).
Add a toString method to your Student class that returns a string containing the student's name and test scores, e.g.:
Name: Joe Test 1: 85 Test 2: 91
Note that the toString method does not call System.out.println -- it just
returns a string. Both the Die class (page 165), the Account class
(pages 178-179), and the Coin class (pages 221-222) in your
textbook have toString methods.
Recompile your Student class and the Grades program (you shouldn't have to change the Grades program -- you don't have to call toString explicitly). Now see what happens when you print a student object -- much nicer!