定义一个学生类Student,成员变量包括姓名、性别、年龄、语文成绩、数学成绩和英语成绩,成员方法包括getxXX方法、setXXX方法、求总分和求平均分。
时间: 2024-12-18 09:26:24 浏览: 14
Get和Set方法-java类和对象
在Java中,你可以这样定义一个名为"Student"的基本类:
```java
public class Student {
// 成员变量
private String name;
private String gender;
private int age;
private double chineseScore;
private double mathScore;
private double englishScore;
// 构造函数
public Student(String name, String gender, int age, double chineseScore, double mathScore, double englishScore) {
this.name = name;
this.gender = gender;
this.age = age;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
// get方法获取成员变量
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
public double getChineseScore() {
return chineseScore;
}
public double getMathScore() {
return mathScore;
}
public double getEnglishScore() {
return englishScore;
}
// set方法设置成员变量
public void setName(String name) {
this.name = name;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setAge(int age) {
this.age = age;
}
public void setChineseScore(double chineseScore) {
this.chineseScore = chineseScore;
}
public void setMathScore(double mathScore) {
this.mathScore = mathScore;
}
public void setEnglishScore(double englishScore) {
this.englishScore = englishScore;
}
// 计算总分和平均分
public double getTotalScore() {
return chineseScore + mathScore + englishScore;
}
public double getAverageScore() {
if (totalScore > 0) {
return totalScore / 3.0;
} else {
throw new IllegalArgumentException("Total score cannot be zero.");
}
}
}
```
阅读全文