java语言equals,toString方法的重写
创建一个Student类,该有String类型的学号stuNo,String类型的姓名, 要求将该类所有的成员变量进行封装,并且提供公共的getter和setter方法, 重写equals方法,只要学生的学号相同即返回true,重写toString()方法, *toString方法返回值类似”姓名:张三 学号:201301 ”
操作方法
- 01
public class Test1 { public static void main(String[] args) { // TODO Auto-generated method stub Student s=new Student("201301","张三"); Student s1=new Student("201301","李四"); System.out.println(s.equals(s1)); System.out.println(s.toString()); } } class Student{ private String stuNo; private String name; public String getStuNo() { return stuNo; } public void setStuNo(String stuNo) { this.stuNo = stuNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Student(String stuNo, String name) { this.stuNo = stuNo; this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((stuNo == null) ? 0 : stuNo.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (stuNo == null) { if (other.stuNo != null) return false; } else if (!stuNo.equals(other.stuNo)) return false; return true; } public String toString(){ return "姓名="+name+",学号="+stuNo+""; }}