编写一个Java程序片段,以定义一个表示学生的类student。该类包括①这个类的属性有:学号,办好,姓名,性别,年龄,每个属性的类型用构造方法;②为每个属性编写getter和setter方法;③编写构造方法public Student(long studentID,int classID,String name,String sex,int age),为属性赋值;④为类Student增加一个方法public String toString(),该方法把Student类的对象的所有属性信息组合成一个字符串以便输出显示;⑤编写一个Java Application程序,创建Student类的对象,并验证新增加的功能。
时间: 2024-02-06 17:09:53 浏览: 40
下面是一个符合要求的Java程序片段:
```java
public class Student {
private long studentID;
private int classID;
private String name;
private String sex;
private int age;
public Student(long studentID, int classID, String name, String sex, int age) {
this.studentID = studentID;
this.classID = classID;
this.name = name;
this.sex = sex;
this.age = age;
}
public long getStudentID() {
return studentID;
}
public void setStudentID(long studentID) {
this.studentID = studentID;
}
public int getClassID() {
return classID;
}
public void setClassID(int classID) {
this.classID = classID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 toString() {
return "Student{" +
"studentID=" + studentID +
", classID=" + classID +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
public static void main(String[] args) {
Student student = new Student(1001L, 10, "Tom", "Male", 18);
System.out.println(student.toString());
}
}
```
在该程序中,我们定义了一个Student类,包含了学号、班级号、姓名、性别和年龄等属性,分别使用了构造方法来定义每个属性的类型;然后我们编写了对应的getter和setter方法,用于读取和设置每个属性的值。在构造方法中,我们为每个属性赋值。最后,我们编写了一个toString()方法,用于把Student类的对象的所有属性信息组合成一个字符串以便输出显示;并且在main()方法中创建了一个Student类的对象,并验证新增加的功能。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)