toString方法
基本介绍
- 默认返回:全类名+@+哈希值的十六进制,【查看object的toString方法】子类往往重写toString方法,用于返回对象的属性信息。
- 重写toString方法,打印对象或者拼接对象时,都会自动调用该对象的toString形式。
- 当直接输出一个对象时,toString方法会被默认的调用。
重写toString方法的必要性
未重写的打印结果
public class Stu {
public String name;
public Stu(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public int age;
public String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
测试类
public class test01 {
public static void main(String[] args) {
Stu stu = new Stu("bob",10,"nan");
System.out.println(stu);
}
}
重写后
public class Stu {
public String name;
public Stu(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public int age;
public String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
@Override
public String toString() {
return "Stu{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public void setSex(String sex) {
this.sex = sex;
}
}