打印对象 = 打印对象的 toString 方法;
如果类中的 toString 方法没有被重写,那么打印 —— 包名@地址值
1、未重写 toString 方法的 Person 类
public class Person {
private String name;
private int num;
public Person(String name, int num) {
this.name = this.name;
this.num = this.num;
}
public String getName() {
return name;
}
public int getNum() {
return num;
}
}
public class test {
public static void main(String[] args) {
Person p = new Person("陈志海",24);
// 打印对象 = 打印对象的地址值 = 打印对象的 toString 方法
System.out.println(p);
System.out.println(p.toString());
}
}
demo110303.Person@1540e19d
demo110303.Person@1540e19d
2、重写 toString 方法的 Person 类
Alt + Insert / 右击 → Generate
public class Person {
private String name;
private int num;
public Person(String name, int num) {
this.name = this.name;
this.num = this.num;
}
public String getName() {
return name;
}
public int getNum() {
return num;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", num=" + num +
'}';
}
}
public class test {
public static void main(String[] args) {
Person p = new Person("陈志海",24);
// 打印对象 = 打印对象的地址值 = 打印对象的 toString 方法
System.out.println(p);
System.out.println(p.toString());
}
}
Person{name='null', num=0}
Person{name='null', num=0}