toString : when does it return ClassName@HexValue, String Value associated with it

陌路散爱 提交于 2019-12-14 03:28:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!