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

自古美人都是妖i 提交于 2020-01-30 13:04:33

问题


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


回答1:


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.




回答2:


super keyword is used to call parent class methods in case of inheritance.
Every class is the child of Object class in java and one of its non-final methods is toString().
Sosuper.toString() calls Objectclass method toSting() .



来源:https://stackoverflow.com/questions/31906606/java-super-tostring-method-in-base-class

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