封装

作者: 媛猿YY | 来源:发表于2021-04-15 16:33 被阅读0次

    定义:

    1. 将类的某些信息隐藏在内部,不允许外部程序直接访问
    2. 通过该 类提供的方法来实现对隐藏信息的操作和访问
    3. 隐藏对象的信息
    4. 留出访问的接口

    特点

    1. 只能通过规定的方法访问数据
    2. 隐藏类的实例细节,方便修改和实现

    步骤

    1. 修改属性的可见性为private
    2. 创建get/set方法
      Cat.java
     private String name;//昵称
    //   创建 get/set方法
    //    在get/set方法中添加对属性的限定
        public void setNmae(String name) {
            this.name = name;
    
        }
    
        public String getName() {
            return "我是一只名加" + this.name + "的猫咪";
        }
    

    catTest.java

            Cat two = new Cat();
            two.setNmae("凡凡");
            System.out.println(one.getName());
    

    构造函数调用set函数给属性赋值,如此就可以避免写多次判断

     public Cat(int month) {
            this.setMonth(month);
        }
    public void setMonth(int month) {
            if (month <= 0) {
                System.out.println("输入信息有误,年龄必须是大于0");
            } else {
                this.month = month;
            }
        }
    

    相关文章

      网友评论

          本文标题:封装

          本文链接:https://www.haomeiwen.com/subject/qmmllltx.html