I am studying for the AP CS Exam, and came across this practice problem in the OOP section of my book. The following two classes are given.
package chap4q9;
public class Person
{
开发者_JAVA百科 private int age;
public Person(int a)
{
age = a;
}
public String toString()
{
return "Age: " + age + "\n";
}
}
package chap4q9;
public class Student extends Person
{
private double gpa;
public Student(int a, double g)
{
super(a);
gpa = g;
}
public String toString()
{
return super.toString() + "GPA: " + gpa; //This was where the missing code was
}
}
And the following is the client program that calls these two classes.
package chap4q9;
public class Chap4Q9
{
public static void main(String[] args)
{
Student kathy = new Student(17, 3.85);
System.out.println(kathy);
}
}
Finally, the output is:
Age: 17
GPA: 3.85
Just in case you were wondering, there is not actually supposed to be a line between the Age and GPA in the output, that was a weird formatting thing when I posted this.
The goal was to replace missing code in the second toString method (in the code above, the correct answer was inserted for the missing code, but I marked the location). I thought the book was wrong, but ran the code and got the same output. I thought that it would simply print the memory location that kathy was located at, and if you wanted to get that output, you would have to print kathy.toString(). However, just printing kathy seems to be running the toString method in the Student class. My question is, why is printing the Student object, kathy, getting that output, and not simply a memory location. Thanks in advance for all responses.
Well that's just because System.out.println by default calls the toString()-method of an object. In your case you have implemented your own toString in the child class, so this is used.
Only if you wouldn't have a toString in your Person and in your Student class, the toString from the Object-class would be called, which prints an object identification string, which consists of the class-name and the hexadecimal representation of the object's hashCode.
See the javadoc for the Object-class for more details: http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#toString()
println(Object)
per default calls the String.valueOf(...)
method.
Have a look at:
http://download.oracle.com/javase/1.4.2/docs/api/java/io/PrintStream.html#print(java.lang.Object)
and
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#valueOf(java.lang.Object)
I think in the book somewhere, it says that when doing System.out.println, it automatically calls the toString method if there's one.
You've overriden toString() in both classes - why on earth do you think the standard Object toString() method would be called?
精彩评论