Lev1

导航

重写父类Objcet的equals的方法

学生类

package cn.Student;
//学生类
public class Student {
        private String name;
        private int age;
        private int  id;
        public Student() {
        }
        public Student(String name,int age,int id) {
            this.name = name;
            this.age = age;
            this.id = id;
        }
        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 int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
                //重写equals()方法,如果学员学号、姓名都相同,证明是同一个学生
                //instanceof操作符用于判断一个引用类型所引用的对象是否是一个类的实例
        @Override
        public boolean equals(Object obj) {   //this 指的是当前对象
                if(this ==obj) {
                    return true;
                }
                if(!(obj instanceof Student)) {
                    return false;
                }
                Student k = (Student)obj;//强制类型转换 
                if(this.name.equals(k.name)&&this.age==k.age&&this.id==k.id) {
                    return true;
                }else {
                    return false;
                }
            
        }
        
        
}

测试类

package cn.Student;
import com.pangui.Dog;
public class Test {
        public static void main(String[] args) {
            Student t1 = new Student("老李",16,15901);
            Student t2 = new Student("老张",18,15955);
            Student t3 = new Student("老李",16,15901);
            Dog c = new Dog("豆豆",250 , -99,"哈士奇");
            System.out.println(t1.equals(t3));
            System.out.println(t1.equals(t2));
            System.out.println(t1.equals(c));
        }
        
}

 

posted on 2019-07-16 10:41  Lev1  阅读(649)  评论(0编辑  收藏  举报