2015年9月2日 星期三

Java 封裝的方法

Encapsulation 的方式:
public class Shirt{

 private int shirtID = 0;
 private String description = "-----";
 
 //public char colorCode = 'U';//Un-encapsulation
 
 private char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
 private double price = 0.0;
 
 public char getColorCode(){
  return colorCode;
 }
 
 public void setColorCode(char newChar){
  switch(newChar){
   case 'R':
   case 'G':
   case 'B':
   case 'W':
     this.colorCode = newChar;
     break;
   default:
   System.out.println("This ColorCode is wrong!");
  }  
 }

 //顯示 Shirt 相關資料
 public void displayInformation(){
 
  System.out.println("Shirt ID: " +  shirtID);
  System.out.println("Description: " + description);
  System.out.println("Shirt Color: " + colorCode);
  System.out.println("Shirt's price: " + price);
 }
}

執行該物件的方法:
public class Demo{

 public static void main(String[] args){
 
  Shirt myShirt = new Shirt();
  
  //myShirt.colorCode = 'B';
  myShirt.setColorCode('B');
    
  System.out.println("ColorCode: " + myShirt.getColorCode());
 
 }
}