用java完成以下需求 创建一个表示学生的类Student,封装所有属性。包括“姓名(name)”、“学号(studentNum)”、“班级(classNumber)”、“性别(sex)”、“年龄(age)”、 “性格(nature)”,以及所有属性的get、set方法。另加一个重写public String toString()方法把Student类对象的所有属性信息组合成一个字符串,并创建测试类实现该需求。
时间: 2024-03-19 16:46:29 浏览: 60
好的,以下是Java代码实现:
```java
public class Student {
private String name;
private String studentNum;
private String classNumber;
private String sex;
private int age;
private String nature;
public Student(String name, String studentNum, String classNumber, String sex, int age, String nature) {
this.name = name;
this.studentNum = studentNum;
this.classNumber = classNumber;
this.sex = sex;
this.age = age;
this.nature = nature;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentNum() {
return studentNum;
}
public void setStudentNum(String studentNum) {
this.studentNum = studentNum;
}
public String getClassNumber() {
return classNumber;
}
public void setClassNumber(String classNumber) {
this.classNumber = classNumber;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getNature() {
return nature;
}
public void setNature(String nature) {
this.nature = nature;
}
@Override
public String toString() {
return "姓名:" + name +
",学号:" + studentNum +
",班级:" + classNumber +
",性别:" + sex +
",年龄:" + age +
",性格:" + nature;
}
}
```
测试类实现:
```java
public class TestStudent {
public static void main(String[] args) {
Student student = new Student("小明", "20210001", "1班", "男", 18, "开朗");
System.out.println(student.toString());
}
}
```
输出结果为:
```
姓名:小明,学号:20210001,班级:1班,性别:男,年龄:18,性格:开朗
```
阅读全文