public class ConstructorMethod {
public static void main(String[] args)
{
Sample s=new Sample("Hello");
Sample[] sa=new Sample[2];
sa[0]=s;
sa[1]=new Sample("World");
for(int i=0;i<sa.length;i++)
System.out.print(sa+" ");
System.out.println();
}
}
class Sample
{
String s;//=new String("Constructed");
Sample()
{
s=new String("Constructor");
System.out.println("Smaple");
}
Sample(String s)
{
System.out.println("Sample with "+s);
s=new String("Constructor");
}
public String toString()
{
return s;
}
}
运行结果怎么会是null.但是如果把注释弄掉,就可以正常显示为Constructor.
或者把变量s换成名字,比如str,又可以正常显示,这是为什么
public static void main(String[] args)
{
Sample s=new Sample("Hello");
Sample[] sa=new Sample[2];
sa[0]=s;
sa[1]=new Sample("World");
for(int i=0;i<sa.length;i++)
System.out.print(sa+" ");
System.out.println();
}
}
class Sample
{
String s;//=new String("Constructed");
Sample()
{
s=new String("Constructor");
System.out.println("Smaple");
}
Sample(String s)
{
System.out.println("Sample with "+s);
s=new String("Constructor");
}
public String toString()
{
return s;
}
}
运行结果怎么会是null.但是如果把注释弄掉,就可以正常显示为Constructor.
或者把变量s换成名字,比如str,又可以正常显示,这是为什么
你这句打印的是sa这个数组,调用的不是你的toString()方法。你改下就好了
System.out.print(sa[i]+" ");
这样就可以了
Sample(String s)
{
System.out.println("Sample with "+s);
this.s=new String("Constructor");
}