Object典型例子学生类重写toString() equals(Object obj)

package 学生;

public class Student {
    public Student() {
    }

    public Student(int id, int age, String name, String gender) {
        this.id = id;
        this.age = age;
        this.name = name;
        this.gender = gender;
    }

    /**
     * 成员变量,一般都设计成私有 可以使用公开的方法,来控制变量赋值和访问
     */
    private int id;
    private int age;
    private String name;
    private String gender;
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "[id=" + id + ", age=" + age + ", name=" + name + ", gender=" + gender + "]";
    }


    @Override
    public boolean equals(Object obj) {
        if(obj==null)return false;
        if(obj==this)return true;
        if(!(obj instanceof Student))return false;
        Student  s=(Student)obj;
        return age==s.age&&id==s.id&&name.equals(s.name)&&gender.equals(s.gender);
    }
    
}

···
package 学生;

public class Test {

public static void main(String[] args) {
    Student s1=new Student(1,18,"张三","男");
    Student s2=new Student(1,18,"张三","男");
    System.out.println(s1);
    System.out.println(s2);
    System.out.println(s1==s2);
    System.out.println(s1.equals(s2));
}

}
···
运行结果

[id=1, age=18, name=张三, gender=男]
[id=1, age=18, name=张三, gender=男]
false
true

你可能感兴趣的:(Object典型例子学生类重写toString() equals(Object obj))