我在 java编程思想里看的一段代码,各位高手帮忙解释一下:代码如下:
class Soap {
  private String s;
 
  Soap() {
    System.out.println("Soap()");
    s = new String("Constructed");
  }
  public String toString() { return s; }
}public class Bath {
  private String 
    // Initializing at point of definition:
    s1 = new String("Happy"), 
    s2 = "Happy", 
    s3, s4;
  Soap castille;
  int i;
  float toy;
  Bath() {
    System.out.println("Inside Bath()");
    s3 = new String("Joy");
    i = 47;
    toy = 3.14f;
    castille = new Soap();
  }
  void print() {
    // Delayed initialization:
    if(s4 == null)
      s4 = new String("Joy");
    System.out.println("s1 = " + s1);
    System.out.println("s2 = " + s2);
    System.out.println("s3 = " + s3);
    System.out.println("s4 = " + s4);
    System.out.println("i = " + i);
    System.out.println("toy = " + toy);
    System.out.println("castille = " + castille);
  }
  public static void main(String[] args) {
    Bath b = new Bath();
    b.print();
  }
}
运行的结果是:
Inside Bath()    
Soap()            //请问为什么输出这两条语句

解决方案 »

  1.   

    我来说下我的看法
    首先,Bath b= new Bath();
    它实例化一个对象,new的时候,调用Bath类的构造方法Bath(),则输出Inside Bath(),
    继续执行下面的代码,castille = new Soap();
    同前面一样,也要调用 Soap类的Soap()构造方法,输出Soap()了
    呵呵
    不知道这样说,LZ可否清楚
    谢谢
      

  2.   

    new Bath();先运行构造函数
    Bath() {
        System.out.println("Inside Bath()");
        s3 = new String("Joy");
     i = 47;
        toy = 3.14f;
        castille = new Soap();
      }
    得####:Inside Bath() 
    其中castille = new Soap();运行构造函数:
    Soap() {
        System.out.println("Soap()");
        s = new String("Constructed");
      }
    得####:Soap() 
      

  3.   

    Bath b= new Bath();
    调用bath
    先输出inside bath()
    在调用父类new soap()
    soap()
      

  4.   

    Bath b= new Bath();  //main函数里的。调用bath的构造函数,先输出inside bath()
    castille = new Soap();//bath的构造函数里的,在调用soap的构造函数,再输出soap()
      

  5.   

    就是当你创建一个类的实例对象的时候  它的构造方法会被  自动  调用
    如  Bath b = new Bath();  b被创建了  那它就要调用
     Bath() {
        System.out.println("Inside Bath()");
        s3 = new String("Joy");
        i = 47;
        toy = 3.14f;
        castille = new Soap();
      }
    这个构造了   所以就先打印出  Inside Bath()
     而后 你又创建了一个 castille  也就是 castille = new Soap();
    那它就又调用 Soap() {
        System.out.println("Soap()");
        s = new String("Constructed");
      }
    这个构造函数  打印出Soap()就是这样了