print的时候其实就调用了实例的toString()方法,你可以重写这个方法public class Test{ public static void main(String[] args){ Test t = new Test(); System.out.println(t); } public String toString(){ return "this is the Test's instance"; } }你的print就会输出 this is the Test's instance
呵呵,我总结:)System.out.println(t);等同于 System.out.println(t.toString);标准的toString是: << public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } >>print的时候其实就调用了实例的toString()方法,你可以重写这个方法public class Test{ public static void main(String[] args){ Test t = new Test(); System.out.println(t); } public String toString(){ return "this is the Test's instance"; } }你的print就会输出 this is the Test's instance因为你没有覆写toString()函数,所以继承自Object.toString(),印出的是该对象的classname和内存地址。
System.out.println(t.toString);
public static void main(String[] args){
Test t = new Test();
System.out.println(t);
}
public String toString(){
return "this is the Test's instance";
}
}你的print就会输出
this is the Test's instance
<<
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
>>
因为你没有覆写toString()函数,所以继承自Object.toString(),印出的是该对象的classname和内存地址。
System.out.println(t.toString);标准的toString是:
<<
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
>>print的时候其实就调用了实例的toString()方法,你可以重写这个方法public class Test{
public static void main(String[] args){
Test t = new Test();
System.out.println(t);
}
public String toString(){
return "this is the Test's instance";
}
}你的print就会输出
this is the Test's instance因为你没有覆写toString()函数,所以继承自Object.toString(),印出的是该对象的classname和内存地址。