封裝及其作用Java

  • 2022 年 2 月 22 日
  • 筆記

封裝

  • 該露的露,該藏的藏

    • 我們程式設計要求」高內聚,低耦合「。高內聚就是類的內部數據操作細節自己完成,不允許外部干涉;低耦合:僅暴漏少量的方法給外部使用

  • 封裝(數據的隱藏):

    • 通常,應禁止直接訪問一個對象中數據的實際表示,而應通過操作介面來訪問,這稱為資訊隱藏
  • 記住這句話就夠了:屬性私有,get/set

作用

1.提高程式的安全性,保護數據

2.隱藏程式碼的實現細節

3.統一介面

4.系統可維護性增加了

public class Student {
//屬性私有
    private String name;//    名字

    private int id;//    學號
    private int age;

    private char sex;//    性別

//提供一些可以操作這個屬性的方法
//    提供public的get,set方法
//get 獲取這個數據
    public String getName() {
        return 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;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        if (age>120||age<0){
            this.age = 1;
        }else {
            this.age = age;
        }

    }
}


public class Appliocation2 {
    public static void main(String[] args) {
        Student student=new Student();
//        student.name不行
        student.setName("xiaoming");
        System.out.println(student.getName());

        student.setAge(180);
        System.out.println(student.getAge());
        student.setAge(4);
        System.out.println(student.getAge());
    }

}