1、第一步:新建一个实体类,提供get/set方法,代码如下:String name;int age;public String getName() { return name;}public void setName(String name) { this.name = name;}public int getAge() { return age;}public void setAge(int age) { this.age = age;}
2、第二步:写一个main方法,并new Student()对象,设置age为9,代码如下:public static void main(String[] args) { Student student = new Student(); student.setAge(9); System.out.println(student.getAge());}
3、第三步:测试main方法里面的数据是不是9,就setter了多少通过getter就是多少,运行结果如图:
4、第四步:通过上面结果看错并没有改变,假如要给每一个age加2呢,这时只要在setter里面添加如下代码即可:public void setAge(int age) { age += 2; this.age = age;}
5、第五步:重新运行main方法,就可以看到age从设置的9变成11,已经对参数进行了改变,如图:
6、第六步:还比如对age进行限制,小于10岁不让设置,代码如下:public void setAge(int age) { if(age < 10) throw new RuntimeException("age太小了"); this.age = age;}