feat(class15): 封装设计,暴露方法

- 在 class15.capsulation 包中添加 Student 类,实现学生信息封装和成绩计算功能
- 在 class15.thisdemo 包中添加 Student 类,演示 this 关键字的使用
- 添加 Test 类进行功能测试
This commit is contained in:
2025-07-09 01:17:08 +08:00
parent 3d8c1f3012
commit 89511c1e84
4 changed files with 105 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
package class15.capsulation;
public class Student {
String name;
private int age;
private double chinese;
private double math;
public String getName()
{
return this.name;
}
public void setName(String name){
this.name = name;
}
// 两门成绩的设置和读取方法
public void setChinese(double chinese){
if(chinese>=0 && chinese<=100){
this.chinese = chinese;
}
else{
System.out.println("请输入正确的成绩");
}
}
public double getChinese(){
return this.chinese;
}
public void setMath(double math){
if(math>=0 && math<=100){
this.math = math;
}
else{
System.out.println("请输入正确的成绩");
}
}
public double getMath(){
return this.math;
}
public int getAge()
{
return this.age;
}
public void setAge(int age){
if(age>0 && age<=100){
this.age = age;
}else {
System.out.println("年龄数据非法!");
}
}
public void printAllScore()
{
System.out.println(name+"的总成绩是:"+(chinese+math));
}
public void printAverageScore()
{
System.out.println(name+"的平均成绩是:"+(chinese+math)/2);
}
}

View File

@@ -0,0 +1,15 @@
package class15.capsulation;
public class Test {
public static void main(String[] args) {
Student s1 = new Student();
s1.setAge(19);
s1.setChinese(90);
s1.setMath(80);
System.out.println(s1.getAge());
System.out.println(s1.getChinese());
System.out.println(s1.getMath());
s1.printAllScore();
s1.printAverageScore();
}
}

View File

@@ -0,0 +1,13 @@
package class15.thisdemo;
public class Student {
String name;
public void print(){
//this 是一个变量,在方法中,用于拿到当前对象
//哪个对象调用的print方法this就代表哪个对象
System.out.println(this);
}
public void printHobby(String name){
System.out.println(this.name + "喜欢" + name);
}
}

View File

@@ -0,0 +1,20 @@
package class15.thisdemo;
public class Test {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "张三";
//地址值相同
s1.print();
System.out.println(s1);
Student s2 = new Student();
s2.print();
System.out.println(s2);
Student s3 = new Student();
s3.name="汪苏泷";
s3.printHobby("唱歌!");
//this指向对象本身对象中的变量与方法变量名冲突时this可以解决变量冲突问题指向方法中的变量this.变量名
}
}