Java - 基类中的 Super.toString() 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31906606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Super.toString() method in base class?
提问by Kartik Shah
My question is what is the reason to write Super.toString() in base class and what it returns and why ?
我的问题是在基类中编写 Super.toString() 的原因是什么,它返回什么,为什么?
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
什么应该是回报?并感谢我的 Java 初学者
回答by Igor
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:
你的类 Person 应该扩展你定义 toString() 方法的父类,否则你的父类是类 Object 并且将使用这个类的本地方法:
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.
因此,您将得到一个字符串,其中包含对象是其实例的类的名称、@ 符号和对象哈希码的无符号十六进制表示。建议所有类(类 Object 的子类) ) 覆盖此方法。
回答by Gaur93
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()
.
super
关键字用于在继承的情况下调用父类方法。
每个类都是Object
java中类的子类,其非最终方法之一是toString()
.
所以super.toString()
调用Object
类方法toSting()
。