Java中对象类型的强制转换

来源:互联网 发布:绒面和磨砂区别知乎 编辑:程序博客网 时间:2024/05/22 13:20

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. }  
原创粉丝点击