问题
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 Object
class method toSting()
.
来源:https://stackoverflow.com/questions/31906606/java-super-tostring-method-in-base-class