2015年8月19日 星期三

Java 物件內的變數宣告

Java 物件內的變數分成 Fields 與 Local Variables ,兩者有不同的地方:
public class Shirt{

 //這是 Fields
 public int shirtID = 0;
 public String description = "-----";
 public char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
 public double price = 0.0;
 
 //顯示 Shirt 相關資料
 public void displayInformation(){
 
  System.out.println("Shirt ID: " +  shirtID);
  displayDescription(this.description);
  System.out.println("Shirt Color: " + colorCode);
  System.out.println("Shirt's price: " + price);
 }

 public static void displayDescription(String d1){
   //這是Local Variables
   String displayString = "";
   displayString = "Shirt description: " + d1;
   System.out.println(displayString);
 } 
}
Java 物件的變數名稱,可以利用物件來指派與修改!
public class Demo{

 public static void main(String[] args){
 
  Shirt myShirt = new Shirt();
  myShirt.shirtID = 100;
  myShirt.colorCode = 'B';
  myShirt.price = 45.12;
  myShirt.description = "45周年紀念衫";
  
  myShirt.displayInformation();
 
 }
}