`

Java 动态绑定

    博客分类:
  • Java
阅读更多

代码:

 

public class Parent {
 
    public void validate(){  
             System.out.println("parent validate");
             customer();
             customer("ssssss");  
 }
    public void customer(){  
            System.out.println("parent customer");  
 }
     public void customer(Object s){  
            System.out.println("parent customer string");  
 }
    public void shout(Object word){   
            System.out.println("parent string shout:"+word);;  
    }  

  
}

 

public class Child extends Parent
 
   /* public void validate(){  
      System.out.println("child validate");
       customer();  
 }*/
    public void customer(){  
             System.out.println("Child customer");  
 }
    public void customer(String s){
  
            System.out.println("Child customer string");
  
 }
 
    public void shout(String word){  
               System.out.println("Child string shout:"+word);;  
    } 
}

 

 public static void main(String[] args) {
       Parent c= new Child();
       c.validate();
      
      
       Child son=new Child();;  
       Parent father = son;           
       son.shout("hello");;  
       father.shout("hello");
      
      
       String s="  String test";
       Child son2=new Child();;  
       Parent father2=son2;            
       son2.shout(s);;  
       father2.shout(s);
      
       Object s3=null;
       Child son3=new Child();;  
       Parent father3=son3;           
       son3.shout(s3);;  
       father3.shout(s3);
      
       String s4=null;
       Child son4=new Child();;  
       Parent father4=son4;           
       son4.shout(s4);;  
       father4.shout(s4);
      
       Collection cl=new LinkedList();
       cl.add("www");
       cl.add("jjjj");
       cl.add("kkk");
       List l=(List)cl;
       int i=1;
       System.out.println(cl.remove(i));//???为什么返回false,而不实现动态绑定;
       System.out.println(l.remove(i));

    }

 

 

什么是多态的动态绑定?当父类引用指向子类对象的时候,能调用子类中所覆盖的父类方法,可是怎样才是覆盖呢?答案是函数签名相同。
Collection 中有boolean remove(Object o)方法,而List有E remove(int index)和boolean remove(Object o);其中E remove(int index)并没有覆盖Collection中的任何方法,它和boolean remove(Object o)只是函数名字相同而函数签名不同(参数类型不同)。

当你调用c.remove(i)的时候,在Collection接口中只找到了boolean remove(Object o)符合函数声明,于是实际上动态绑定了LinkedList的boolean remove(Object o),并将i自动装箱成Object类型,返回值当然是boolean值了。
而当你调用l.remove(i)的时候,他根据参数类型在List接口找到最适合的函数是E remove(int index),于是绑定了LinkedList的E remove(int index)方法,返回了对象的值。

对象C的声明是一个Collection的接口,而Collection接口中的remove方法的是这样的
 boolean remove(Object o);
而对象l的声明是一个List接口,List接口是扩展自Collection接口的.
在List接口中的remove方法有
E remove(int index);
boolean remove(Object o);

所以,你的代码中的C对象调用的remove方法中LinkedList中的 boolean remove(Object o);
返回的是Boolean类型
而l对象调用的是remove方法是LinkedList中的E remove(int index);返回的是移除的对象
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics