toString类是Object类的方法,所有的类都要继承Object,所以所有的类都有这个默认的toString()方法
toString()方法的源代码为
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
package Experience;
public class Test {
int a=1;
int b=2;
Test(int a,int b){
this.a=a;
this.b=b;
}
public static void main(String[] args){
Test test=new Test(3,4);
System.out.println(test.toString());
}
}
所有对象调用这个方法,都会返回一个"包名.类名+@+对象的哈希码值"
为了让这个方法的返回值更有意义,所有的子类建议都重写这个方法
package Experience;
public class Test {
int a=1;
int b=2;
Test(int a,int b){
this.a=a;
this.b=b;
}
@Override
public String toString(){
return "a="+a+",b="+b;
}
public static void main(String[] args){
Test test=new Test(3,4);
System.out.println(test.toString());
}
}
注意:这个方法的返回值类型是String类型,不能return a+b;