日期:2014-05-20 浏览次数:20789 次
package com.org.sxt.overload; public class OverLoad { public static void main(String[] args) { Person p = new Person(); Person p1 = new Person(2); Person p2 = new Person(3, 22); System.out.println("p: " + p); System.out.println("p1: " + p1); System.out.println("p2: " + p2); } } class Person { int id; int age; Person() { id = 1; age = 20; } Person(int _id) { id = _id; age = 21; } Person(int _id, int _age) { id = _id; age = _age; } public String toString() { return "Person id=" + id + " age=" + age; } }
------解决方案--------------------
在Person中重写toString()方法
public String toString(){
return "this.id = " + this.id + " this.age=" + this.age;
}
然后在main()方法中
System.out.println(p.toString);
System.out.println(p1.toString);
System.out.println(p2.toString);
------解决方案--------------------
原理就是在下面语句中
System.out.println("p: " + p);
计算"p: " + p时会自动调用p.toString()
等价于
"p: " + p.toString()
如果这样写System.out.println(p);
也等价于
System.out.println(p.toString());