Java中对象类型的强制转换

Java中对象类型的强制转换

class person  
  1. {  
  2.     void f1()  
  3.     {  
  4.         System.out.println("person f1 is calling !");  
  5.     }  
  6.     void f2()  
  7.     {  
  8.         f1();  
  9.     }  
  10. }  
  11.   
  12. class student  extends person  
  13. {  
  14.     void f1()  
  15.     {  
  16.         System.out.println("student f1 is calling! ");  
  17.     }  
  18.     void f3()  
  19.     {  
  20.         System.out.println("student f3 is calling!");  
  21.     }  
  22.     void f4()  
  23.     {}  
  24. }  
  25. class Rt20  
  26. {  
  27. public static void main(String[]args)  
  28.     {  
  29.         student s=new student();  
  30.         call(s);  
  31.     }  
  32.     public static void call(person p)//子类的对象可以自动转换为父类的对象.   
  33.     {  
  34.         if(p instanceof student)//这句意思:p确实是student的对象吗.   
  35.         {  
  36.         student s=(student)p;//把person类型强制转换为student类型.   
  37.         s.f1();  
  38.         s.f2();  
  39.         s.f3();   
  40.         }  
  41.         else   
  42.         {  
  43.         p.f1();  
  44.         p.f2();  
  45.         }  
  46.         //p.f4();//p只能调用person类的内容,虽然说p来源于student .但是它带上person类的   
  47.         //帽子,所以只能调用person类的成员.   
  48.     }  
  49. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值