问题
As per definition toString()
returns "Returns a string representation of the object as:
getClass().getName() + '@' + Integer.toHexString(hashCode())
But sometimes I could see even if it is not Overriden in our class, it returns the String associated with it. I mean Object.toString()
returns some String but not "ClassName@HexCode
".
When does this happen. Please let me know whats the reason behind this ??
回答1:
It's only possible if a class extends another class with overriden (or inherited overriden) toString().
回答2:
The default behavior of toString()
is to return the object as
getClass().getName() + '@' + Integer.toHexString(hashCode()).
But if you override toString()
in base class or child class you can specify the way your object should be printed.
Probably in your case its using the inherited method of your base class .
Ex:
class Person {
private String myName; // name of the person
private int myAge; // person's age
private String myGender; // 'M' for male, 'F' for female
// constructor
public Person(String name, int age, String gender) {
myName = name;
myAge = age;
myGender = gender;
}
public String getName() {
return myName;
}
public int getAge() {
return myAge;
}
public String getGender() {
return myGender;
}
public void setName(String name) {
myName = name;
}
public void setAge(int age) {
myAge = age;
}
public void setGender(String gender) {
myGender = gender;
}
public String toString() {
return myName + ", age: " + myAge + ", gender: " + myGender;
}
}
public class Teacher extends Person {
//...
}
calling `toString();` method will call inherited `tOString()` method of base class and will return `return myName + ", age: " + myAge + ", gender: " + myGender;`
来源:https://stackoverflow.com/questions/18592759/tostring-when-does-it-return-classnamehexvalue-string-value-associated-with