赞
踩
使用Java创建一个简单的学生类,内容包含学生的姓名,年龄,性别,学号。并且可以判断两个学生是否为同一个人(覆盖重写equals函数)
- public class student {
-
- private String name; //学生姓名
- private int age; //学生年龄
- private String sex; //学生性别
- private String stuNum; //学生学号
-
- //构造函数
- public student(String name, int age, String sex, String stuNum){
- this.name = name;
- this.age = age;
- this.sex = sex;
- this.stuNum = stuNum;
- }
-
- //获取年龄
- public int getStudentAge(){
- return age;
- }
-
- //获取性别
- public String getStudentSex(){
- return sex;
- }
-
- //获取学生号
- public String getStudentNumber(){
- return stuNum;
- }
-
- //获取学生姓名
- public String getStudentName(){
- return name;
- }
-
- //判断两个学生是否为一个人 覆盖equals函数
- @Override
- public boolean equals(Object st){
- if(this == st) return true;
- if(st ==null) return false;
- if(this.getClass() != st.getClass()) return false;
-
- student another = (student) st; // 强制类型转换成 student类
- // 调用toLowerCase() 在判断时可忽略大小写
- if (this.name.toLowerCase().equals(another.name.toLowerCase()) && this.sex.equals(another.sex) && this.stuNum.equals(another.stuNum) && (this.age == another.age)) return true;
- else return false;
- }
-
- }
测试类:
- public class StudentClassTest {
-
- public static void main (String[] args){
- student st1 = new student("Helen",25, "female", "ABC12359");
- student st2 = new student("helen",25, "female", "ABC12359");
- student st3 = new student("Juli",20, "female", "ABC12360");
- student st4 = new student("Helen",25, "female", "ABC12371");
- boolean flag1, flag2,flag3;
- flag1= st1.equals(st2);
- flag2= st1.equals(st3);
- flag3= st1.equals(st4);
- System.out.println("student1's name: " + st1.getStudentName());
- System.out.println("student1's sex: " + st1.getStudentSex());
- System.out.println("student1's age: " + st1.getStudentAge());
- System.out.println("student1's student number:" + st1.getStudentNumber());
- System.out.println("student1 equals to student2 " + flag1);
- System.out.println("student1 equals to student3 " + flag2);
- System.out.println("student1 equals to student4 " + flag3);
-
- }
-
- }
输出结果:
- student1's name: Helen
- student1's sex: female
- student1's age: 25
- student1's student number:ABC12359
- student1 equals to student2 true
- student1 equals to student3 false
- student1 equals to student4 false
参考资料:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。