向上转型,向下转型

要给学生们讲卷子,不知道这个转型问题怎么讲,搜了几个例子,才发现这个例子最合适,也好懂。

ExpandedBlockStart.gif ContractedBlock.gif class    Chinese dot.gif {   
InBlock.gif            
ExpandedSubBlockStart.gifContractedSubBlock.gif          
public   static   void   print()dot.gif{   
InBlock.gif                  System.out.println(
"this   is   中国人");   
InBlock.gif                    
ExpandedSubBlockEnd.gif          }
   
InBlock.gif          
ExpandedBlockEnd.gif  }
   
ExpandedBlockStart.gifContractedBlock.gif  
class    Guangdongren    extends    Chinese dot.gif {   
ExpandedSubBlockStart.gifContractedSubBlock.gif          
public   static   void   print()dot.gif{   
InBlock.gif                  System.out.println(
"this   is   广东人   ");   
ExpandedSubBlockEnd.gif          }
   
InBlock.gif            
ExpandedBlockEnd.gif  }
   
ExpandedBlockStart.gifContractedBlock.gif  
class    HunanRen    extends    Chinese dot.gif {   
ExpandedSubBlockStart.gifContractedSubBlock.gif          
public   static   void   print()dot.gif{   
InBlock.gif                  System.out.println(
"this   is   湖南人   ");   
ExpandedSubBlockEnd.gif          }
   
ExpandedBlockEnd.gif  }
   
ExpandedBlockStart.gifContractedBlock.gif  
class    GuangzhouRen    extends    Guangdongren dot.gif {   
ExpandedSubBlockStart.gifContractedSubBlock.gif          
public   static   void   print()dot.gif{   
InBlock.gif                  System.out.println(
"this   is   广州人     ");   
ExpandedSubBlockEnd.gif          }
   
ExpandedBlockEnd.gif  }
   
None.gif    
ExpandedBlockStart.gifContractedBlock.gif  
public     class    Test    dot.gif {   
InBlock.gif            
ExpandedSubBlockStart.gifContractedSubBlock.gif            
public   static   void   main(String   args[])dot.gif{   
InBlock.gif                      
InBlock.gif                    Chinese   c
=new   Chinese();//这样编译可以通过,但运行会抛出异常   
InBlock.gif
                      HunanRen   h=(HunanRen)c;//     这是因为向下转型错误,中国人不一定是湖南人,这里   
InBlock.gif                                                                    
//是不是可以这样理解要将c强制转换成一个HunanRen     
InBlock.gif
                      
InBlock.gif                    HunanRen   h
=new   HunanRen();//这样就没有问题,这是向上转型,   
InBlock.gif
                    Chinese   c=(Chinese)h;         //湖南人一定是中国人这是是否可以理解为将h转换成Cinese   
InBlock.gif
                Chinaese   h=new   HunanRen();//向上转型   
InBlock.gif
                    h.print();   
ExpandedSubBlockEnd.gif            }
   
ExpandedBlockEnd.gif      }
   
None.gif

转载于:https://www.cnblogs.com/mgod/archive/2007/07/12/815178.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值