java中的toString函数

时间:2014-04-30 22:12:39   收藏:0   阅读:286

java中所有的类都是Object的子类,Object中实现了toString方法,在调用输出函数System.out.println(ob)时,默认调用对象ob所属类的toString方法。现对toString方法进行重载。

public class JavaTest
{
	public static void main(String[] args)
	{
		Student stu=new Student("cjc",24);
		Worker wor=new Worker("cjc",24);
		System.out.println(stu);
		System.out.println(wor);
	}	
}

class Student
{
	private String name;
	private int age;
	Student(String str,int num)
	{
		name=str;
		age=num;
	}
	public String toString()
	{
		return "My name is "+name+",I‘m "+age+"."; 
	}
}
class Worker
{
	public String name;
	public int age;
	Worker(String str,int num)
	{
		name=str;
		age=num;
	}
}
mamicode.com,码迷

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!