Search code examples
javatostringsuperbase-class

Java - Super.toString() method in base class?


My question is what is the reason to write Super.toString() in base class and what it returns and why ?

this is my code :

class Person    {
public String toString()    {
        return super.toString() /*+ "->" + "Person" + name + "------"*/;
        }
}

what is supposed to be return ? and thanks i m beginner in java


Solution

  • Your class Person should extend parent class where you define method toString(), otherwise your parent class is class Object and the native method of this class is going to be used:

        public String toString() {
            return getClass().getName() + "@" + Integer.toHexString(hashCode());
        }
    

    So, you will get a string that consisting of the name of the class of which the object is an instance, the at-sign @, and unsigned hexadecimal representation of the hash code of the object It's recommended that all classes (subclasses of class Object) override this method.