zoukankan      html  css  js  c++  java
  • 关于JAVA中的前期绑定 后期绑定(动态绑定)

    前期绑定,在程序执行前根据编译时类型绑定,调用开销较小,如C语言只有前期绑定这种方法调用。
      后期绑定,是指在运行时根据对象的类型进行绑定,又叫动态绑定或运行时绑定。实现后期绑定,需要某种机制支持,以便在运行时能判断对象的类型,调用开销比前期绑定大。

          Java中的static方法和final方法(private属于final方法,详细的解释见《Java编程思想》)属于前期绑定,子类无法重写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()
     */
    复制代码
  • 相关阅读:
    python中os.listdir( )函数读取文件夹
    斐讯k2p 月光银 硬件版本A2-软件版本22.7.8.5 刷官改系统
    Ubuntu 16.04 换国内源
    pip和apt-get换源
    Python-OpenCV中的filter2D()函数
    Python-OpenCV中图像合并显示
    Python-OpenCV——Image Blurring(Image Smoothing)
    Python-OpenCV中的resize()函数
    删除Chrome地址栏记录中自动补全的网址
    Python中Numpy mat的使用
  • 原文地址:https://www.cnblogs.com/the-wang/p/6915034.html
Copyright © 2011-2022 走看看