對面向對象而言:封裝就是將方法和屬性包裝到一個程序單元中,并且這個單元以類的形式實現。
簡單講:封閉就是將屬性私有化,提供公有方法來訪問私有屬性
封裝的作用:
松耦合:把對象想象成一個電池,這個電池不僅可以在相機中使用,也可以在遙控器,吹風機和剃須發等中使用, 我們說電池的松耦合性是非常好,而實現如此好的松耦合的前提就是對象有很好的封裝性
二、封裝的實現package com.pb.demo3;public class Person { private String name; //姓名 private String sex; //性別 private int age;//年齡 //設置getter和setter方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { if(sex.equals("男") || sex.equals("女")){ //設置性別限制,不合法的值將提示錯誤 this.sex = sex; }else{ System.out.println("性別不合法,性別只能是:男或者女"); } } public int getAge() { return age; } public void setAge(int age) { if(age>0 && age<=150){ //設置年齡限制 this.age = age; }else{ System.out.println("年齡只能在1-150歲之間"); } } public Person() { } public Person(String name, String sex, int age) { this.name = name; this.sex = sex; this.age = age; } public void say(){ System.out.println("自我介紹:"); System.out.println("姓名:"+this.name); System.out.println("性別:"+this.sex); System.out.println("年齡:"+this.age); }}測試類:
package com.pb.demo3;public class PersonTest { public static void main(String[] args) { Person person=new Person(); person.setName("韓冰"); //傳入不合法的值 person.setSex("中性"); //傳入不合法的值 person.setAge(200); //調用普通方法輸出 person.say(); }}結果:將提示錯誤
性別不合法,性別只能是:男或者女年齡只能在1-150歲之間自我介紹:姓名:韓冰性別:null年齡:0
從結果可以看出,不合法的值,將為該數據類型的初始值String 為null,int 為0
也可以在構造方法中為值進行初始化,這樣,設置值為不合法時,就會使用初始化的值
public Person() { this.name = "無名氏"; this.sex = "男"; this.age = 22; }再執行錯誤的值傳入時
package com.pb.demo3;public class PersonTest { public static void main(String[] args) { Person person=new Person(); person.setName("韓冰"); //傳入不合法的值 person.setSex("中性"); //傳入不合法的值 person.setAge(200); //調用普通方法輸出 person.say(); }}結果:
性別不合法,性別只能是:男或者女年齡只能在1-150歲之間自我介紹:姓名:韓冰性別:男年齡:22
新聞熱點
疑難解答