封装

 1 package OOP;
 2 //类  private 私有
 3 //封装的相关知识
 4 public class Test03 {
 5     private String name;//名字
 6    private int id;//学号
 7     private int age;//
 8     //用private时,需要在类中使用get和set进行封装,在main方法里面才能被调用;
 9     //get获得这个数据
10     public String getName() { return name; }
11     //set给这个数据设置一个值 快捷键:alt+inert.
12     public void setName(String name) { this.name = name; }
13 
14     public int getId() {return id; }
15     public void setId(int id) { this.id = id; }
16 
17     public int getAge() { return age; }
18     public void setAge(int age) {
19         if (age>120|| age<0){ this.age=3; }
20         else { this.age = age; }
21     }
22 }

 1 package OOP;
 2 
 3 public class Application {
 4 
 5     public static void main(String[] args) {
 6         Test03 S1 = new Test03();
 7         S1.setName("小明");
 8         System.out.println(S1.getName());
 9         S1.setAge(7);
10         System.out.println(S1.getAge()+"岁");
11     }
12 }

 

posted @ 2022-01-17 00:05  捞月亮的渔夫  阅读(36)  评论(0)    收藏  举报