初学java第三天,新手上路,多多关照,请看下面的程序:class Soap       //定义类Soap
{
private String s ;
         Soap()
{
System.out.println("Soap()") ;
s = new String("Constructed") ;
}
         public String toString()
{
return s ;
}
}//定义类Bath
public class Bath
{
private String s1 = new String("Happy"),
   s2 = "Happy",
   s3, s4 ; private Soap castille ;
private int i ;
private float toy ; public Bath()
{
System.out.println("Inside Bath()") ;
s3 = new String("Joy") ;
i = 47 ;
toy = 3.14f ;
castille = new Soap() ;
} public String toString()
{
if(s4 == null)
s4 = new String("Joy") ; return 
"s1 = " + s1 +"\n" +
"s2 = " + s2 +"\n" +
"s3 = " + s3 +"\n" +
"s4 = " + s4 +"\n" +
"i = " + i + "\n" +
"toy = " + toy + "\n" +
"castille = " + castille ;
}
public static void main(String[] args) 
{
Bath b = new Bath() ;
System.out.println(b) ;
}
}
程序的输出为   Inside Bath()
               Soap()
               s1 = Happy
               s2 = Happy
               s3 = Joy
               s4 = Joy
               i = 47
               toy = 3.14
               castille = Constructed
请高手指点一下:对于程序为什么会有如此的输出结果我不是太明白,特别是对于在两个类中都出现的方法toString()的调用情况不清楚,希望热情的csdn高手们能够指教一下小弟我,谢谢!

解决方案 »

  1.   

    main是入口,所以先执行,于是首先new Bath();调用其构造函数输出第一行,里面又new Soap();输出第二行,构造结束;然后执行main的第2行,println(b);于是引起调用toString方法,因为对于非字符串类型,输出显示时都要默认调用tostring进行转换,于是输出下面各行.
      

  2.   

    谢谢楼上的解答。不过有一点我还是不太明白System.out.println(b),这条语句怎么能够默认调用totring呢,有什么规律吗?totring既不是类方法,也不是默认构造函数,为什么可以不经过调用而使用呢?
      

  3.   

    JAVA 编译器干的,它要这么干,谁也没办法。:)
      

  4.   

    toString()当然是一个类的成员方法,它是从java.lang.Object类继承下来的,因为java.lang.Object是类层次结构的根,所有的类都是从它继承而来,所以每个类都有toString()这个方法.
    在jdkdoc中有下面这一段关于toString()的描述:
        Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. 
        Returns a string representation of the object. In general, the 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. 
        The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', 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:  getClass().getName() + '@' + Integer.toHexString(hashCode())
      

  5.   

    为什么 s3 = Joy ?? ,s3 = new String("Joy") ;s4=????
           s4 = Joy