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);
}
}
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);
}
}
System.out.println(b);
System.out.println(s);
在运行这些语句的时候 会自动调用obj的toString()方法
但是你把它重写了 所以就自动调你的了
这句中是println()方法调用了toString()方法,看一下PrintStream类的源码就知道了。"Box b"+b
这句是因为Java的底层实现中重载了“+”运算符,当对Object执行相加操作时,就会调用其toString()方法。