class Box{
double width;
double height;
double depth;
Box(double w,double h,double d){
width=w;
height=h;
depth=d;
}
public String toString(){    //为什么是自动调用的呢?
retrurn "a"+width+"b"+height+"c"+depth;
}
}
class toStringDemo{
public static void main(String args[]){
Box b=new Box(10,12,14);
String s="Box b"+b;
System.out.println(b);
System.out.println(s);
}
}

解决方案 »

  1.   

    toString是Object类的方法,如果你在你自己的类里面写了toString方法,相当于重写了toString方法,System.out.println();输出字符串自然会调用toString方法
      

  2.   

    String s="Box b"+b;
    System.out.println(b);
    System.out.println(s);
    在运行这些语句的时候  会自动调用obj的toString()方法
    但是你把它重写了 所以就自动调你的了
      

  3.   

    toString()就是Object类中的一个普通方法,并不会“自动调用”。System.out.println(b);
    这句中是println()方法调用了toString()方法,看一下PrintStream类的源码就知道了。"Box b"+b
    这句是因为Java的底层实现中重载了“+”运算符,当对Object执行相加操作时,就会调用其toString()方法。