当前位置:   article > 正文

Java创建一个简单的学生类_java定义一个学生类,包括学号,姓名,性别

java定义一个学生类,包括学号,姓名,性别

使用Java创建一个简单的学生类,内容包含学生的姓名,年龄,性别,学号。并且可以判断两个学生是否为同一个人(覆盖重写equals函数)

  1. public class student {
  2. private String name; //学生姓名
  3. private int age; //学生年龄
  4. private String sex; //学生性别
  5. private String stuNum; //学生学号
  6. //构造函数
  7. public student(String name, int age, String sex, String stuNum){
  8. this.name = name;
  9. this.age = age;
  10. this.sex = sex;
  11. this.stuNum = stuNum;
  12. }
  13. //获取年龄
  14. public int getStudentAge(){
  15. return age;
  16. }
  17. //获取性别
  18. public String getStudentSex(){
  19. return sex;
  20. }
  21. //获取学生号
  22. public String getStudentNumber(){
  23. return stuNum;
  24. }
  25. //获取学生姓名
  26. public String getStudentName(){
  27. return name;
  28. }
  29. //判断两个学生是否为一个人 覆盖equals函数
  30. @Override
  31. public boolean equals(Object st){
  32. if(this == st) return true;
  33. if(st ==null) return false;
  34. if(this.getClass() != st.getClass()) return false;
  35. student another = (student) st; // 强制类型转换成 student类
  36. // 调用toLowerCase() 在判断时可忽略大小写
  37. if (this.name.toLowerCase().equals(another.name.toLowerCase()) && this.sex.equals(another.sex) && this.stuNum.equals(another.stuNum) && (this.age == another.age)) return true;
  38. else return false;
  39. }
  40. }

测试类:

  1. public class StudentClassTest {
  2. public static void main (String[] args){
  3. student st1 = new student("Helen",25, "female", "ABC12359");
  4. student st2 = new student("helen",25, "female", "ABC12359");
  5. student st3 = new student("Juli",20, "female", "ABC12360");
  6. student st4 = new student("Helen",25, "female", "ABC12371");
  7. boolean flag1, flag2,flag3;
  8. flag1= st1.equals(st2);
  9. flag2= st1.equals(st3);
  10. flag3= st1.equals(st4);
  11. System.out.println("student1's name: " + st1.getStudentName());
  12. System.out.println("student1's sex: " + st1.getStudentSex());
  13. System.out.println("student1's age: " + st1.getStudentAge());
  14. System.out.println("student1's student number:" + st1.getStudentNumber());
  15. System.out.println("student1 equals to student2 " + flag1);
  16. System.out.println("student1 equals to student3 " + flag2);
  17. System.out.println("student1 equals to student4 " + flag3);
  18. }
  19. }

输出结果:

  1. student1's name: Helen
  2. student1's sex: female
  3. student1's age: 25
  4. student1's student number:ABC12359
  5. student1 equals to student2 true
  6. student1 equals to student3 false
  7. student1 equals to student4 false

参考资料:

https://haicoder.net/java/java-class-demo.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/244449?site
推荐阅读
相关标签
  

闽ICP备14008679号