Object上帝类就有一个toString方法,我们定义自己类的时候直接复写该方法就行了,直接上代码
public class User {
private int id;
private String name;
public User(int id,String name){
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "user:"+id+"--"+name;
}
public static void main(String[] args) {
User u = new User(1,"lily");
System.out.println(u);//此处打印User对象时候,直接回调用User对象里面的toString方法
}
}
|