-3
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;
       }

标题

4

3 回答 3

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"

于 2013-10-29T03:11:38.630 回答
0

Object 类的方法,返回对象的值。

根据 Java 文档:

public String toString()

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

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

在此处参考 java 文档

于 2013-10-29T03:07:44.593 回答
0

来自 java 文档

/**
 * 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

于 2013-10-29T03:08:15.657 回答