1 /* 2 标准的代码改进版 3 4 this:哪个对象调用那个方法,this就代表那个对象 5 */ 6 class Student { 7 private String name; 8 private int age; 9 10 public String getName() { 11 return name; //这里其实是隐含了this 12 } 13 14 public void setName(String name) { 15 this.name = name; 16 } 17 18 public int getAge() { 19 return age; 20 } 21 22 public void setAge(int age) { 23 this.age = age; 24 } 25 } 26 27 class StudentTest2 { 28 public static void main(String[] args) { 29 //创建一个对象 30 Student s1 = new Student(); 31 s1.setName("林青霞"); 32 s1.setAge(27); 33 System.out.println(s1.getName()+"---"+s1.getAge()); 34 35 //创建第二个对象 36 Student s2 = new Student(); 37 s2.setName("刘意"); 38 s2.setAge(30); 39 System.out.println(s2.getName()+"---"+s2.getAge()); 40 } 41 }
时间: 2024-11-17 17:11:47