feat(class15): 对象传参,数据业务分离

- 新增 Student 类,用于封装学生信息(姓名、语文成绩、数学成绩)
- 新增 StudentOperator 类,用于操作学生对象(计算总成绩和平均成绩)- 新增 Test 类,用于测试 Student 和 StudentOperator 类的功能
This commit is contained in:
2025-07-09 01:35:58 +08:00
parent 89511c1e84
commit ccb4da0550
3 changed files with 83 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
package class15.javabean;
public class Student {
private String name;
private double chinese;
private double math;
// 无参构造器
public Student() {
}
//提供一个有参构造器
public Student(String name, double chinese, double math) {
this.name = name;
this.chinese = chinese;
this.math = math;
}
//提供公开的getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getChinese() {
return chinese;
}
public void setChinese(double chinese) {
this.chinese = chinese;
}
public double getMath() {
return math;
}
public void setMath(double math) {
this.math = math;
}
}

View File

@@ -0,0 +1,15 @@
package class15.javabean;
public class StudentOperator {
private final Student s;
public StudentOperator(Student s){
this.s = s;
}
// 打印学生对象的总成绩
public void printTotalScore(){
System.out.println(s.getName()+"的总成绩是:" + (s.getChinese()+s.getMath()));
}
public void printAverageScore(){
System.out.println(s.getName()+"的平均成绩是:" + (s.getChinese()+s.getMath())/2);
}
}

View File

@@ -0,0 +1,20 @@
package class15.javabean;
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setName("波妞");
s.setChinese(100);
s.setMath(100);
System.out.println(s.getName() + "总成绩是:"+(s.getChinese() + s.getMath()));
Student s1 = new Student("小王", 100, 100);
System.out.println(s1.getName() + "总成绩是:"+(s1.getChinese() + s1.getMath()));
StudentOperator operator = new StudentOperator(s1);
operator.printTotalScore();
operator.printAverageScore();
}
}