封装详解。
封裝詳解
1.該露的露,該藏的藏
? 我們程序設計的追求“高內聚,低耦合”。
? 高內聚:就是類的內部數據操作細節自己完成,不允許外部干涉;
? 低耦合:僅暴露少量的方法給外部使用。
2封裝(數據的隱藏)
? 通常,應禁止直接訪問一個對象的數據的實際表示,而應通過操作接口來訪問,這稱為信息隱藏。
記住這句話就夠了:屬性私有,get/set
封裝的意義:
1.提高程序的安全性,保護數據
2.隱藏代碼的實現細節
3.統一接口
4.系統可維護增加了
import com.oop.demo04.Student;//一個項目應該這存在一個main方法 public class Application {public static void main(String[] args) {Student s1= new Student();s1.setName("你好");System.out.println(s1.getName());s1.setAge(-1);//不合法的System.out.println(s1.getAge());} } //類 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;}public int getId(){return this.id;}public void setId(int id){this.id=id;}public char getSex(){return this.sex;}public void setSex(char sex){this.sex=sex;}public int getAge(){return this.age;}public void setAge(int age){if(age>120||age<0){//不合法System.out.println("年齡不合法");}else {this.age=age;}}//alt +insert總結
- 上一篇: html-下拉框、文本域、文件域
- 下一篇: html-初识表单post和get提交