重写object类的tostring方法

实例:

import java.util.Objects;

public class Test04 {
    public static void main(String[] args) {
        Student student1 = new Student(111,"wutiaolu");
        Student student2 = new Student(111,"wutiaolu");
        System.out.println(student1==student2);
        System.out.println(student1.equals(student2));
    }
}
class Student{
    int no;
    String school;

    public Student(){

    }

    public Student(int no, String school) {
        this.no = no;
        this.school = school;
    }

    @Override
    public String toString() {
        return "Student{" +
                "no=" + no +
                ", school='" + school + '\'' +
                '}';
    }

    //equals需求:当一个学生的学号相等,且学校相同时,表示同一个学生
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return no == student.no &&
                Objects.equals(school, student.school);
    }

你可能感兴趣的:(重写object类的tostring方法)