diff --git a/src/class15/capsulation/Student.java b/src/class15/capsulation/Student.java new file mode 100644 index 0000000..9c7b10c --- /dev/null +++ b/src/class15/capsulation/Student.java @@ -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); + } +} diff --git a/src/class15/capsulation/Test.java b/src/class15/capsulation/Test.java new file mode 100644 index 0000000..54a43a9 --- /dev/null +++ b/src/class15/capsulation/Test.java @@ -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(); + } +} diff --git a/src/class15/thisdemo/Student.java b/src/class15/thisdemo/Student.java new file mode 100644 index 0000000..1b57eee --- /dev/null +++ b/src/class15/thisdemo/Student.java @@ -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); + } +} diff --git a/src/class15/thisdemo/Test.java b/src/class15/thisdemo/Test.java new file mode 100644 index 0000000..d6f4097 --- /dev/null +++ b/src/class15/thisdemo/Test.java @@ -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.变量名 + } +}