Java面向物件之封裝詳解
阿新 • • 發佈:2021-10-03
封裝詳解
封裝
- 該露的露,該藏的藏
1、我們程式設計要追求“高內聚、低耦合”。高內聚:類的內部資料操作細節自己完成,不允許外部干涉;低耦合:僅暴露少量的方法給外部使用。 - 封裝(資料的隱藏)
1、通常,應禁止直接訪問一個物件中資料的實際表示,而應通過操作介面來訪問,這稱為資訊隱藏。 - 記住:
屬性私有,get/set。
封裝的作用:
- 提高程式的安全性,保護資料
- 隱藏程式碼的實現細節
- 統一介面
- 增加系統的可維護性
package OOP.Demo04; //類 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; } public int getAge() { return age; } public void setAge(int age) { if (age>120 || age <0){ this.age = 3; }else{ this.age = age; } } }
程式的呼叫
package OOP.Demo04; public class Application { public static void main(String[] args) { Student s1 = new Student(); s1.getName(); s1.setName("張三"); System.out.println(s1.getName()); s1.setAge(999); System.out.println(s1.getAge()); } }
@側耳聽智慧,專心求聰明 Turnging your ear to wisdom and applying your heart to understanding!被真相傷害總好過被謊言欺騙。