面向对象程序设计(Java)实验5

实验要求

编写一Person类,通过重写toString()、equals()、hashcode()方法,实现可以对Person类实例化出的对象进行equals和==的比较。

实验内容

package test5;

import java.util.Objects;

class person {
    String sex;
    int age;
    String name;
    boolean notempty;
    public person(String sex,int age,String name){
        this.sex = sex;
        this.age = age;
        this.name = name;
        this.notempty = true;
    }

    @Override
    public String toString() {
        return "person{" +
                "sex='" + sex + '\'' +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        person person = (person) o;
        return age == person.age && sex.equals(person.sex) && name.equals(person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(sex, age, name);
    }

    public static void main(String args[]){
        person p1 = new person("男",20,"张三");
        person p2 = new person("男",20,"张三");
        System.out.println("p1 is " + p1 );
        System.out.println("p2 is " + p2 );
        System.out.println(p1.hashCode() == p2.hashCode());
        System.out.println(p1 == p2);
        System.out.println(p1.equals(p2));
    }
}

在这里插入图片描述

posted @ 2022-04-15 19:46  CK_0ff  阅读(139)  评论(0编辑  收藏  举报