2015年8月31日 星期一

Overload 的語法

Java 的 Overload 語法:

import java.util.Scanner;

public class blenderDemo{

 public static void main(String[] args){
 
  Scanner scanner = new Scanner(System.in);
  Blender myBlender = new Blender();
  
  System.out.print("請選擇水果種類:1) 蘋果  2) 香蕉 3) 芒果");
  int fruit = scanner.nextInt();
  
  switch(fruit){
   case 1:
    System.out.printf("蘋果汁:%d CC",myBlender.makeJuice(1));
    break;
   case 2:
    System.out.printf("香蕉牛奶:%d CC",myBlender.makeJuice(2,100));
    break;
   case 3:
    System.out.printf("芒果冰沙:%.2f CC",myBlender.makeJuice(3,100,200));
    break;
  } 
 }
}

public class Blender{

 public int makeJuice(int fruit){
  int juice = 0;
  switch(fruit){
   case 1:
    juice = 150;
    break;
   case 2:
    juice = 300;
    break;
   case 3:
    juice = 400;
    break;
  }   
  return juice;
 }
 
 public int makeJuice(int fruit, int milk){
  return (this.makeJuice(fruit)+ milk);
 }
 
 public double makeJuice(int fruit, int milk, int ice){
  return (this.makeJuice(fruit,milk)+ ice)/2.0;
 }
}