码迷,mamicode.com
首页 > 编程语言 > 详细

java 父类对象 和 子类对象 的类型转换

时间:2019-12-18 10:53:34      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:类型   subclass   this   error   ati   static   exception   父类   mpi   

/**
 * 父类对象 和 子类对象  的类型转换
 */
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;
    }
}

java 父类对象 和 子类对象 的类型转换

标签:类型   subclass   this   error   ati   static   exception   父类   mpi   

原文地址:https://www.cnblogs.com/billxxx/p/12058490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!