(十六)toString()的用法

  • 每一个非基本类型的对象都有一个toString()方法,而且当编译器需要一个String而你却只有一个对象时候,该方法便会被调用。
public class te {
	public String toString()
	{
		return "hahaha";
	}
	public static void main(String[] args) {
		te t=new te();
		System.out.println(t);  
		String s="123"+t;
		System.out.println(s);
	}
}
结果:
hahaha
123hahaha

 解析:  如果没有toString()方法,那么System.out.println(t); 输出的就是引用的地址,因为默认的toString()就是输出引用的地址,而且我们定义的方法正好覆盖掉了。

 

posted @ 2017-01-24 16:44  shyroke、  阅读(252)  评论(0编辑  收藏  举报
作者:shyroke 博客地址:http://www.cnblogs.com/shyroke/ 转载注明来源~