java中转型(upcasting)与动态绑定(dynamic binding)或者后期(late binding)细节

    技术2024-11-04  23

    from: http://blog.csdn.net/kaiming2008/archive/2007/04/27/1587843.aspx

     

    在Java中,父类与子类之间的类型转换有两种,一种是子类向上转型父类(这永远是安全的),另一种是父类向下转型为子类(这得由相应的instanceof来判断数据类型,同时这也是一种不安全的转换)

     

    Base class 与derived class 之间,为了达到从一个特定类型转为一个通用类型(有点多态的味道),可以借助向上]转型这一工具(即子类向上转为父类类型的),因为Java 里的对象引用都是dynamic binding或者lated bindin或者runing time binding,缺点就是在向上转型的过程中会丢失了属于子类专用的方法 ;向下转型中用得最多的就是interface的运用.

     

    下面用一段代码讲示:

     class Base {  public void baseMethod()  {   System.out.println("into Base#baseMethod");   }   public void fuc()  {    System.out.println("into Base#fuc");   }  }

    class Child extends Base {  public void childMethod()  {   System.out.println("into Child#childMethod");   }    public void fuc()  {   System.out.println("into Child#fuc");    }   }

    class CCChild extends Child {  public void ccchildMethod()  {   System.out.println("into CCChild#ccchildMethod");   }    public void fuc()  {   System.out.println("into CCChild#fuc");    }   }

    class DChild extends CCChild {  public void dchildMethod()  {   System.out.println("into DChild#dchildMethod");   }    public void fuc()  {   System.out.println("into DChild#fuc");    }   }

     

    public class DynamicBindingTest {  public static void main(String[]args)  {   Base bs =new Child();   bs.fuc();//dynamic binding derived Child so call Child#fuc   // bs.childMethod();//error:this method has been lost when upcasting to base class Base       Base cbs =new CCChild();   cbs.fuc();   // bs.ccchildMethod();//error:this method has been lost when upcasting to base class Base    System.out.println("=================");   Child c=new Child();   CCChild ccc=new CCChild();   DChild dc=new DChild();   testCall(c);   testCall(ccc);   testCall(dc);  }    static void testCall(Base b)  {   b.fuc();  }   } 控制台打印出来的结果

    into Child#fuc into CCChild#fuc ================ into Child#fuc into CCChild#fuc into DChild#fuc

    最新回复(0)