封装详解

封装

  • 该漏的漏,该藏的藏
    • 我们程序设计要追求“高内聚,低耦合”。高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用。
  • 封装(数据的隐藏)
    • 通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏。
  • 记住这句话就够了:属性私有,get/set
  • Student类
//类     private: 私有
public class Student {

    //属性私有
    private String name;    //名字
    private int id;     //学号
    private char sex;   //性别
    private int age;

    public int getAge() {
        return age;
    }

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

    //提供一些可以操作这个属性的方法!
    //提供一些public的get、set方法
    //get   获得这个数据
    public String getName(){
        return this.name;
    }

    //set   给这个数据设置值
    public void setName(String name){
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }
//alt + insert

}
  • Application类
/*
    1.提高程序的安全性,保护数据
    2.隐藏代码的实现细节
    3.统一接口
    4.系统的可维护性增加了
 */
public class Application {
    public static void main(String[] args) {
        Student student = new Student();

        student.setAge(999);    //不合法的
        System.out.println(student.getAge());
    }
}
posted @   摘星丶仙  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示