初学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高手们能够指教一下小弟我,谢谢!
{
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高手们能够指教一下小弟我,谢谢!
在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())
s4 = Joy