java 父類對象 和 子類對象 的類型轉換


/**
 * 父類對象 和 子類對象  的類型轉換
 */
public class TypeCast{
    public static void main(String[] args){
        Employee[] staff = new Employee[3];
        staff[0] = new Employee();
        System.out.println(staff[0]);
        System.out.println(staff[1]);

        //Manager boss0 = staff[0];  //java.lang.Error: Unresolved compilation problems:
                                     //Type mismatch:cannot convert from Employee to Manager

        //Manager boss0 = (Manager)staff[0]; //ClassCastException: Employee cannot be cast to Manager
        Manager boss0 = (Manager)staff[1];  //staff[1] is null, can give to boss0
        System.out.println(boss0);

        Manager boss = new Manager();
        System.out.println(boss);

        staff[0] = boss;  // subclass object assign to reference
        System.out.println(staff[0]);
    }
}

class Employee{
    private String name;
    public Employee(){
        this("emplyee");
    }
    public Employee(String name){
        this.name = name;
    }
    public String toString(){
        return name;
    }
}

class Manager extends Employee{
    private int bonus;
    public Manager(){
        super("manager");
        bonus = 1;
    }
    public String toString(){
        return super.toString() + " " + bonus;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM