java的前期绑定和后期绑定使用示例

2022-10-20,,,

后期绑定,是指在运行时根据对象的类型进行绑定,又叫动态绑定或运行时绑定。实现后期绑定,需要某种机制支持,以便在运行时能判断对象的类型,调用开销比前期绑定大。
java中的static方法和final方法属于前期绑定,子类无法重写final方法,成员变量(包括静态及非静态)也属于前期绑定。除了static方法和final方法(private属于final方法)之外的其他方法属于后期绑定,运行时能判断对象的类型进行绑定。验证程序如下:

复制代码 代码如下:
class base
{
    //成员变量,子类也有同样的成员变量名
    public string test="base field";
    //静态方法,子类也有同样签名的静态方法
    public static void staticmethod()
    {
        system.out.println("base staticmethod()");
    }
    //子类将对此方法进行覆盖
    public void notstaticmethod()
    {
        system.out.println("base notstaticmethod()");
    }

}
public class derive extends base
{
    public string test="derive field";
    public static void staticmethod()
    {
        system.out.println("derive staticmethod()");
    }
    @override
    public void notstaticmethod()
    {
        system.out.println("derive notstaticmethod()");
    }
    //输出成员变量的值,验证其为前期绑定。
    public static void testfieldbind(base base)
    {
        system.out.println(base.test);
    }
    //静态方法,验证其为前期绑定。
    public static void teststaticmethodbind(base base)
    {
        //the static method test() from the type base should be accessed in a static way
        //使用base.test()更加合理,这里为了更为直观的展示前期绑定才使用这种表示。
        base.staticmethod();
    }
    //调用非静态方法,验证其为后期绑定。
    public static void testnotstaticmethodbind(base base)
    {
        base.notstaticmethod();
    }
    public static void main(string[] args)
    {
        derive d=new derive();
        testfieldbind(d);
        teststaticmethodbind(d);
        testnotstaticmethodbind(d);
    }
}
/*程序输出:
base field
base staticmethod()
derive notstaticmethod()
 */

《java的前期绑定和后期绑定使用示例.doc》

下载本文的Word格式文档,以方便收藏与打印。