day25 封装详解

封装

  • 该露的露,该藏的藏

    • 我们程序设计要追求“高内聚,低耦合”。高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用。
  • 封装(数据的隐藏)

    • 通常,应禁止直接访问一个对象中数据的实际表示,而应该通过操作接口访问,这称为信息隐藏。
  • 记住这句话就够了:属性私有,get/set

例:

package com.oop.demo04;

import jdk.nashorn.internal.ir.ReturnNode;

//类     private:私有
public class Student {

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

    //提供一些可以操作这个属性的方法
    //提供一些public的get、set方法

    //get   获得这个数据
    public String getName(){
        return this.name;
    }
    //set 给这个数据设置值
    public void setName(String name){
        this.name = name;
    }
    //slt+insert    自动生成get set


    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;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age>120||age<0) {//不合法
            this.age = 3;
        }else {
            this.age = age;
        }
    }
}
/*
package com.oop;

import com.oop.demo04.Student;


1. 提高程序的安全性,保护数据
2. 隐藏代码的实现细节
3. 统一接口
4. 提供系统可维护性

public class Application {
    public static void main(String[] args) {
        Student wc = new Student();

        wc.setName("abc");
        System.out.println(wc.getName());
        wc.setAge(99);
        System.out.println(wc.getAge());
    }
}
*/
posted @ 2021-03-20 22:12  圈圈子  阅读(43)  评论(0)    收藏  举报