java 封装详解


封装详解:

 

package com.study.oop;
/*
      1.提高程序的安全性,保护数据
      2.隐藏代码实现的细节
      3.统一接口
      4.系统的可维护增加了

 */
public class Application {
    public static void main(String[] args) {

     student s1 =   new student();
      s1.setName("张三");
        System.out.println(s1.getName());
        s1.setAge(89);
        System.out.println(s1.getAge());
        s1.setId(2023);
        System.out.println(s1.getId());
    }
}
package com.study.oop;

public class student {
    private String name;
    private int age;
    private  int id;

    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

ALT + Insert 快捷键创造get / set    方法

相关