日期:2014-05-20  浏览次数:20829 次

this,toString一些基本的问题,请多指教
class   method  
{
double   x=5,y=6;
void   test(double   y)
{
System.out.println(y);
test(this);
}
public   String   toString()
{
return   x+ ", "+y;
}
void   test(String   a)
{
System.out.println(a);
}
void   test(Object   a)
{
System.out.println(a);
}
public   static   void   main(String   args[])
{
method   a=new   method();
a.test(8);
a.test( "hello ");
}
}


能否谈下this,及toString的具体用法!具体一点最好!还有解释一下本程序中a.test(8)和a.test( "hello ")执行哪个函数?为什么??

我郁闷,一直被他们困扰着!!!!


请大家帮下,不胜感激!!!!

------解决方案--------------------
this 一般指调用当前方法的对象
如a.test(8);
则会先调用

void test(double y)
{
System.out.println(y);
test(this);
}

这个方法,而这个方法体的又调用了test(this);方法 这里的this就是指
method a=new method();的a对象。即test(a);

所以程序又跳到
void test(Object a)
{
System.out.println(a);
}

这个方法中。
这几个test()方法都是方法的重载,虽然方法名相同,但运行时 JVM会根据参数列表来确定你到底调的哪个方法。

------解决方案--------------------
method a=new method();
如果加一句System.out.println(a);应该打印出a 的地址。但你重写toString后。应该打印出toString方法中的东东。

总之一句话。System.out.println(a);调用toString方法。
------解决方案--------------------
public static void main(String args[])
{
method a=new method();
a.test(8);
a.test( "hello ");
}
method a =new method()// 创建一个引用a指向method对象
a.test(8); //通过引用a调用method对象的test方法,这里参数是个8,提升为double类型,那么8将会传递给方法 void test(double y)
{
System.out.println(y);
test(this);
}
执行的结果就是先输出 8,再调用 test(this) ,这里this是个指向当前对象的引用,结果是this引用传递给方法 void test(Object a)
{
System.out.println(a);
}
执行结果是将会打印这个对象,会自动调用object.toString()方法打印出这个对象的信息,但是由于这里重写了toString()方法,
public String toString()
{
return x+ ", "+y;
} 执行的结果将会返回 5.0,6.0
最后a.test( "hello ") 输出hello