日期:2014-05-20  浏览次数:20594 次

请教一个上转型对象的问题
将子类的实例赋值给父类的引用 有实际引用过程中有什么作用

------解决方案--------------------
可以方便方法的编写,让方法面向父类进行编写,而适用于所有子类
------解决方案--------------------
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好好看一下注释部分,也许能帮你解除疑惑
------解决方案--------------------
方法是用子类的。
数据是用父类的。
------解决方案--------------------
通常我们希望返回的接口更加抽象,而不希望调用者了解接口实现的细节。