Java的封装

Java的封装

package Demo02;

public class Person {
   //属性私有,private 私有的
   //封装一般对属性进行封装
   private String name;
   private int ID;
   private int age;

   //get 获取数据
   public String getName(){
       return this.name;
  }

   //set 给数据赋值
   public void setName(String name){
       this.name=name;
  }

   //alt + insert


   public int getID() {
       return ID;
  }

   public void setID(int ID) {
       this.ID = ID;
  }

   public int getAge() {
       return age;
  }

   public void setAge(int age) {
       if(age>120 || age<0){
           this.age=3;
      }else {
           this.age=age;
      }
  }
}
package Demo02;

public class Application {
   public static void main(String[] args) {
       Person person = new Person();
       System.out.println(person.getName());//null
       person.setName("王志");
       System.out.println(person.getName());//王志
       //通过了setName赋值过了所以是"王志"
       System.out.println(person.getID());//0
       person.setID(20);
       System.out.println(person.getID());//20
       System.out.println(person.getAge());//0
       person.setAge(150);
       System.out.println(person.getAge());
       //输出为3,超过了age>120 || age<0
       person.setAge(70);
       System.out.println(person.getAge());//70
  }
}

 

posted @ 2021-03-13 16:59  默默努力的路人甲  阅读(180)  评论(0)    收藏  举报