1. 程式人生 > >Java基礎--面向對象編程2(封裝)

Java基礎--面向對象編程2(封裝)

gets ner 程序 heal 設定 .sh println str 編程

1.封裝的定義:

封裝:將類的某些信息隱藏在類內部,不允許外部程序直接訪問,而是通過該類提供的方法來實現對隱藏信息的操作和訪問。

2. 為什麽需要封裝?封裝的作用和含義?

首先思考一個問題:當我們要看電視時,只需要按一下開關和換臺就可以了。有必要了解電視機內部的結構嗎?有必要碰碰顯像管嗎?

答案顯然是否定的。隱藏對象內部的復雜性,只對外公開簡單的接口。便於外界調用,從而提高系統的可擴展性、可維護性。

我們程序設計要追求“高內聚,低耦合”。高內聚是類的內部數據操作細節自己完成,不允許外部幹涉;低耦合是僅暴露少量的方法給外部使用。

3.程序封裝的步驟

[1]

屬性私有化

在聲明類的屬性時在用private進行修飾。

[2]提供公共的設置器和訪問器

在類中添加set()方法和get()方法充當公共的設置器和訪問器。

[3]在設置器和訪問器中添加業務校驗邏輯

在set()方法和get()方法中設置判斷語句,對對象中輸入的屬性值進行判斷,過濾掉錯誤的數據。

4.實例

以下程序為創建一個Dog類:

a.在屬性聲明時,對屬性進行private修飾進行私有化。

b.通過添加setName(String name)方法,對當對象的name屬性值為空時,進行系統提醒並賦予默認值。同理,setHealth(int health)和setLove(int love)方法對health和love屬性值進行數值限制,當這2個對象的屬性值超過100和小於0時,系統會進行提醒並默認賦值。

 1 public class Dog{
 2     private String name;
 3     private String strain;
 4     private int health;
 5     private int love;
 6     public void setName(String name){
 7         if(name.equals("")){
 8             System.out.println("寵物名字不能沒有名字,系統默認將寵物取名為天天");
 9             this.name="天天";
10 }else{ 11 this.name=name; 12 } 13 } 14 public String getName(){ 15 return this.name; 16 } 17 public void setStrain(String strain){ 18 this.strain=strain; 19 } 20 21 public String getStrain(){ 22 return this.strain; 23 } 24 public void setHealth(int health){ 25 if(health>100 || health<0){ 26 System.out.println("寵物健康值輸入有誤,系統默認將健康值設定為60"); 27 this.health=60; 28 }else{ 29 this.health=health; 30 } 31 } 32 public int getHealth(){ 33 return this.health; 34 } 35 public void setLove(int love){ 36 if(love>100||love<0){ 37 System.out.println("寵物親密度輸入有誤,系統默認將親密度設定為60"); 38 this.love=60; 39 }else{ 40 this.love=love; 41 } 42 } 43 public int getLove(){ 44 return this.love; 45 } 46 public Dog(){ 47 48 } 49 50 public Dog(String strain){ 51 this.strain =strain; 52 } 53 public Dog(String name,String strain,int health,int love){ 54 this(strain); 55 this.setName(name); 56 this.setHealth(health); 57 this.setLove(love); 58 59 } 60 public void showInfo(){ 61 System.out.print("我的名字叫"+this.name); 62 System.out.print(",我的品種是"+this.strain); 63 System.out.print(",健康值:"+this.health); 64 System.out.print(",親密度:"+this.love); 65 } 66 67 }
 1 import java.util.Scanner;
 2 public class Test01{
 3     public static void main(String[] args){
 4         Scanner input =new Scanner(System.in);
 5         System.out.println("請輸入狗狗的名字:");
 6         String name=input.next();
 7         System.out.println("請輸入狗狗的品種:");
 8         String strain=input.next();
 9         System.out.println("請輸入狗狗的健康值:");
10         int health=input.nextInt();
11         System.out.println("請輸入狗狗的親密度:");
12         int love=input.nextInt();
13         Dog dog =new Dog(name,strain,health,love);
14         dog.showInfo();
15     }
16 }

測試結果:

技術分享圖片

技術分享圖片

Java基礎--面向對象編程2(封裝)