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;
}
}
原文地址:http://blog.csdn.net/cjc211322/article/details/24809649