java编写一个封装学生的类Student,能够描述学生的“学号”、“姓名”、“性别”、“年龄”、“平均成绩′等基本属性,及获取属性、修改属性的方法和打印学生基本信息的print()方法。要求生成两个学生对象,在构造方法中进行初始化,并打印每个学生的基本信息。
时间: 2024-05-14 11:12:54 浏览: 148
以下是Java代码实现:
```
public class Student {
private String studentNo; // 学号
private String name; // 姓名
private String gender; // 性别
private int age; // 年龄
private double averageScore; // 平均成绩
public Student(String studentNo, String name, String gender, int age, double averageScore) {
this.studentNo = studentNo;
this.name = name;
this.gender = gender;
this.age = age;
this.averageScore = averageScore;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getAverageScore() {
return averageScore;
}
public void setAverageScore(double averageScore) {
this.averageScore = averageScore;
}
public void print() {
System.out.println("学号:" + studentNo);
System.out.println("姓名:" + name);
System.out.println("性别:" + gender);
System.out.println("年龄:" + age);
System.out.println("平均成绩:" + averageScore);
}
public static void main(String[] args) {
Student student1 = new Student("20210001", "张三", "男", 20, 85.5);
Student student2 = new Student("20210002", "李四", "女", 21, 90.0);
student1.print();
System.out.println();
student2.print();
}
}
```
输出结果为:
```
学号:20210001
姓名:张三
性别:男
年龄:20
平均成绩:85.5
学号:20210002
姓名:李四
性别:女
年龄:21
平均成绩:90.0
```
阅读全文