2015年9月2日 星期三

Java 繼承方式

利用繼承來減少程式碼:
public class Clothing{

 private int shirtID = 0;
 private String description = "-----";
 private char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
 private double price = 0.0;
 
 //constructors
 public Clothing(int shirtID, String description, char colorCode, double price){
  setShirtID(shirtID);
  setDescription(description);
  setColorCode(colorCode);
  setPrice(price);
 }
 public void setPrice(double price){
  this.price = price;
 }
 public double getPrice(){
  return this.price;
 }
 public void setDescription(String content){
  this.description = content;
 }
 public String getDescription(){
  return this.description;
 }
 public void setShirtID(int shirtID){
  this.shirtID = shirtID;
 }
 public int getShirtID(){
  return this.shirtID;
 }
 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 display(){
 
  System.out.println("Cloth ID: " +  shirtID);
  System.out.println("Description: " + description);
  System.out.println("Cloth Color: " + colorCode);
  System.out.println("Cloth's price: " + price);
 }
}

Shirt 繼承 Clothing 的方式:

public class Shirt extends Clothing{

 private char fit = 'U'; //'S','M','L'
 
 //constructors
 public Shirt(int shirtID, String description, char colorCode,
              double price, char fit){
  super(shirtID,description,colorCode,price);
  setFit(fit);
 }
 public char getFit(){
  return fit;
 }
 public void setFit(char newFit){
  switch(newFit){
   case 'S':
   case 'M':
   case 'L':
   this.fit = newFit;
   break;
   default:
   System.out.println("This Fit is wrong!");
  }
 }
 //Overriding Clothing display method
 public void display(){
  System.out.println("Shirt ID: " +  getShirtID());
  System.out.println("Description: " + getDescription());
  System.out.println("Shirt Color: " + getColorCode());
  System.out.println("Shirt's price: " + getPrice());
  System.out.println("Shirt Fit: " + getFit());
 }
}

執行方式:
public class Demo{

 public static void main(String[] args){
 
  Shirt myShirt = new Shirt(
      321,"NET new Shirt Style!",'B',121.22,'L');
  
  myShirt.display();
 }
}