2015年9月16日 星期三

Polymorphism 用法

Polymorphism (多型)用法:
public class Employee {

    //....參考這一篇內容.....
     protected int calculateStock() {
        return 10;
    }
}

public class Manager extends Employee{

    //....參考這一篇內容.....
    public int calculateStock() {
        return 20;
    }
}

新的類別:
public class EmployeeStackPlan {

    private float stockMultiplier = 1.5f;

    // 使用父類別當引數:
    public int grantStock (Employee e){
        return (int)(stockMultiplier * e.calculateStock());
    }
}

執行的執行:
public class Demo {
    public static void main(String[] args){
    
    Employee e = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);    
    Manager m = new Manager(102, "Joan Kern", "012-23-4567",110_450.54, "Marketing");
    Employee em = new Manager(103, "Williams Tim", "014-87-5679",123_560.54, "Production");

    System.out.println("Stock: " + e.calculateStock());
    System.out.println("Stock: " + m.calculateStock());
    System.out.println("Stock: " + em.calculateStock());