爱问知识人 爱问教育 医院库

Java中的组合语法的一个例子,有个地方不明白

首页

Java中的组合语法的一个例子,有个地方不明白

下面的例子是《ThinkinginJava》第三版中第142页的一个例子。本来这个程序要用到 mpletest.*这个包里的一些方法,大家没有这个包,所以为了方便,我把和这个包有关的语句注释掉了。不会影响程序的正常运行。程序代码如下://:c06:Bath.java//Constructorinitializationwithcomposition.//From'ThinkinginJava,3rded.'(c)BruceEckel2002//SeecopyrightnoticeinCopyRight.txt.// mpletest.*;classSoap{privateStrings;Soap(){ intln("Soap()");s=newString("Constructed");}publicStringtoString(){returns;}}publicclassBath{//privatestaticTestmonitor=newTest();privateString//Initializingatpointofd ("Happy"),s2="Happy",s3,s4;privateSoapcastille;privateinti;privatefloattoy;publicBath(){ intln("InsideBath()");s3=newString("Joy");i=47;toy=3.14f;castille=newSoap();}publicStringtoString(){if(s4==null)//Delayediniti ("Joy");return"s1="+s1+"\n"+"s2="+s2+"\n"+"s3="+s3+"\n"+"s4="+s4+"\n"+"i="+i+"\n"+"toy="+toy+"\n"+"castille="+castille;}publicstaticvoidmain(String[]args){Bathb=newBath(); intln(b);/*monitor.expect(newString[]{"InsideBath()","Soap()","s1=Happy","s2=Happy","s3=Joy","s4=Joy","i=47","toy=3.14","castille=Constructed"});*/}}///:~这个程序我能看懂,也都明白。但是我怎么也看不明白第144页的这段话:“请注意,在Bath的构造器中,有一行语句在所有初始化产生之前就已经执行了。如果没有在定义处初始化,那么除非发生了不可避免的运行期异常,否则将不能保证信息在发送给对象引用之前已经被初始化。”那位高手能把这段话给我讲明白?谢谢了

提交回答
好评回答
  • 2006-09-27 09:25:36
      也不知道第三版是谁翻译的,真够呛,原文如下:
    Note that in the Bath constructor, a statement is executed before any of the initialization take place。
       When you don't initialize at the point of definition, there's still no guarantee that you'll perform any initialization before you send a message to an object reference - except for the inevitable run-time exception。
       注意,再Bath的构造函数中,在任何初始化发生之前一个语句被执行( int("Inside Bath()");,但是这里的初始化是指Bath的成员变量)。当你不在定义成员的时候初始化(而在构造函数中),在你用(直译:发送一个消息)到这个对象的引用时,不能保证你已经运行了所有成员的初始化。
       产生这种情况可能因为不可避免的运行时exception。。。 也就是说,如果在这里抛出运行时异常的话,就不能保持下面的一系列初始化语句被执行。所以,在构造函数中初始化成员,不像在定义时初始化那样更得到保证。 翻译恶心了……。

    k***

    2006-09-27 09:25:36

其他答案

类似问题

换一换

相关推荐

正在加载...
最新问答 推荐信息 热门专题 热点推荐
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200

热点检索

  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 179-198
返回
顶部
帮助 意见
反馈

确定举报此问题

举报原因(必选):