Posts Tagged ‘ 多态 ’


Java查漏补缺1-Binding时间

在编程语言中,有两种binding方式,一是在compile期间binding,被称作Early-binding,一种是在execute期间binding,被称作Late-binding。
在Java中,更多的采用的是Late-binding这种方式。要做一个比较好的解释,可以看看关于继承的例子。以下这段代码显示了一个很简单的继承关系,父类是Shape,子类是Circle和Rectangle,其中分别实现了各自的draw()方法。

public class Shape {
    public void draw(){
        System.out.println("Draw shape");
    }
}

public class Circle extends Shape{
    public void draw(){
        System.out.println("Draw circle");
    }
}

public class Rectangle extends Shape{
    public void draw(){
        System.out.println("Draw rectangle");
    }
}

public class Test {
    public static void main(String[] args){
            Shape shape = new Shape();
            shape.draw();
            Shape shape1 = new Rectangle();
            shape1.draw();
            Shape shape2 = new Circle();
            shape2.draw();
        }
}

在以上的示例中,我们在main函数中看到生成了三个分别是以上三个类的实例,但是它们共用了同样的Shape声明。这也就是Java最重要的多态的之所在。不过不是本文的重点,略过。我们发现既然三个实例享有同样的声明,在编译期间,编译器是无法判断到底每一个实例属于的是哪一个类,需要调用的是哪一个draw方法。而在执行期间,run-time会自动根据new关键字对应的类型,将其binding上。这就是所谓的late-binding。在传统的大多数非OOP语言中,early-binding占据绝大多数。总之,early-binding意味着在程序编译期间,运行时系统将确定需要调用的函数的地址,而late-binding则会在系统运行时根据当时情况动态决定。(在C++中,也支持类似的late-binding,不过需要显示的加以virtual关键字)

  • English Version

    • Cannot read Chinese? Please take a look at my English site, hope you can find more you need there!
  • 感谢支持

  • twitter

    facebook

    linkedin

  • Categories