java学生类的创建和使用

2024年11月27日 12:32
有1个网友回答
网友(1):

package student;

public class Student {

private static int count;

/**
* 班级号
*/

private String classNo;

/**
* 年龄
*/

private int age;

/**
* 性别
*/

private char sex;

/**
* 姓名
*/

private String name;

/**
* 学号
*/

private String stuNo;

public Student(String stuNo, String classNo, String name, char sex, int age) {
super();
this.age = age;
this.classNo = classNo;
this.name = name;
this.sex = sex;
this.stuNo = stuNo;
count++;
}

public static int getExsitingStudentCount() {
return count;
}

public String getClassNo() {
return classNo;
}

public void setClassNo(String classNo) {
this.classNo = classNo;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

/**
*
* @return F为男,M为女
*/
public String getSexString() {
return sex == 'F' ? "男" : "女";
}

public char getSex() {
return sex;
}

public void setSex(char sex) {
this.sex = sex;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getStuNo() {
return stuNo;
}

public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}

private String prop(String name, Object value, char sep) {
return sep + name + ":" + value;
}

public String toString() {
String desc = prop("学号", stuNo, '\0');
desc += prop("班号", classNo, ',');
desc += prop("姓名", name, ',');
desc += prop("性别", getSexString(), ',');
desc += prop("年龄", age, ',');
return desc;
}
}

import student.Student;

public class StudentTest {
public static void main(String[] args) {
Student s1 = new Student("No.1", "T1", "张三", 'F', 14);
Student s2 = new Student("No.1", "T1", "马莉", 'M', 13);
println(s1);
println(s2);
s1.setName("李四");
s1.setAge(12);

println("姓名", s1.getName());
println("年龄", s1.getAge());
printlnSeparator();
if (s1.getAge() > s2.getAge()) {
println(s1);
} else
println(s2);
}
private static void printlnSeparator(){
System.out.println("=============================");
}
public static void println(Student s) {
println("学号", s.getStuNo());
println("班级", s.getClassNo());
println("姓名", s.getName());
println("性别", s.getSexString());
println("年龄", s.getAge());
printlnSeparator();
}

public static void println(String prop, Object value) {
System.out.println(prop + ":" + value);
}
}