将子类的实例赋值给父类的引用  有实际引用过程中有什么作用

解决方案 »

  1.   

    class pre extends Premium{
    public pre(String str){
    super(str);
    }
    public String toString(){
    return "pre  "+this.str;
    }
    }public   class   Premium   {
    public String str;
    public Premium(String str){
    this.str=str;
    }
    public String toString(){
    return "Premium  "+this.str;
    }
    public static void main(String[] args) {
    pre p=new pre("pre");
    Premium pre=new Premium("Premium");
    System.out.println(p);
    System.out.println(pre);
    System.out.println();
    pre p1=new pre("pre");
    Premium pre1=new pre("pre");//此为向上转型,这里涉及到多态,在运行时将使用子类方法
    System.out.println(p1);
    System.out.println(pre1);
    System.out.println();
    pre p2=new pre("pre");
    Premium pre2=new Premium("Premium");
    pre2=p2;                    //此为子类引用赋值给父类引用
    System.out.println(p2);
    System.out.println(pre2);
    }
    }
    希望LZ好好看一下注释部分,也许能帮你解除疑惑