public class father {
public void method( father n){
System.out.println("this is father method use father parameter");
}
public void method( child n){
System.out.println("this is child method use child parameter");
}
}
class child extends father
{
public void method( father n){
System.out.println("this is child method use father parameter");
}
public void method( child n){
System.out.println("this is child method use child parameter");
}
public static void main(String[] args)
{
child childVariable = new child( );
father fatherVariable=childVariable; //upcasting
fatherVariable.method( fatherVariable );//会调用子类的method,因为存储的reference
// address是子类的object
//并且优先调用的是当前object类型(father)
//为parameter的method
childVariable=(child)fatherVariable;//downcasting,当且仅当还原数据类型时使用
childVariable.method(childVariable);//会调用子类的method,因为存储的reference
// address是子类的object
//并且优先调用的是当前object类型(child)
//为parameter的method
father fatherVariable2=new father();
child childVariable2=(child)fatherVariable2; //报错,因为是downcasting
}
}
upcast和downcast的作用
于 2019-10-06 22:53:19 首次发布