什么是java中的toString

时间:2013-10-29 03:06:36

标签: java

What is the function of  toString in here?
what is the need for toString

任何人都可以解释一下toString假设在这里做什么。我是java的新手,并且学习了很多新东西

public class Employee  
    {
       private String name;
       private String address;
       private int number;
       public Employee(String name, String address, int number)
       {
          System.out.println("Constructing an Employee");
          this.name = name;
          this.address = address;
          this.number = number;
       }




     public String toString() //what is  this function doing
       {
          return name + " " + address + " " + number;
       }

标题

3 个答案:

答案 0 :(得分:1)

考虑:

Employee coolDude = new Employee("Billy Bob McCool", "123 Main Str", "867-5309");
System.out.println(coolDude);

如果没有你要问的toString方法,这会打印出类名和一个看起来像垃圾的十六进制数,但它实际上是coolDude存在于toString的内存地址记忆。使用"Billy Bob McCool 123 Main Str 867-5309"方法,您可以实际打印有用的内容。在这种特定情况下,{{1}}。

答案 1 :(得分:0)

Object类的方法,它返回object的值。

根据Java Docs:

public String toString()

返回对象的字符串表示形式。通常,toString方法返回一个“文本表示”此对象的字符串。结果应该是一个简洁但信息丰富的表示,便于人们阅读。建议所有子类都重写此方法。 类Object的toString方法返回一个字符串,该字符串由对象为实例的类的名称,符号字符“@”和对象的哈希码的无符号十六进制表示组成。换句话说,此方法返回一个等于值的字符串:

  

返回:   对象的字符串表示。

refer java docs here

答案 2 :(得分:0)

来自java doc

/**
 * Returns a string representation of the object. In general, the
 * {@code toString} method returns a string that
 * "textually represents" this object. The result should
 * be a concise but informative representation that is easy for a
 * person to read.
 * It is recommended that all subclasses override this method.
 * <p>
 * The {@code toString} method for class {@code Object}
 * returns a string consisting of the name of the class of which the
 * object is an instance, the at-sign character `{@code @}', and
 * the unsigned hexadecimal representation of the hash code of the
 * object. In other words, this method returns a string equal to the
 * value of:
 * <blockquote>
 * <pre>
 * getClass().getName() + '@' + Integer.toHexString(hashCode())
 * </pre></blockquote>
 *
 * @return  a string representation of the object.
 */

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29