package com.student;
//重写比较规则,判断Student两学员是否是同一个对象
//如果两学员的姓名学号相同则是同一个对象
public class Student {
//学员属性
private String name;
private int id;
private String sex;
/**
* @param name
* @param id
*/
public Student(String name, int id,String sex) {
this.name = name;
this.id = id;
this.sex = sex;
}
//重写equals方法
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(!(obj instanceof Student)) {
return false;
}
Student s = (Student)obj;
if(this.name.equals(s.name) && this.id==s.id) {
return true;
}else {
return false;
}
}
//重写equals方法
// public boolean equals(Object obj) {
// if(obj instanceof Student) {
// Student stu = (Student)obj;
// if(this.name.equals(stu.name)&&this.id==stu.id) {
// return true;
// }
// }
// return false;
// }
//重写toStrint方法
public String toString() {
return name;
}
//测试方法
public static void main(String[] args) {
Student s1 = new Student("张三", 12,"男");
Student s2 = new Student("张三",12,"男");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s1);
String s = "bbb";
//打印输出s的时候默认调取了toString()方法
System.out.println(s);
}
}
![]()