class Frog
{
private int id;
private String name;
public Frog(int id,String name)
{
this.id=id;
this.name=name;
}
public String toString(){
return id+" "+name;
}
}
public class Verify
{
public static void main(String[] args)
{
Frog frog1=new Frog(4,"maggie");
System.out.println(frog1);
}
}
在上面的代码中,我们得到了相同的结果传递" frog1"和" frog1.toString"在println
方法中为什么?请有人解释我。在第一种情况下,我们没有明确地调用toString
方法。
答案 0 :(得分:2)
因为println(Object)调用了String.valueOf方法的实体 最后调用给定Object的toString方法。
请参阅PrintStream和String的文档:
https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(java.lang.Object)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)
这是println(Object)方法的实现: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/PrintStream.java
786
787 public void println(Object x) {
788 String s = String.valueOf(x);
789 synchronized (this) {
790 print(s);
791 newLine();
792 }
793 }
以下是valueOf方法的实现: http://developer.classpath.org/doc/java/lang/String-source.html
/**
1629: * Returns a String representation of an Object. This is "null" if the
1630: * object is null, otherwise it is <code>obj.toString()</code> (which
1631: * can be null).
1632: *
1633: * @param obj the Object
1634: * @return the string conversion of obj
1635: */
1636: public static String valueOf(Object obj)
1637: {
1638: return obj == null ? "null" : obj.toString();
1639: }