資策會|JAVA|封裝

什麼是封裝?
目的是在於提升資料存取安全性與隱藏資料
為甚麼要這樣做?
避免出包!!
................................

封裝基本概念

JAVA資料封裝的基本就是類別(class),然後使用private , default , protected , public四種存取修飾子作為封裝權限的等級。

直接看扣吧!


阿文開了一家文具店,只賣筆!然後自己設計了一個標價系統!!

public class PenNG {
  public String brand = "A Min Brand"; 
  public double price = 0.0;
  public void show() {
    System.out.println("Brand is : " + brand);
    System.out.println("Price is : " + price);
  }
 }
程式完成囉!準備開業!為了慶祝開幕,一支筆10塊!!

public class PenTest {
 public static void main(String[] args) {
  PenNG p = new PenNG();
  p.price = -10;
  p.show();
 }
}
人生就是這個but! 標錯價啦! 結過造成生意火爆,大賣5000支,賠了五萬元,打響名號!! 可喜可賀!
Brand is : A Min Brand
Price is : -10.0
於是阿明決定google爬文,修正錯誤,不讓錯誤一再發生。
public class PenGood {
 private String brand;
 private double price;
 
 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 }
 public double getPrice() {
  return price;
 }
 public void setPrice(double price) {
  if(price > 0)
   this.price = price;
  else
   System.out.println("請確認售價設定");
 }
 public void show() {
  System.out.println("Brand is : " + brand);
  System.out.println("Price is : " + price);
 }
}
不長記性!差點又出包。
public class PenTest {
 public static void main(String[] args) {
  PenGood p = new PenGood();
  p.setBrand("A Min Brand");
  p.setPrice(-10);
  p.show();
  
  System.out.println("好險有提醒,重新調整售價囉!");
  p.setPrice(25);
  p.show();
 }
}
感恩讚嘆!筆出去,錢進來,阿明發大財!
請確認售價設定
Brand is : A Min Brand
Price is : 0.0
好險有提醒,重新調整售價囉!
Brand is : A Min Brand
Price is : 25.0

究竟,阿明是怎樣解決問題的呢?

阿明三部曲

  • private
  • public getXXX
  • public setXXX

留言