下面是简单的一个Demo
/*
测试子父类之间的转换
*/
class grandfather
{
void iamgrandfather(){
System.out.println("i am grandfather");
}
}
class father extends grandfather
{
void iamfather(){
System.out.println("i am father");
}
}
class son extends father
{
void iamson(){
System.out.println("i am son");
}
}
class brother extends father
{
void iambrother(){
System.out.println("i am brother");
}
}
class Demo
{
public static void main(String[] args)
{
//father直接转换为son
//转换结果:失败
//son s = (son)new father();
//son先转换为father,再从father重新转换为son。
//转换结果:成功
//father f = new son();
//son s = (son)f;
//s.iamson();
//brother先转换为father,再从father转换为son
//转换结果:失败
//father f = (father) new brother();
//son s = (son)f;
//son直接转换为father
//转换结果:成功,且不需要强制类型转换
//但是不能再直接引用子类的方法。
//father f = new son();
//f.iamfather();
//f.iamson();//找不到iamson();
//son先转换为grandfather,再转换为father
//转换结果:成功
grandfather gf = (grandfather) new son();
gf.iamgrandfather();
father f = (father)gf;
f.iamfather();
son s = (son)f;
s.iamson();
}
}