类中的toString()是一种固定写法,如果提供此方法,则调用时系统会默认使用此方法输出字符串,如果为其它名称,则需要手动输出c.xxx()。源代码如下:
public class Person { String name="jack"; int age=20; String sex="F"; public Person(){ //name="jack"; } public Person(String name, int age, String sex){ this.name = name; this.age = age; this.sex = sex; } //一种固定写法,如果提供此方法,则调用时系统会默认使用此方法输出字符串,如果为其它名称,则需要手动输出c.xxx() public String toString(){ return "name="+name+",age="+age+",sex="+sex; } public void getInfo(){ System.out.println("The person's name is "+name+", age is "+age+", and sex is "+sex); } public static void main( String args[]){ Person p1 = new Person("john", 11, "M"); p1.getInfo(); System.out.println(p1); Person p2 = new Person(); p2.getInfo(); System.out.println(p2.toString()); } }