2015年9月14日 星期一

物件與多型

Java 多型 (Polymorphism) 的使用:
範例:Employee
public class Employee {
    
    private int empId;
    private String name;
    private String ssn;
    private double salary;

    public Employee() {
    }

    public Employee(int empId, String name, String ssn, double salary) {
        this.empId = empId;
        this.name = name;
        this.ssn = ssn;
        this.salary = salary;
    }

    //......一堆 getter 與 setter ......

   public void raiseSalary(double increase){
        salary += increase;
    }

}

Manager 繼承 Employee :
public class Manager extends Employee{
    
    private String deptName;

    public Manager() {
    }

    public Manager(int empId, String name, String ssn, double salary, String deptName) {
        //super();
        super(empId, name, ssn, salary);
        this.deptName = deptName;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }   
}

最後來個大Demo :
public class Demo {
    public static void main(String[] args){
    
        Manager mgr = new Manager(102, "Barbara Jones", "107-99-9078", 109345.67, "Marketing");
        mgr.raiseSalary(10000.00);
        String dept = mgr.getDeptName();
        
        Employee emp = new Manager();
        //錯誤
        //emp.setDeptName("Marketing");
        ((Manager)emp).setDeptName("Marketing");
    }
}