封装一个学生类StudentInfo,有成员属性:姓名、年龄、性别、英语成绩、数学成绩、语文成绩,有成员方法:求总分、求平均分、打印学生信息。然后在Test01类中创建对象进行测试。(成员变量私有化,并自定义构造方法)
时间: 2023-10-20 09:23:03 浏览: 55
好的,这是一个关于Java编程的问题,我可以回答。以下是封装一个学生类StudentInfo的代码示例:
```
public class StudentInfo {
private String name;
private int age;
private String gender;
private double englishScore;
private double mathScore;
private double chineseScore;
public StudentInfo(String name, int age, String gender, double englishScore, double mathScore, double chineseScore) {
this.name = name;
this.age = age;
this.gender = gender;
this.englishScore = englishScore;
this.mathScore = mathScore;
this.chineseScore = chineseScore;
}
public double getTotalScore() {
return englishScore + mathScore + chineseScore;
}
public double getAverageScore() {
return getTotalScore() / 3;
}
public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
System.out.println("English Score: " + englishScore);
System.out.println("Math Score: " + mathScore);
System.out.println("Chinese Score: " + chineseScore);
System.out.println("Total Score: " + getTotalScore());
System.out.println("Average Score: " + getAverageScore());
}
}
```
在Test01类中可以这样创建对象并进行测试:
```
public class Test01 {
public static void main(String[] args) {
StudentInfo student = new StudentInfo("张三", 18, "男", 85.5, 90.2, 92.8);
student.printInfo();
}
}
```
输出结果如下:
```
Name: 张三
Age: 18
Gender: 男
English Score: 85.5
Math Score: 90.2
Chinese Score: 92.8
Total Score: 268.5
Average Score: 89.5
```